Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to add @login_required error message
I'm using the @login_required decorator for my webapp and I've set it so that when a user tries to access the index without being logged in, he is redirected to the login page. I'd like to display an error message whenever the user is redirected to this login page. I've tried using the source code of the @login_decorator and creating my own with: def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: messages.success(request, 'Error message here') return actual_decorator(function) return actual_decorator However this doesn't work. I've also tried multiple solutions which rely on available_attrs which is no longer supported by Django. Is there a way to solve this? Thanks in advance -
Creating models.UniqueConstraint in django, but the constraint is not applying
My table is defined as below. class Role(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, to_field="email", db_column="user", on_delete=models.CASCADE ) vertical = models.ForeignKey( Verticals, to_field="name", db_column="vertical", on_delete=models.CASCADE ) product_domain = models.ForeignKey( ProductDomains, to_field="name", db_column="product_domain", null=True, on_delete=models.CASCADE ) class Meta: constraints = [ models.UniqueConstraint(fields=[ 'user', 'vertical', 'product_domain' ], name='unique-permissions-per-user') ] Here the UniqueConstraint is not working, why? I use models.UniqueConstraint in the same project many times but it doesn't work in this case. My configuration is Django - 3.0.4 Django Rest Framework - 3.11.0 Database - MySql Please help and ask if any information is missing out. -
How to set data type of path parameter in drf-yasg
I use Django, the DRF, drf-yasg and Swagger Codegen to automatically build TypeScript code to access my REST API. In the Django backend I added a path to be served with the DRF: rest_router = routers.DefaultRouter() rest_router.register(r'source/(?P<source_id>[0-9]+)/document', DocumentViewSet) DocumentViewSet is a DRF ModelViewSet. As you can see, the source_id parameter is of numeric type. However, the resulting generated API description defines the source_id parameter as type String. Obviously the numeric regexp in the path setting is not enough so I guess I need some type annotation in the DocumentViewSet class? I tried the following code, but this showed no effect: @swagger_auto_schema( manual_parameters=[ openapi.Parameter(name="source_id", required=True, type="integer", in_="path", description="Source reference", ), ], ) class DocumentViewSet(viewsets.ModelViewSet): serializer_class = rest_serializers.DocumentSerializer queryset = models.Document.objects.all().order_by('id') How can I tell drf-yasg to set the source_id parameter to type Integer? -
removed column from postresql, but django doesn't see it
I removed the column from postresql database by using sql statement (alter table table_name drop column if exists column_name); It removed it... But django model doesn't see it... I tried "syncdb", but it is deprecated, so no more functional, tried makemigrations and migrate, but it doesn't change models in django... It should be quite simple task? Since it should be normal to change database (if not primary or foreign keys)... but nothing I tried works for me and there are seems no answer for this questions... fake migrations wouldn't be good for database, and turning off django changing database is not an option also? And because I have django and postresql not synced, I have filter fault which comes up... Any help? Thank you! -
Using Crispy Forms on Django how do I add an address field?
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2', ) def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] -
Use the value of an input field in calculation, and display the result in another element
I have a shopping cart, with a price, quantity, and subtotal field for each product. The quantity field can be changed by the user, but the other fields are static. Is there a way to calculate the subtotal when the quantity is changed by the user? I want to multiply the quantity with the price, then update the subtotal, without the need for the user to submit the form. Also, when a subtotal is calculated, the total should be updated as well. Visual representation here My code is a Django template and looks like this, with the relevant part in the loop: <div class="container"> <table id="cart" class="table table-hover table-condensed"> <thead> <tr> <th style="width:50%">Product</th> <th style="width:10%">Price</th> <th style="width:8%">Quantity</th> <th style="width:22%" class="text-center">Subtotal</th> </tr> </thead> {% for crops_ordered_names,crops_ordered_images,crops_ordered_cost,crops_ava in total %} <tbody> <tr> <td data-th="Product"> <div class="row"> <div class="col-sm-2 hidden-xs"><img src="http://placehold.it/100x100" alt="..." class="img-responsive"/></div> <div class="col-sm-10"> <h4 class="nomargin">{{crops_ordered_names}}</h4> <p>Available amount: {{crops_ava}}</p> </div> </div> </td> <td data-th="Price" id="price">{{crops_ordered_cost}}</td> <td data-th="Quantity"> <input type="number" class="form-control text-center" id="quan" min="1" max="{{crops_ava}}"> </td> <td data-th="Subtotal" class="text-center" id="subtotal"></td> <td class="actions" data-th=""> <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button> </td> </tr> </tbody> {% endfor %} <tfoot> <tr class="visible-xs"> <td class="text-center"><strong>Total 1.99</strong></td> </tr> <tr> <td colspan="2" class="hidden-xs"></td> <td class="hidden-xs text-center" id="total"><strong>Total </strong></td> </tr> </tfoot> … -
Does Django have a built-in application for location awareness?
I will be asking users when signing up to provide their location. Does Django have a built-in application for this? If not, can anyone recommend a third-party package? The idea is for users to search for other users based on a certain mile range. -
How to redirect from a Django View to some other view
For example if I have a view where I do some conversion according to the text-box input. Then I want to redirect to somewhere after the conversion is done, where the user can see the results. def main(){ //Some Conversion going on // After the conversion is done redirect to somewhere else if(conversion == done): return redirect('/somewhere') return render('index.html') } -
Efficiently update multiple fields in Django
Django beginner here. I have a many-to-many model and want to update multiple values at once. This is the model (simplified): class Inventory(models.Model): item = models.ForeignKey(Items, models.CASCADE) player = models.ForeignKey(Players, models.CASCADE) count = models.PositiveIntegerField() What I do right now is this: for key in dict: change_value = Inventory.objects.get(player=player, item=key) change_value.count += dict[key] change_value.save() At least on my HDD test environment this is very slow. Is there a more efficient way of doing this? In other posts it was suggested to use update instead, so this would be: for key in dict: Inventory.objects.get(player=player, item=key).update(count=dict[key]) Would this be faster? Could this be improved even further by updating multiple entries at once? Also, is there an efficient way of adding multiple new entries? -
How to override river-admin template?
Firstly , i would like to say that this package is amazing in the sense where there can be so much flexibility. Im relatively new to this package and im just trying to figure a way to fiddle around with the provided front end in the river-admin package. Could someone point me in the correct direction in doing so? -
Django, environment variables. Error: SMTPRecipientsRefused at /password_reset/
it's my first post here. I'm learning Django, and i'm trying to send an email to reset my password. There is one problem.. When I send an email with my username and password assigned to these constants, everything works well: EMAIL_HOST_USER = 'abc.def@gmail.com' EMAIL_HOST_PASSWORD = 'Abc123' But when i try to use environment variables instead: EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') i got an error SMTPRecipientsRefused at /password_reset/ {'abc.def@gmail.com': (501, b': sender address must contain a domain')} Am I doing something wrong? Maybe I should use environment variables in different ways? In advance, thanks for your help, guys! -
can we work with Django authentication without builtin Django forms
I want to use input field for authentication but if I search for authentication tutorial they are using built-in Django forms which I can't design it using html -
how to implement a movie review system using sentimental analysis in python using django
Take a movie as a input from a user and pass it as a argument to our python file and our program will do a sentimental analysis on movie comments and give output wheather a movie is worth watching or not . framework used is django , backend language python and movie reviews collected from rottentomatoes. -
How to specify basehref in Django
Is it possible to launch Django app depending on .env configuration with BASEPATH=/api or just BASEPATH=/? -
404 error when deploying django project with apache2
I tried to create a new django project on apache2, but I got 404 error. Here are what I did. -In /home/ubuntu/django directory, type django-admin startproject proj -Edit proj/proj/wsgi.py as follows. import os import sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') sys.path.append('/home/ubuntu/django/proj'); sys.path.append('/home/ubuntu/django/proj/proj'); application = get_wsgi_application() -Edit ALLOWED_HOSTS in proj/proj/settings.py as follows. ALLOWED_HOSTS = ['example.com'] -Edit /etc/apache2/conf-available/wsgi.conf as follows. WSGIScriptAlias /proj /home/ubuntu/django/proj/proj/wsgi.py WSGIPythonPath /home/ubuntu/django/proj <Directory /home/ubuntu> Require all granted </Directory> <Directory /home/ubuntu/proj/proj> <Files wsgi.py> Require all granted </Files> </Directory> -Restart apache2 as /etc/init.d/apache2 restart -Access to http://example.com/proj, and then got 404 error as follows. Page not found (404) Request Method: GET Request URL: http://example.com/proj/ Using the URLconf defined in proj.urls, Django tried these URL patterns, in this order: admin/ The empty path didn't match any of these. My enviroment is as follows. Ubuntu 18.04 LTS (AWS) Apache/2.4.29 Python 3.6.9 Django 3.0.5 How can I solve this 404 error? -
Django graphql JWT authentication gives anonymous user although valid token is given
I'm following this tutorial on authentication with django-graphql-jwt. I'm failing at step Testing the Authentication. I get a valid token via ObtainJSONWebToken but when I insert this token into the HTTP header authorization and perform a query (me) that checks the user status it gives an anonymous user. When I am logged in via django admin page it works without any token. It seems like the middleware is not working properly but that is just a guess. Here my code and what I do: settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] GRAPHENE = { 'SCHEMA': 'schema.py', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware' ] } schema.py class Query(teamorgaisation_queries.Query, users_queries.Query, graphene.ObjectType): # this class inherits multiple Queries as we add more apps with their own schema pass class Mutation(teamorganisation_mutations.Mutation, users_mutations.Mutation, graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() me-query import graphene from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from voss_be_django.users.graphql.types import UserType class Query(graphene.ObjectType): me = graphene.Field(UserType) def resolve_me(self, info): user = info.context.user if user.is_anonymous: raise Exception('Not logged in!') return user Postman query without authorization header: mutation tokenAuth($username: String!, $password: String!){ tokenAuth(username: $username, password: $password){ token } } variables: { "username": "testUser", "password": "UserTest#1234" } response (inside … -
Django static url with digitalocean spaces
I have an droplet on digitalocean which for the most part is working great, however i have enabled the cdn option in digitalocean spaces (similar to aws s3 storage) and in trying to load static files using the cdn url, i cannot seem to get the url working correctly so suspect i am missing the obvious? For example when i change the STATIC_URL in settings to the cdn no change is seen in the web page source? If i change the AWS_S3_ENDPOINT_URL and MEDIA_ENDPOINT_URL then the source does change but the files are not found and as one can guess a collectstatic no longer works, So i assume that the AWS_S3_ENDPOINT_URL & MEDIA_ENDPOINT_URL need to remain as is and i merely need to ensure the static_url is used? I did read somewhere that it was not good practice to change the templates from {%static.... to {%static_url so have not done that, is this something i should update or not? Settings: AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com' MEDIA_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com/media/' AWS_STORAGE_BUCKET_NAME = 'mysitestaging' #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # if False it will create unique file names for every uploaded file AWS_S3_FILE_OVERWRITE = False STATICFILES_STORAGE = 'mysite.settings.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'mysite.settings.storage_backends.MediaStorage' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } … -
How to limits some users to view Django admin content by default permission
Am new to Django I have developed app in Django, when I assign view permission allowed to view content Question is this how can I override default view permission to allow user to his own created content on admin site Any help appreciated -
how does django get_next_by_FOO() query work?
i want to know how get_next_by_FOO()/get_previous_by_FOO() fetch data from database. anyone know the SQL code for that?. can anyone tell me how it works behind the scene? -
Django Authentication - Page redirecting to home even it goes in to exception
I am doing Simple User Registration part of my project, using Django's User table. Which supposed to redirect to home page after successful user registration and its login only, but even though I am filling up duplicate (incorrect)entry for username, its going to home page instead of showing the error on Sign up page. P.S - Tried to keep the question short, not displayed unnecessary code Please do read comments in the code and logs, added extra explanation there def register(request): if request.method == 'POST': reqdict = to_reqdict(request) print("user.is_authenticated", reqdict) # This statement printed in the logs username = reqdict.get('email') first_name = reqdict.get('first_name') last_name = reqdict.get('last_name') raw_password = reqdict.get('password') try: clear_old_sessions(request) user = User.objects.create_user(username=username,first_name=first_name, last_name=last_name,email=username, password=raw_password) user.save() user = authenticate(username=username, password=raw_password) login(request, user) print("user.is_authenticated>>>>>", user.is_authenticated) # This does not get printed in the logs return redirect(reverse('home')) # Only this line redirects page to home page except IntegrityError as e: messages.error(request, "User already exists!") print("error", e) except Exception as e: print("Other error", e) messages.error(request, "User already exists!") return render(request, template_name="signup.html") else: return render(request, template_name="signup.html") See the logs for detail: System check identified no issues (0 silenced). April 13, 2020 - 15:51:54 Django version 3.0.5, using settings 'backend.settings' Starting development server at … -
Change function to class view django
I'm doing a django app and at first I've done methods to my view, but I'd like now to change to class. Here's an exemple of how I tried : def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") else: form = RegisterForm() return render(response, "register/register.html", {"form":form}) And tried to change like this : class RegisterView(generic.View): def post(self, request): form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") else: form = RegisterForm() return render(response, "register/register.html", {"form":form}) But I keep getting a 405 Error Method not allowed, I guess it's because I'm not doing right the changing from method to class. Any idea ? -
How to calculate the value of two html tags and output it to other tag
Is there any way to calculate the subtotal using (price * quantity), quantity is the number tag which needs to be entered by the user. Then all the subtotals should be added to the total. Can this all be done without submitting any form?(Price * quantity = Subtotal) -
Where is Django's own database?
This question asks where the Django installation is. This question is about the table django_migrations. I've looked under the path from the command django in the interactive console, where I find a subdirectory db, along with middleware, etc. But I've no idea where this table django_migrations (i.e. the data in it) is in fact kept. I want to know firstly because I want to know what happens if this data is lost. I'm just learning Django and I don't quite understand how much of a problem this would be. The path to the Django location is under a directory in my home folder where I keep my Python virtual environments, the name of which begins with a ".". I tend to exclude such directories from my backup plans... Having just deleted db.sqlite in my project I see that it gets regenerated when you do migrate, together with a list of (in my present case) some 15 migration operations. I'm quite mystified by some of these: the first 10 or so seem to have occurred before I started doing anything to my models.py file. Are they documented or explained somewhere? -
Managing timer based threads
I'll give some back story for context before the question. I'm currently creating a small Django based web site with some code on the back. This is basically a security scan website, so a Recon module is part of it. A user fills up a form and recon begins. Because many users can access the website at the same time, I handeled the call to recon method with threads, this way more than one user can actually use the website. Something like the following def recon_view(request): if request.method == 'POST': form = ReconForm(request.POST) if form.is_valid(): recon_thread = threading.Thread(name='Recon Process', target=recon.run_recon, args=(form,)) recon_thread.start() The next step is to implement some sort of monitoring mode, from what I have searched, one can use threads this way. threading.Timer(1, foo).start() The recon will run once a week or few days so time is not an issue. Would this be the correct approach? Woulnd't this mean that everytime the user starts a recon, the Thread will continue running basically until the server stops (Meaning possibly hundreds of threads at the same time). The other option I can think of is using a separate script that makes an API call to the website, triggering the recon -
Fetch modal data with Ajax from Django Model
Sorry for repeating this question, and Ajax integration since its very broad subject, but I just can't figure it out. I have a html table with 4k+ rows of data, and each of rows has some basic information like name, address, last name, phone, and a button which triggers a bootstrap modal which contains additional data like phone2, address 2, etc. My problem is, since my modal is located inside a for loop like this - <tbody> {% for opp in optika %} <tr> <td>{{ opp.example }}</td> <td>{{ opp.some_field }}</td> <td> <button id="testbtn" type="button" class="btn btn-success btn-sm btn-detail" data-toggle="modal" data-target="#detalji_modal{{ opp.pk }}" Detalji </button> </td> ... </tr> {% include "opportunity/partials/_detalji_modal.html" %} {% endfor %} </tbody> And this is modal detail - <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" id="detalji_modal{{ opp.pk }}" aria-labelledby="detalji_modalLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="detalji_modalLabel">Detalji</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" id=""> <div class="container-fluid"> <h5>{{ opp.... }}</h5> <p>{{ opp.....title }}</p> ... </div> </div> <div class="modal-footer"> <p style="margin-right: auto">Zahtev uneo/la : {{ opp.... }}</p> ... ... <button type="button" class="btn btn-outline-primary" data-dismiss="modal"> Close </button> </div> </div> </div> </div> I'll pass the view also : @login_required(login_url='registration/login') def OptikaList(request): user_groups = request.user.groups.all() …