Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Heroku - Custom 500 template
I have a template defined and loaded on S3. The template has been granted public access. The template is referred in Heroku as variable ERROR_PAGE_URL and the S3 link is attached against this variable. Somehow the template is not displaying and I still get the basic 500 error generated: 500 Internal Server Error Exception inside application. Daphne I have (I think) applied the same approach as the custom maintenance template, which is rendered perfectly fine. Am I reading the documentation wrong? (https://devcenter.heroku.com/articles/error-pages) Am I using the correct variable? Or is it actually not somehting Heroku generates and I should code this in django? -
Exception Value: User matching query does not exist
DoesNotExist at /profile/username User matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/profile/username Django Version: 5.0.4 Exception Type: DoesNotExist Exception Value: User matching query does not exist. Exception Location: D:\Django projects\social media app\social_media_app_env\Lib\site-packages\django\db\models\query.py, line 649, in get Raised during: core.views.profile Python Executable: D:\Django projects\social media app\social_media_app_env\Scripts\python.exe Python Version: 3.11.9 Python Path: ['D:\Django projects\social media app\social_media', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\python311.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0', 'D:\Django projects\social media app\social_media_app_env', 'D:\Django projects\social media ' 'app\social_media_app_env\Lib\site-packages'] Server time: Fri, 19 Apr 2024 10:53:11 +0000 -
Django populating a form on a modal
I have a problem with populating a form on a modal pop up. I can get a form added to the modal, but I want it to be based on the line a user clicks on. My view: class SalesQuotationDetailView(LoginRequiredMixin, View): template_name = 'Sales/quotation_details.html' def get(self, request, quoteid): quotation = Quotation.objects.get(id=quoteid) quotationlines = QuotationLine.objects.filter(quotation=quotation, deleted=False) company = quotation.customer quotationform = QuotationForm(initial=model_to_dict(quotation), companyid=company.id) newquotationlineform = NewQuotationLineForm() context = { 'quotation':quotation, 'quotationform':quotationform, 'quotationlines':quotationlines, 'new_quotation_line':newquotationlineform, 'table_title':"Quotation Lines", 'table_heading_1':"Article", 'table_heading_2':"Amount", 'table_heading_3':"Price per Piece", 'table_heading_4':"Lead Time", 'table_heading_5':"Line total" } return render(request, self.template_name, context) def post(self, request, quoteid): quotation = Quotation.objects.get(id=quoteid) quotationlines = QuotationLine.objects.filter(quotation=quotation, deleted=False) company = quotation.customer quotationform = QuotationForm(data=request.POST, files=request.FILES, instance=quotation, companyid=company.id) if quotationform.has_changed and quotationform.is_valid(): qform = quotationform.save(commit=False) qform.updated_by = request.user qform.updated_date = timezone.now() quotationform.save() messages.success(request, f'{quotation.number} has been saved correctly') return redirect('sales-quote-details', quoteid=quotation.id) else: messages.warning(request, f'{quotationform.errors}') newquotationlineform = NewQuotationLineForm(data=request.POST) if newquotationlineform.has_changed and newquotationlineform.is_valid(): newquotationline = newquotationlineform.save(commit=False) newquotationline.quotation = quotation newquotationline.total_line_price = newquotationline.amount * newquotationline.price newquotationline = newquotationlineform.save() messages.success(request, f'The new quotation line was added succesfully') return redirect('sales-quote-details', quoteid=quotation.id) context = { 'quotation':quotation, 'quotationform':quotationform, 'quotationlines':quotationlines, 'new_quotation_line':newquotationlineform, 'table_title':"Quotation Lines", 'table_heading_1':"Article", 'table_heading_2':"Amount", 'table_heading_3':"Price per Piece", 'table_heading_4':"Lead Time", 'table_heading_5':"Line total" } return redirect('sales-quotations') And my template: {% extends "start/parent.html" %} {% block body %} <!-- Content … -
HEROKU (Dockerfile that does not exist)
tried hosting my django website on Heroku, but keeps getting dockfile does not exist which is from the heroku.yml file Waiting on build... Waiting on build... (elapsed: 6s) Waiting on build... (elapsed: 9s) === Fetching app code =!= There were problems parsing your heroku.yml. We've detected the following issues: build.docker.web references a Dockerfile that does not exist below is a screenshoot of my vscode explorer and heroku.yml fileVScode Screenshot -
Two detail tabels with a foreign key to the same master table, how to limit a ManyToManyField to see only the subset of the other detail tabel
In Django I have an Order and Contact table that both have a foreignKeyField to the User table, in the Order table I want a ManyToManyField to see only the subset of Contact table records that belong to the same User, instead of the ManyToManyField seeing all of the records of the contact table. class Contact(models.Model): cnt_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=30, blank=False, null=True) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_set') ref_code = models.CharField(max_length=20, blank=True, null=True) ### ManyToManyField should only see subset of contacts that have same user. contacts = models.ManyToManyField(Contact, blank=True, limit_choices_to={'cnt_user': user}) I cannot figure out how to set the limit_choices_to parameter or how to use a callable in this case. In this example ({'cnt_user': user}) django sees user as a "foreignKey object" not a "user object" this results in the following error: Field 'id' expected a number but got <django.db.models.fields.related.ForeignKey: user>. To me, "this problem" does not seem to be an uncommon scenario, I am hoping there is a straightforward solution. Can anybody show me an example of how to this, either by a callable or a Q object or any other way (proxy model maybe)? Thanks in advance. -
Django Project CORS error after deployment
I got Pyton Django project and my project work on local server but when i deploy on server i got this error.I used IIS Manager for deployment.Other DB connection must be work because i can reach other APIs.By the way my user is superuser. Access to XMLHttpRequest at 'https://website.websites.com:8000/integration/sync' from origin 'https://website.website.com' has been blocked by CORS policy: No 'Access-Control- Allow-Origin'header is present on the requested resource. And here is my API;POST https://website.website..com:8000/integration/sync net::ERR_FAILED 500 (Internal Server Error) By the way OTher API are working without problem I search about error and they suggest me to change setting.py but under below is my settings; ALLOWED_HOSTS = ['*'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', I use for deployment IIS may be its about it. So they said that its about Autontication IIS I tried every combination but it still doesnt work, -
I have a Category model and a subCategory model and a product model which has foreign key with category and sub category
I have a Category model and a subCategory model and a product model which has foreign key with category and sub category . Whenever a client will add a product then he will select a category and according to that the related subcategory should shown or change without submitting the form in django admin panel. Please tell me how to do this. The value should change on "onChange event" of the category. -
Django Channels on IIS using FASTCGI
I am deploying a Django app using an IIS server. In this Django app, I have implemented Django Channels to use websockets. Locally, everything is working fine with websocket connections, and I am able to send messages. However, the issue arises when I deploy the Django app. The HTTPS works perfectly fine, but the WSS (WebSocket Secure) is not working. I encounter a 404 not found error. the url in which I am trying is wss://my_domain/ws/start-quiz/ also note that i am using memurai instead of redis to use channel_layers CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6370)], }, }, } -
How to set default value of a model field to another field of same mode in django
I've created a Student model in django project with has a field named "enrollmentdate" and "paymentdate" now i need to save "paymentdate" as default value in "enrollmentdate" my model code is as under, > ``` class Student(models.Model): fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) email = models.CharField(max_length=100) password=models.CharField(max_length=100) contactno = models.CharField(max_length=100) address = models.TextField() grade=models.CharField(max_length=100) enrollmentstartdate=models.DateField() enrollmentenddate=models.DateField() daysremaining=models.IntegerField() feespaid=models.DecimalField(max_digits=6, decimal_places=2) paymentdate=models.DateField() > ``` how can i do this? thanks in advance I have tried entrollmentdate=models.DateField(default=paymentdate) but not works -
How can I establish a connection between the front-end and a database?
I have created a website with Django that features a combined login and registration page. Now, I want the user data to be successfully saved in the database upon registration. How can I accomplish this? I expect that after a user registers successfully, they can log in successfully as well, and their data should be present in both the back-end management system and displayed within the database. I am building the front-end using HTML, CSS, and JS. -
Django serializer
this serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): #user = super(RegisterSerializer, self).create(validated_data) user = User.objects.create_user(**validated_data) return user and Loginserializer : class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): username = data.get('username') password = data.get('password') if username and password: user = authenticate(username=username, password=password) if user and user.is_active: return user raise serializers.ValidationError("Invalid credentials!") I used this code and worked well but when I changed my Register serialzer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = super(RegisterSerializer, self).create(validated_data) return user the code does not work well . when I want to test my endpoint in Postman the code creates user very well but for login endpoint I always take this response Invalid credentials I don't know what has happened when I changed my code first works well but when I add this line it did not work "user = super(RegisterSerializer, self).create(validated_data)" -
Data store multiple time in django admin panel
I am submitting the form once in the django admin panel, but the data are shown twice. here is my code: views.py: def checkout(request): if request.method == 'POST': country = request.POST['country'] fname = request.POST['fname'] lname = request.POST['lname'] C_address= request.POST['C_address'] state= request.POST['state'] zip = request.POST['zip'] emailADD = request.POST['emailADD'] phoneNO= request.POST['phoneNO'] y = checkoutitem(country=country,fname=fname,lname=lname,C_address=C_address,state=state,zip=zip,emailADD=emailADD,phoneNO=phoneNO) y.save() return render(request,'checkout.html') models.py: class checkoutitem(models.Model): country = models.CharField(max_length=100,default='') fname = models.CharField(max_length = 100,default='') lname = models.CharField(max_length =100,default='') C_address = models.CharField(max_length=255 , default='') state = models.CharField(max_length=100,default='') zip = models.CharField(max_length=100,default='') emailADD = models.EmailField(max_length = 100,default='') phoneNO = models.CharField(max_length =10,default='') urls.py: path('checkout/', views.checkout, name="checkout") I want to display a data only once not twice. So, give me solution. -
Django " [ was not closed " error in url routing
I'm new to python. Trying to understand and following the tutorials. One of the many tutorials that I follow, in django for url routing we are creating url.py and put our routing logic inside that file as below: urlpatterns = [ path=("",views.index), path=("/index",views.index) ] In every tutorial that syntax is working. But in my example it throws an error as below: I did not understand why it is showing me error and not for others. Also I have tried so assign path method into a variable and after that It worked. Am I missing syntax rule or someting? -
django string interpolation struggles
Hi so I am having a problem trying to concatenate in django. I have created a new templatetag and im trying to get the string interpolation right and im struggling a bit. {% button text="Reset" onclick="test('{{user.id}}')" colour="yellow" %} function test(user_id){ console.log('user id:', user_id) } the console log just gives back user id: {{user.id}} {% button text="Reset" onclick="test('"|add:user.id|stringformat:"s"|add:"')" colour="yellow" %} I have also tried this way but it just gives me a syntax error. any help on how to properly do this or even if its not possible any help would be great. (still new to django) -
Django: Generate random time in a within a specific day and insert multiple rows to database
I have a schedule for user in which it will generate randomly. For example I want to create and schedule for tomorrow, the admin will choose a day and N number of report a day. So the no_of_route is the # of rows to insert in database and also the # of generated hours and the # of route it will select from RoutePoints class. So, I really don't know to to generate hours. And this is where it should be. no_of_route = request.POST.get('no_of_route') date = request.POST.get('date') # generate hours, if no_of_route is 3, it would be 9AM, 1PM, 5PM hour = ... This is how I select random route id. items = list(RoutePoints.objects.all()) random_route = random.sample(items, no_of_route)[0] And this where I create multiple of rows. I'm not really sure how to do it. Schedule.objects.bulk_create(route=items.id, time=hour, date=date) Hope someone see this. Thank you in advance! -
Hosting a Django application on azure app service
After following the official host python with postgres tutorial, and making modifications in my gh actions file because my django apps isn't present in the root on the repo, I get a 404 error when trying to access it. Here is my settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 5.0.3. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from decouple import config from os import environ from google.oauth2 import service_account from pathlib import Path from django.conf import global_settings # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config( "SECRET_KEY", default="django-insecure-g8khpcexyyb0q@p40^d5#r_j#ezf%(-90r-y^2@x1)2$wpch9+", ) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config("DEBUG", default=False, cast=bool) ALLOWED_HOSTS = ( [environ["WEBSITE_HOSTNAME"]] if "WEBSITE_HOSTNAME" in environ else config( "ALLOWED_HOSTS", cast=lambda v: [s.strip() for s in v.split(",")], default=[] ) ) CORS_ALLOWED_ORIGINS = config( "CORS_ALLOWED_ORIGINS", cast=lambda v: [s.strip() for s in v.split(",")], default="http://localhost:5173,http://127.0.0.1:5173", ) # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", … -
Invalid block tag on line ...: 'endblock', expected 'endwith'. Did you forget to register or load this tag?
I have a problem with my project on Python Here is a code, that located in Django template {% extends "base.html" %} {% load django_bootstrap5 %} {% block content %} <form method="post"> {% csrf_token %} {% bootstrap_form form %} {% bootstrap_button button_type="submit" content="Отправить" %} </form> **{% with data=request.POST %}** {% endblock %} When i reloading the page i receive an error on screenshot. error screen After the deleting this string, everything fine. {% with data=request.POST %} I dont understand what wrong ??? Iam trying to delete the string, that leads to an error, it helps, but according to the conditions of the task this string is must to be in this block of code -
How to Enable DEBUG Logging in Django?
I'm currently working on implementing logging in my Django project, but I'm encountering an issue where calls to logger.debug('log') do not output anything. I suspect there might be something wrong with my logging configuration. Below is the LOGGING configuration from my settings.py: logger = logging.getLogger(__name__) logger.debug(f"debug from logger") DJANGO_LOG_LEVEL = "DEBUG" LOGGING = { 'version': 1, 'disable_existing_loggers': False, "formatters": { "verbose": { "format": "{levelname}: {message} ({process:d}:{thread:d}::{filename}:{lineno}::{asctime})", "style": "{", 'datefmt': '%Y-%m-%d %H:%M:%S', }, "simple": { "format": "{levelname}: {message} ({filename}:{lineno})", "style": "{", }, }, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, "file": { "level": "INFO", "class": "logging.FileHandler", "formatter": "simple", "filename": logs_path.joinpath(f"{STAGE}-django.log").as_posix(), }, "mail_admins": { "level": "INFO", "class": "django.utils.log.AdminEmailHandler", "include_html": True, }, }, 'loggers': { '': { 'handlers': ['stdout', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['stdout', 'file'], 'level': 'WARNING', 'propagate': True, }, "django.request": { "handlers": ["mail_admins"], "level": "ERROR", "propagate": False, }, }, } Some can help me to figure out what's wrong with my logging configuration? -
DJANGO [WinError 10061] email features
I'm working in a Django project that uses the mail features. When try to send the mail I got this error message: [WinError 10061] No connection could be made because the target machine actively refused it. I'm using an email with godaddy domain. This is my configuration: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'mymail' EMAIL_HOST_PASSWORD = 'mypassword' I have tried all the related questions like: How to fix ConnectionRefusedError: [WinError 10061] the target machine actively refused it? (Django e.mails) I checked the firewall and none of the ports like 587, 25, 465, etc. were blocked. I also tried to connect with office365 server and didn't work. I don't know if this worth, but I have errors connecting with some pages for example when I run pip install library, gives an error related to SSL certification and only works if I bypass with --trusted-host. Maybe in this case I need to use something similar. -
Django - How to filter model objects by certain attribute and use it for front-end?
I am a beginner and building a website to showcase wines. This is the model for Wine: class Wine(models.Model): name = models.CharField(max_length=100) type = models.CharField(max_length=50) description = models.TextField() image = models.ImageField(upload_to='images/wines/') keywords = models.CharField(max_length=255, blank=True) def __str__(self): return self.name I added a page called "Advanced Search" which should initially show all the wines. I want to implement filtering functionality so when I select the corresponding checkboxes, the wines should be filtered by their keywords. Currently the keyword field accepts string as input. For example Wine1 has the following keywords: "red, plum, citrus". But the keywords field accepting string is not necessary (please suggest other approaches if needed). In my HTML file I added some checkboxes to test. The checkboxes correspond the keywords. So if I check the "plum" and "red" checkboxes, only the wines which contain those keywords should be shown. Here is the html part of the page: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false"> Filter </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="filterOptions"> <li><input class="form-check-input" type="checkbox" id="redCheckbox" value="red"><label class="form-check-label" for="redCheckbox">Red</label></li> <li><input class="form-check-input" type="checkbox" id="sparklingCheckbox" value="sparkling"><label class="form-check-label" for="sparklingCheckbox">Sparkling</label></li> <li><input class="form-check-input" type="checkbox" id="whiteCheckbox" value="white"><label class="form-check-label" for="whiteCheckbox">White</label></li> <li><input class="form-check-input" type="checkbox" id="sweetCheckbox" value="sweet"><label class="form-check-label" for="sweetCheckbox">Sweet</label></li> <li><input class="form-check-input" type="checkbox" id="dryCheckbox" value="dry"><label class="form-check-label" for="dryCheckbox">Dry</label></li> … -
i want some help to host my django Application on AWS LIGHT SAIL
I have tried hosting websites with sites like netlify but this time i want host my django application on AWS lightsail i need some help on how this can be archieved -
Running python manage.py commands tries to open a file in windows 10
As the title suggests, whenever i try to use python manage.py commands like runserver/ makemigrations, windows tries to open file for some reason any help is appreciated. -
Table does not exist with django
I'm facing an issue in my Django application when trying to delete a user through the REST API. I receive an internal server error with the message: Internal Server Error: /api/v1/user/30 Traceback (most recent call last): File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute return self.cursor.execute(query, args) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.ProgrammingError: (1146, "Table 'portobello.auth_user_groups' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\generics.py", line 291, in delete return self.destroy(request, *args, **kwargs) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\mixins.py", line 91, in destroy self.perform_destroy(instance) File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\mixins.py", line 95, in perform_destroy instance.delete() File "C:\Users\lucas.baixo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", … -
Why are permissions not being overridden for a viewset?
I have created a viewset for authentication. Since this is the authentication viewset, I want this viewset to be accessible to unauthorized users as well. Following DRF documentation, this is what I have: class AuthenticationViewSet(viewsets.ViewSet): permission_classes = [AllowAny] def create_user(self, request: Request) -> Response: #code for creating a user Since I want the other viewsets to be accessible only to the authorized users, I set the following in settings.py: REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], "DEFAULT_AUTHENTICATION_CLASSES": [ "authentication.token_auth.ExpiringTokenAuthentication" ] } When I make an API call to the create_user endpoint, I get an error saying: "No token found". Why is this happening? Shouldn't the permissions be overridden based on the permission_classes list in the viewset? For reference, my authentication class: class ExpiringTokenAuthentication(TokenAuthentication): def authenticate(self, request): if COOKIE_KEY in request.COOKIES: token_key = request.COOKIES[COOKIE_KEY] else: raise exceptions.AuthenticationFailed("No token found") try: token = Token.objects.get(key=token_key) except Token.DoesNotExist: return exceptions.AuthenticationFailed("Invalid token") if isTokenExpired(token): raise exceptions.AuthenticationFailed("Token has expired") user = token.user return (user, token) def isTokenExpired(token): currentTime = datetime.now(datetime.UTC) currentTimeUTC = currentTime.replace(tzinfo=pytz.UTC) return token.created < currentTimeUTC - timedelta(hours=TOKEN_EXPIRE_HOURS) -
django 'NoneType' object has no attribute 'userprofile' problem in related fileds
hi i have a django project and i have related database i can not reach for a two filed from database and the above mistake appear and this is models.py for app display class Display(models.Model) : url=models.URLField(unique=True) text = models.CharField(max_length=150) class Display_Data(models.Model) : displays = models.ManyToManyField(Display,related_name='display_data') users= models.ManyToManyField(User) choosenum=models.IntegerField() puplish_date =models.DateTimeField(default=datetime.now) and this is models.py for app account class UserProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) user_nickname=models.CharField(max_length=150) userphoto =models.ImageField(upload_to='imageprofile/%Y/%m/%d/') class UserUrl(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) url=models.URLField(default="https://www.facebook.com/profile.php? id=100068020764035") and this is views.py def check_url_exists_and_person(url_to_check): user_info_array = [] for i in range(1, 6): latest_successful_record = Display_Data.objects.filter(displays__url=url_to_check, choosenum=i).order_by('-puplish_date').first() if latest_successful_record: user_info = { 'user_nickname': latest_successful_record.users.first().userprofile.user_nickname, 'url': latest_successful_record.users.first().userurl.url } else: user_info = None user_info_array.append(user_info) return user_info_array