Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Authentication Form not working properly
I am trying to create a very basic login system (just to grasp Django's authentication system, nothing fancy). Thing is, when I use the following code (i.e. don't validate authentication form submission), everything works perfectly. The views.py file: from django.shortcuts import render, redirect from django.http import request from django.contrib.auth.decorators import login_required from .forms import UserRegistrationForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import AuthenticationForm @login_required(login_url="accounts/login") def home(request): return render(request, "main/home.html") def register_user(request): if request.method == "POST": reg_form = UserRegistrationForm(request.POST) if reg_form.is_valid(): user = reg_form.save() messages.success(request, f'You have successfully registered!') return redirect("login") else: messages.error(request, "Some problem occured") else: reg_form = UserRegistrationForm() return render(request, template_name='main/register.html', context={"form":reg_form}) def login_view(request): if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = authenticate(request, username = username, password = password) if user is not None: login(request, user) messages.success(request, f"You logged in as: {username}") return redirect("home") else: messages.error(request, "Invalid username or password") return redirect("login") else: auth_form = AuthenticationForm() return render(request, "registration/login.html", context={"form":auth_form}) def logout_request(request): logout(request) messages.success(request, f"You have logged out.") return redirect("login") However, when I insert authentication form validation and population, user is not authenticated and None is returned instead. For the purpose of simplicity I am adding the 'login_view' only … -
Vue Django app Forbidden (CSRF cookie not set.): 403 Forbidden
I suppose this would actually be a django question as I think there's something wrong with the backend. I have my Vue code in frontend/ (127.0.0.1:8080) and django code in backend/ (127.0.0.1:8000). I've followed the django docs on CORS and CSRF Tokens but I get Forbidden (CSRF cookie not set.): when trying to make a post request to the django server. I'm trying to reset password via email. backend/settings.py ... CORS_ALLOW_ALL_ORIGINS = True # If this is used then `CORS_ALLOWED_ORIGINS` will not have any effect CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ 'http://127.0.0.1:8080', ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:8080', ] # SESSION_COOKIE_SAMESITE = 'None' # CORS_ALLOW_CREDENTIALS = True EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_DIR = BASE_DIR / 'emails' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'product', 'order', 'email_app' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... backend/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), path('api/v1/', include('product.urls')), path('api/v1/', include('order.urls')), path('api/v1/', include('email_app.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) backend/email_app/urls.py: from django.urls import path from email_app import views urlpatterns = [ path('reset_password/', views.ResetPasswordEmail), ] backend/email_app/views.py: ... from rest_framework.decorators import api_view from django.views.decorators.csrf import csrf_exempt from .serializers import ResetPasswordEmail @api_view(['POST']) @csrf_exempt def reset_password(request): … -
Get webpage path useing django
When user login iwant to redirect him to user page with the same language This is what i tried to do if request.path == '/classgate/log-ar/' : messages.success(request,f'مرحبا !{request.user.username} استمتع بوقتك') return redirect('user-ar') elif request.path == '/classgate/log/' : messages.success(request,f'Welcome {request.user.username} enjoy your time') return redirect('userr') But when i did it with request.META.get('HTTP-REFERRER') It worked -
When using custom AuthBackend, unable to use request.user.is_authenticated or @login_required decorator
Firstly I'm coming from a PHP background and new to Django. And I'm trying to upgrade a webapp from a PHP framework to Django, keeping the database unchanged. The built-in authentication in Django is bit confusing, as my User table is different to what is expected in django's auth.User modal. In my usecase, I have an Employee entity whose login account is created at the instance of creating the Employee itself. The authentication part I managed to complete by implementing a custom AuthBackend. But now, I'm unable to use the @login_required decorator for other views post-login, because it throws and error 'User' object has no attribute 'is_authenticated'. In order to use is_authenticate method my User modal must then extend from auth.AbstractUser or auth.AbstractBaseUser. How can I keep the original table structure for User modal, but still get around these authentication functions in django? -
URL shortner app django based doesnt open the intended url
i was building a url shortner app in django and i am facing a problem that when i am putting the url it gets short but does not opens the url it was intended to and i cannot detect where the problem is i tried re directing the url to intended url path in my views but it doe=sent work i am expecting that if i am putting a long url in the box it shortens it and opens the url i asked for like full_url= https://stackoverflow.com/questions/ask short_url = stackoverflow and still opens this page -
Getting '502 Bad Gateway' error when accessing TensorFlow Django app deployed on the Google App Engine Flexible Environment
I am trying to deploy my Django app, which includes TensorFlow, on the Google App Engine Flexible Environment. The deployment was successful, but I encountered warnings and errors related to TensorFlow: 2023-06-25 11:24:30 default[20230625t180702] 2023-06-25 18:24:30.097285: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT 2023-06-25 11:24:32 default[20230625t180702] 2023-06-25 18:24:32.252226: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used. 2023-06-25 11:24:34 default[20230625t180702] 2023-06-25 18:24:34.264702: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used. 2023-06-25 11:24:34 default[20230625t180702] 2023-06-25 18:24:34.294337: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. 2023-06-25 11:24:34 default[20230625t180702] To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags. I cannot find any other errors in my app besides this one, so I assume that this error is causing the application to fail and resulting in a "502 Bad Gateway" error. This my app.yaml: runtime: python env: flex entrypoint: daphne -p $PORT api.asgi:application env_variables: DJANGO_SETTINGS_MODULE: "api.settings" beta_settings: cloud_sql_instances: PROJECT_ID:REGION:INSTANCE_NAME runtime_config: operating_system: "ubuntu22" runtime_version: "3.10" Daphne worked fine without any errors, but it is unable to return anything. 2023-06-25 11:38:40 default[20230625t180702] "GET /" 502 2023-06-25 11:38:51 … -
Not able to set cookie using django set_cookie
I am trying to set cookie using django set_cookie. I am converting dict to string and then setting it in a cookie named 'blah'. The cookie gets set, but I see that the commas are replaced with \054. Python code x = { "key1": "value1", "key2": "value2", "key3": "value3", } response.set_cookie('blah', json.dumps(x)) return response How I see it in chrome: "{\"key1\": \"value1\"\054 \"key2\": \"value2\"\054 \"key3\": \"value3\"}" Any pointer what am I missing - please suggest. django==4.2 -
How to include custom model method in Django admin custom filter?
What I am trying to do: I am trying to make custom filter in Django admin using SimpleFilter for using in list_filter. What I tried: Below is the code that I wrote down in admin.py file. I used SimpleFilter for creating custom filter called RoomScoreFilter. RoomScoreFilter filters that if average score is 1.00 to 1.99, it will filter as Very poor and so forth. class RoomScoreFilter(admin.SimpleListFilter): title = _("Room Score") parameter_name = "score" def lookups(self, request, model_admin): return [ ("1", _("Very poor")), ("2", _("Poor")), ("3", _("Normal")), ("4", _("Good")), ("5", _("Excellent")), ] def queryset(self, request, queryset): if self.value() == "1": return queryset.filter(get_average_rating__gte=1, get_average_rating__lt=2) @admin.register(Review) class ReviewAdmin(admin.ModelAdmin): empty_value_display = "-----" fieldsets = [ ("Room & Customer", {"fields": ["room", "customer"]}), ( "Evaluation", {"fields": ["get_average_rating", "comment"], "classes": "wide"}, ), ( "Individual Scores", { "fields": [ "cleanliness", "accuracy", "location", "communication", "check_in", "value", ] }, ), ] list_display = ( "room", "customer", "cleanliness", "accuracy", "location", "communication", "check_in", "value", "get_average_rating", "comment", ) list_display_links = ("room",) list_per_page = 20 list_filter = [RoomScoreFilter] search_fields = ("room", "user") search_help_text = _("Searchable by room name and user ID.") readonly_fields = ("room", "customer", "comment", "get_average_rating") and below is my model. class Review(CommonDateTimeModel): """Review model Definition""" cleanliness = models.PositiveSmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)], verbose_name=_("Cleanliness"), help_text=_("How … -
In Django, after extending the User model, how to add values to the new model?
I have extended the User model in Django with a profile model named "Account" as per 4.2 version. The Django administration panel successfully lists the "Account" model as a section, and it works wonderfully in Django Adminstration panel. I want to set a value of "mobile_number" in Account model while the user signup. Right now I can do that manually in Django Admin Panel, but I need to update that while user signup. I am using following code: user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name, email=email, password=password) mobile_number = user.Account.mobile_number user.save(); And I get error: AttributeError at /accounts/create 'User' object has no attribute 'Account' -
Django and react browser router shows only css
views.py def home(request): return render(request, 'index.html') def home4(request): return render(request, 'index.html') urls.py path('a/',views.home,name='home'), path('b/',views.home4,name='home4'), App.js import './App.css' ... <BrowserRouter> <Route path='/a' element={<Form/>} /> </BrowserRouter> When I got to /a it doesn't show the form component(it is just a form) but the css works. -
how to use context procesors
i want to use context processor in html template witch shows some information but dont know why doesn't it work properly ? models class Info(models.Model): phone_number = models.CharField(max_length=28) email_address = models.EmailField() locations = models.TextField(null=True, blank=True) context processor from Blog.models import Info def info_returner(request): return {'number':Info.phone_number, 'address': Info.locations} template HTML <div class="content"> <ul> <li> <h5>{{ number }}</h5> <span>PHONE NUMBER</span> </li> <li> <h5>{{ email }}</h5> <span>EMAIL ADDRESS</span> </li> <li> <h5>{{ location }}</h5> <span>STREET ADDRESS</span> </li> </ul> </div> as said I was trying to show user some info by context processors but don't know what's wrong with above code -
Data is not storing in django database
This is the code in views.py. def thanks(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone= request.POST['phone'] doctor = request.POST['doctor'] msg = request.POST['reason'] print(name, email, phone, msg) appointment_db = appointment(name=name, email=email, phone=phone, doctor=doctor, message=msg) appointment_db.save() return render(request, "thanks.html", {"name": name}) rest of the code is working. the only error is in the second-last and third-last line. appointment_db = appointment(name=name, email=email, phone=phone, doctor=doctor, message=msg) appointment_db.save() this is the error: appointment_db = appointment(email=email, phone=phone, doctor=doctor, message=msg) TypeError: appointment() got an unexpected keyword argument 'name' The model is also registered and it is showing in the admin panel. However, when I try to store data in it via forms, it throws an error. -
Getting 'crbug/1173575, non-JS module files deprecated' error when running 'npm run dev' with React and Django. How can I resolve this issue?
I'm developing a project using Django as an API, with React as the frontend. I'm following a tutorial on Youtube: https://www.youtube.com/watch?v=YEmjBEDyVSY&list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j&index=4 When I run npm run dev it compiles everything successfully, however, when I head to my website I receive the error 'crbug/1173575, non-JS module files deprecated.' I can get my website to run by using python manage.py runserver simultaneously, but in the tutorial, he doesn't do that at all and only uses npm run dev. Package.json: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" } -
Access blocked: Authorization Error - The OAuth client was not found
i'm working on a Django project and i want to implement the "Login via Google" functionality i've created a new app and got its credentials (Client ID and Client Secret) and i've put them in my Django's project dashboard properly but i'm getting this "Error 401: invalid_client" . i have added my client id and secrete key using the code below SOCIAL_AUTH_GOOGLE_OAuth2_KEY='96637591302-7e0hla5amsv2hmibgi704ehd0v5n8dsl.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_OAuth2_SECERET='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' thanks i am trying to add login via a google functionality .but its giving an error 401 client-id not found -
Login Authentication for custom user model
I have custom user model. I am able to signup but when it comes to login and logout, i have no idea what is happening. Login Form is not logging in the user when I submit the form, it just says the user with that username already exists (it is kind of acting like signup page) How to resolve this issue #models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin # Create your models here. class Organisation(models.Model): organisation_name = models.CharField(max_length = 256) contact_no = models.IntegerField() email = models.EmailField() class Meta(): unique_together = ['organisation_name','email'] def __str__(self): return self.organisation_name class MyUserManager(BaseUserManager): def create_user(self, username, organisation, email, password): if not organisation: raise ValueError("Users must have an organisation") email = self.normalize_email(email) user = self.model(username=username, email=email, organisation=organisation) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, username, email, password): user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.is_superuser = True user.is_staff = True user.save(using=self.db) return user class MyUser(AbstractBaseUser): username = models.CharField(max_length=256,unique=True) email = models.EmailField(max_length=256) organisation = models.ForeignKey(Organisation,on_delete=models.CASCADE,null=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email'] objects = MyUserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True #forms.py from . import models from django import forms class MyUserForm(forms.ModelForm): class Meta(): model = … -
models.BooleanField(default=False) returning True instead of false
issevenDisabled=models.BooleanField(default=False) issevenSaved=models.BooleanField(default=False) iseightDisabled=models.BooleanField(default=False) iseightSaved=models.BooleanField(default=False) output: "issevenDisabled": true, "issevenSaved": true, "iseightDisabled": true, "iseightSaved": true, -
how to query the fields when taking dump from a single table?
I have a table in to the postgres db name is "drf_api_logs", and I want to filter this table and dump data ... filter like this: two_month_ago = datetime.now().date() - timedelta(days=60) APILogsModel.objects.filter(~Q(added_on__date__gte=two_month_ago)) and i want to dump data like this: cmd = f'PGPASSWORD={config("DB_PASSWORD")} /usr/bin/pg_dump --dbname={config("DB_NAME")} --table=drf_api_logs --file={dir}/{log_name} --username={config("DB_USER")} --host={config("DB_HOST")} --port=5432' how can I do this filter when dumping i try this one, but not work :/ month_ago = datetime.now().date() - timedelta(days=60) cmd = f'PGPASSWORD={config("DB_PASSWORD")} /usr/bin/pg_dump --dbname={config("DB_NAME")} --table=drf_api_logs --where=added_on__date__gte={month_ago} --file={dir}/{log_name} --username={config("DB_USER")} --host={config("DB_HOST")} --port=5432' -
Accessing array in django template
I have given time = [ 5 , 7 , 10 , 15 , 30 , 50 , 70 , 100 , 120 , 150 ] , stocks = [1 ,2 ,3, 4, 5, 6, 7, 8, 9, 1] , and repetation = [ 0 , 1 , 2, 3, 4 ,5 , 6 ,7, 8, 9] Now i want to access time and stocks according to the repetation array like time[0] , time[1] like time[repetation first value ] and so on. {% for n in repetation %} <div class="stockDataDiv"> <span> {{ time.n }} </span> <span> {{ stockRequired.n }} </span> </div> {% endfor %} This is the code that i tried but couldn't find a solution. -
python manage.py runserver not working on Windows
I am currently learning Python and Django, trying to use the runserver command, python manage.py runserver, but it has not been working. It gives me bunch of lines of errors which I have the screenshots attached. If you do have a solution, thank you in advance. [enter image description here](https://i.stack.imgur.com/x7OG7.png) I tried adding a specific local port to get it working which did not. I need it to create a local port to a webpage -
How to fix multivalue dict key error in django
How to fix multivalue dict key error in django plz fix this problem How to fix multivalue dict key error in djangoHow to fix multivalue dict key error in django How to fix multivalue dict key error in djangoHow to fix multivalue dict key djangoHow to fix multivalue dict key error in djangoHow to fix multivalue dict key django -
How to cancel (terminate) a running task in celery? Already tried using "AsyncResult(task_id).revoke(terminate=True)", but it doesn't work
In the django project, I use celery to run asynchronous tasks. I want to implement a function to cancel the running task. The official documentrevoke: Revoking tasks says that the "revoke(terminate=True)" method can be used. I tried it but it didn't work. Here are some ways I've tried: ... task = AsyncResult("1e8fb3f3-4253-4bec-b71a-665ba5d23004") print(task.state) 'STARTED' task.revoke(terminate=True) print(task.state) 'STARTED' app.control.revoke("1e8fb3f3-4253-4bec-b71a-665ba5d23004", terminate=True) print(task.state) 'STARTED' And eventually it still executes to completion. Has anyone encountered a similar problem? Or is there another way to achieve my needs in celery? Any help would be greatly appreciated! -
Pass request to django-filters custom widget
I'm trying to create a filter like the one in the image below (from Fiverr), it is a combination of select with options as inputs, I was able to create the widget and select an option and send its sub-input values on submit, but after the loading the values are gone and no option is selected, because the radio select value is not specified by the field so i need to get it directly from the request.GET, but i couldn't pass the reqeust to the widget, i'm seeing it on the Filter class but not in widget. My Custom Filter: `class PriceFilter(Widget): template_name = 'widgets/PriceFilter.html' def __init__(self, attrs=None, min=0, max=5000, *args, **kwargs): self.min = min self.max = max # print(self.request) print(kwargs) super(PriceFilter, self).__init__() def get_context(self, name, value, attrs=None, *args, **kwargs): context = super().get_context(name, value, attrs) context['min'] = self.min context['max'] = self.max print(self.request) print(kwargs) return context` My widget template ` Clickable inside <input class="form-check-input" type="radio" name="{{widget.name}}__selector" id="{{widget.name}}__selector" #if request.GET.price__selector==1 then ceck this#> Default radio ` My Filter `class ListFilter(django_filters.FilterSet): price = django_filters.NumberFilter(widget=PriceFilter()) class Meta: model = MainModel fields = { 'name':['contains'],'price':[] } def __init__(self, *args, **kwargs): print('kwgs') # print(args[0]) self.request = kwargs.pop('request', None) super(ListFilter, self).__init__(*args, **kwargs) self.filters["price"].request = args[0] ` -
In Dajngo, does the UserCreationForm or its parent classes handle the POST and GET logic? Or how is that handled?
I am new with django and going over some code that I don't understand. I looked through the django source code trying to find out if the class UserCreationFrom (pasted below) from Django handles the logic of POST for you, or if this is implemented elsewhere. To clarify, I have been seeing a class used for rendering the form then some type of view validating the data. It typically goes like: Form Class: class UserForm(forms.ModelForm): class Meta: model = User fields = ("first_name", "last_name") View: def update_profile(request): if request.method == "POST": user_form = UserForm(request.POST, instance=request.user) if user_form.is_valid(): user_form.save() return redirect("somewhere") else: user_form = UserForm(instance=request.user) return render(request, "profile.html", {"user_form":user_form}) That implementation makes sense. What I don't get is when there is a view that renders the form but then the form itself handles validation and leaves out the if request.method == "POST" logic as shown above. Or is this in some parent class? Is either one of these inline with django convention as well? An example: Class View: class UserSignupView(CreateView): model = CustomUser form_class = UserProfileSignupForm template_name = 'signup_form.html' def get_context_data(self, **kwargs): kwargs['is_confused'] = True return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('somewhere') Then the form with … -
GCP-Django-IP Address based error: write EPROTO error:100000f7 OPENSSL_internal
This is among the strangest issues I have seen. When I make a postman GET api call to this url in the US, I do not have any problems, it gives me the JSON I need. However, when I make the same API call in Canada (even using the same computer), it gives the following error: Error: write EPROTO error:100000f7:SSL routines:OPENSSL_internal:WRONG_VERSION_NUMBER:../../third_party/boringssl/src/ssl/tls_record.cc:242: You don't need Postman, you can also just navigate to the url to see the response. The API is hosted on GCP (Google Cloud Platform) and uses the Python Django framework. There's no IP Address restrictions that I setup personally I have gone through several responses with this error, but none have any solution that worked, and I'm not sure what to look for now -
Dropdown values for django form not showing up in view
I am trying to make a todo app in django but I am not able to get a dropdown to set a category populate. This is what the form looks like when I render everything: What I am expecting was that the dropdown would have the options 'Personal' and 'Professional' This is my model: from django.db import models class Category(models.Model): CATEGORY = (('Personal', 'Personal'), ('Professional', 'Professional')) type = models.CharField(max_length=100, null=True, choices=CATEGORY) def __str__(self): return self.type class Item(models.Model): created_at = models.DateTimeField(auto_now=True) task = models.CharField(max_length=200) completed = models.BooleanField(default=False) category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True) def __str__(self): return (f"{self.created_at}: {self.task}") This is the form I am trying to use: from .models import Item from django import forms class AddItem(forms.ModelForm): class Meta: model = Item fields = ['task', 'category'] This is the template: <div> <h1>Your todo task</h1> <br> <form method="POST" action="{% url 'home' %}"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-secondary">Add a task</button> </form> </div> Thank you for your time and any information you can provide.