Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Prevent django from writing e-mail information to stdout
I'm using django 2.2. with python 3.6. In some cases my server stores stdout into a log used by managers. For some reason django started to write to stdout at send-mail some time ago. The managers do not like it because it looks like en error case for them. So the following sends the e-mail, but also writes to stdout: ^C(venv) > python manage.py shell Python 3.6.15 (default, Sep 15 2021, 12:00:00) Type 'copyright', 'credits' or 'license' for more information IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from django.core.mail import send_mail In [2]: send_mail( ...: 'Problems in sync script', ...: "kukkuu", ...: 'pxpro_sync@<myOrg>', ...: ['<myEmail>'], ...: fail_silently = False,) connection: {'fail_silently': False, 'host': 'localhost', 'port': 25, 'username': '', 'password': '', 'use_tls': False, 'use_ssl': False, 'timeout': None, 'ssl_keyfile': None, 'ssl_certfile': None, 'connection': None, '_lock': <unlocked _thread.RLock object owner=0 count=0 at 0x7fa8e5a01180>} mail: <django.core.mail.message.EmailMultiAlternatives object at 0x7fa8e59b4ba8> <class 'django.core.mail.message.EmailMultiAlternatives'> Out[2]: 1 How can I get just e-mails sent without anything (like "connection:...") displayed into stdout ? -
Unable to create custom user in django
I am trying to create a custom user model in django. I want the user to register using their username and email and password. Howerver when i try to create the superuser, it never asks for the email and then throws this error: File "C:\Users\User\Desktop\myproj\todo_app\models.py", line 8, in _create_user raise ValueError('Please provide a valid email') ValueError: Please provide a valid email Here is my models.py file `from django.db import models from django.utils import timezone from django.contrib.auth.models import UserManager,AbstractBaseUser,PermissionsMixin Create your models here. class CustomUserManager(UserManager): def _create_user (self, email,password, **extra_fields): if not email: raise ValueError('Please provide a valid email') email= self.normalize_email(email) user= self.model(email=email, **extra_fields) user.set_password(password) user.save( using= self.db ) return user def create_user(self,email=None,password=None, **extra_fields): extra_fields.setdefault('is_staff' ,False) extra_fields.setdefault('is_superuser', False) return self._create_user(email,password, **extra_fields) def create_superuser(self,email=None,password=None, **extra_fields): extra_fields.setdefault('is_staff' ,True) extra_fields.setdefault('is_superuser', True) return self._create_user(email,password, **extra_fields) class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(blank=True,default='',unique=True) name = models.CharField(max_length=255,blank=False,default='',unique=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(blank=True, null=True) objects = CustomUserManager() USERNAME_FIELD = 'name' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = 'User' verbose_name_plural = 'Users' def get_full_name (self): return self.name def get_short_name(self): return self.name or self.email.split('@')[0] ` -
AssertionError while testing forms.py in Django
I tried to test forms.py in Django which has LeadForm class. Here, is the code I used to test. @pytest.fixture def valid_course(db): return Course.objects.create(name='Design') @pytest.fixture def valid_lead_data(valid_course): return { 'full_name': 'john', 'phone_number': '1234567890', 'email': 'john@gmail.com', 'course': valid_course.id, 'g-recaptcha-response': 'PASSED', } The above code shows AssertionError that the course is not in one of the available choices. Thanks in advance. -
Celery can't connect to Postgres Django
Celery can't connect to Postgres Django The problem is that the Celery container cannot connect to the Postgres database when it starts executing a task. What could be the problem? When sending a task, it returns the following error - django.db.utils.OperationalError: connection is bad: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory. Is the server running locally and accepting connections on that socket? docker-compose.yml version: '3' services: db: image: postgres:latest container_name: postgres restart: always env_file: .env ports: - "5432:5432" web-app: build: . container_name: django restart: always command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - "8000:8000" env_file: .env depends_on: - db - redis - worker worker: build: . container_name: celery restart: always command: celery -A yumezo worker -l info volumes: - .:/app depends_on: - redis redis: image: redis:latest container_name: redis restart: always ports: - "6379:6379" celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yumezo.settings') app = Celery('yumezo') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() init.py from .celery import app as celery_app __all__ = ['celery_app'] settings.py CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_RESULT_BACKEND = 'redis://redis:6379/0' ENV file POSTGRES_DB = 'yumezo' POSTGRES_USER = 'katsuyoriiii' POSTGRES_PASSWORD = 'pass' DB_HOST = 'db' DB_NAME = 'yumezo' … -
Value from F expression in Django ORM is not a decimal and Objects has to field named
I have the following classes/models and I'm trying to do bulk update thousands of Recipt objects to have an Item JSON object in the details section from django.db import models from schematics import models as schema_models class Recipt(models.Model): id = UUID() is_red = models.BooleanField(default=False) disputed_at = models.DateTimeField(null=True) total_amount = models.DecimalField(max_digits=12, decimal_places=2) details = JSONModelField(ReciptDetails) class ReciptDetails(PickleableModel): id = UUID() item = schema_types.ModelType(Item) class Item(schema_models.Model): id = schema_types.UUIDType() name = schema_types.StringType() amount = schema_types.DecimalType() description = schema_types.StringType() When doing: Recipt.objects.filter(Q(details__item=None), is_red=True).update(details__item=Item({"name": SOMECONST.HAPPY, "amount": F('total_amount')})) I get the error: *** schematics.exceptions.DataError: {"amount": ["Value 'F(total_amount)' is not decimal."]} I'm guessing it's because the F expression is inside of the Item class (json object). What is the proper way to get the total_amount value from the Recipt to add to the item json? Moreover, when I try to set a decimal constant value (to bypass the issue above): Recipt.objects.filter(Q(details__item=None), is_red=True).update(details__item=Item({"name": SOMECONST.HAPPY, "amount": Decimal("10.00")})) I get that: django.core.exceptions.FieldDoesNotExist: Recipt has no field named 'details__item' Any ideas of how to fix these issues? I think it stems from the nesting of JSON objects -
postgres: Connection already closed issue
I'm encountering a "connection already closed" error in my Django application that uses PostgreSQL as the database backend. Despite trying various solutions, I can't seem to resolve this issue. Background Information Django Version: 4.2.13 Psycopg2: 2.9.9 Problem Statement I have a Django application that intermittently throws a "connection already closed" error when trying to interact with the PostgreSQL database. This issue often arises under the following circumstances: Running background task for inserting data into db in every 30 seconds errors: File "django\utils\asyncio.py", line 26, in innerreturn func(*args, **kwargs) File "django\db\backends\base\base.py", line 330, in cursorreturn self._cursor() File "django\db\backends\base\base.py", line 308, in _cursorreturn self._prepare_cursor(self.create_cursor(name))File "django\db\utils.py", line 91, in exitraise dj_exc_value.with_traceback(traceback) from exc_valueFile "django\db\backends\base\base.py", line 308, in _cursorreturn self._prepare_cursor(self.create_cursor(name))File "django\utils\asyncio.py", line 26, in innerreturn func(*args, **kwargs)File "django\db\backends\postgresql\base.py", line 330, in create_cursorcursor = self.connection.cursor()django.db.utils.InterfaceError: connection already closed What I’ve Tried Ensured that the database connection parameters are correct. Checked for any long-running queries that might be causing timeouts. Adjusted Django's database connection settings such as CONN_MAX_AGE and CONN_HEALTH_CHECKS. Increased the connection timeout settings in PostgreSQL. Despite these attempts, the issue persists -
Using CloudLinux to create a Python app getting error Specified directory already used by '/path/to/application'
I am using cloudlinux through DirectAdmin (this shouldn't matter) and I am trying to create a new Django application using the "Setup Python App" create application option. I have uploaded my django files properly and I am certain that the correct permissions are set to the applications folder (i.e. chowner -R username foldername and chmod -R 755 foldername). Every time I try to add it get the error Specified directory already used by '/path/to/application'. I have removed the virtual environment and even tried putting the app in various locations in case the root wasn't good enough but I still received this error. -
× Encountered error while trying to install package. ╰─> typed-ast
I have a django project which I cloned into my local but I am not being able to start backend coding because of the requirements not being installed. Everytime I try to install the requirements.txt, it gives me the following error. note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> typed-ast note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure. I have tried the following things. Downgrading python version to 3.11.1 Downgrade the typed-ast to 1.4.2 Installed mypy latest version 1.10.0 Installed Desktop development with C++ and other packages. I have windows 11. I cloned the project in other system which has windows 10, but it worked perfecty...I didnt have to downgrade anything. My error is as follows: Running setup.py install for typed-ast ... error error: subprocess-exited-with-error × Running setup.py install for typed-ast did not run successfully. │ exit code: 1 ╰─> [127 lines of output] running install C:\ALL_FILES\Projected\kvwsmb\myvenv\Lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. warnings.warn( running build running build_py creating build creating build\lib.win-amd64-cpython-311 creating … -
django-import-export, using the foreign key widget
I seem to be having some issues trying to figure out how to use the ForeignKeyWidget in the django-import-export package. I'm hoping someone here will be able to point out what is wrong with my code. I'm able to export the data I want except for the asset. I would like it to be the name of the asset, but it is exporting the ID. Here is my models from django.db import models from datetime import datetime class asset(models.Model): name = models.CharField(max_length=8) def __str__(self): return f"{self.id} {self.name}" class report(models.Model): machine = models.ForeignKey(asset, on_delete=models.CASCADE) last_active = models.DateField() return_code = models.CharField(max_length=16, blank=True) comment = models.CharField(max_length=256, blank=True) status = models.CharField(max_length=256, blank=True) @property def since(self): return (datetime.now().date() - self.last_active).days def __str__(self): return f"{self.machine} {self.last_active} {self.return_code} {self.comment} {self.status}" Here is my admin.py from django.contrib import admin from django.contrib.admin import DateFieldListFilter from import_export.admin import ImportExportModelAdmin from import_export import fields, resources from import_export.widgets import ForeignKeyWidget from .models import asset, report class reportResource(resources.ModelResource): machine = fields.Field( column_name='machine', attribute='machine', widget=ForeignKeyWidget(asset, 'name')) class Meta: model = report # fields = ('machine',) class reportAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ("machine", "last_active", "return_code", "comment", "status") resources_class = reportResource admin.site.register(report, reportAdmin) admin.site.register(asset) I'm exporting the report data. I would like to have the name of … -
how to show nifty Sensex values on a Django website
I am new to web development and I want to make a contribution to Django based repo where the news website shows dynamically updating nifty Sensex values , Please tell me how to do it without registering to any website , it it possible ? I tried looking for few websites but since I am very new, any help would be appreciated -
How to use django TemporaryUploadedFile multiple times?
I am trying to create several records in django from a TemporaryUploadedFile object, due to the nature of this, when wanting to create more records, I get the error [Errno 2] No such file or directory: '/tmp/tmpoz8_c7i3.upload. jpg'. I already tried to override the classes, to set delete=False of tempfile.NamedTemporaryFile, but I still get the error. Django Version = 4.1.3 from django.core.files.uploadhandler import FileUploadHandler, TemporaryFileUploadHandler from django.core.files.uploadedfile import UploadedFile import os from django.conf import settings from django.core.files import temp as tempfile class CustomTemporaryFileUploadHandler(TemporaryFileUploadHandler): """ Upload handler that streams data into a temporary file. """ def new_file(self, *args, **kwargs): """ Create the file object to append to as data is coming in. """ super().new_file(*args, **kwargs) self.file = CustomTemporaryUploadedFile( self.file_name, self.content_type, 0, self.charset, self.content_type_extra ) def receive_data_chunk(self, raw_data, start): self.file.write(raw_data) def file_complete(self, file_size): self.file.seek(0) self.file.size = file_size return self.file def upload_interrupted(self): if hasattr(self, "file"): temp_location = self.file.temporary_file_path() try: self.file.close() os.remove(temp_location) except FileNotFoundError: pass class CustomTemporaryUploadedFile(UploadedFile): """ A file uploaded to a temporary location (i.e. stream-to-disk). """ def __init__(self, name, content_type, size, charset, content_type_extra=None): _, ext = os.path.splitext(name) file = tempfile.NamedTemporaryFile( suffix=".upload" + ext, dir=settings.FILE_UPLOAD_TEMP_DIR, delete=False ) super().__init__(file, name, content_type, size, charset, content_type_extra) def temporary_file_path(self): """Return the full path of this file.""" return … -
How to recieve MS Teams created announcements to my webapp python (django)
In my MS teams I create an announcement, the announcement I created will be sent to my webapp python django then stored into my database, is this possible? I've been doing some research and some ways on how to tackle this problem majority of the stuffs ive discover is mostly how to post messages in MS Teams through the connectors. -
Docker Django application deployment
I have a Django app that I am trying to 'Dockerize'. Here is the Dockerfile: FROM python:3.10.12-slim-bullseye ENV PYTHONBUFFERED=1 ENV PORT 8080 WORKDIR /app COPY . /app/ RUN pip install --upgrade pip RUN pip install -r requirements.txt CMD gunicorn django_ec2_complete.wsgi:application --bind 0.0.0.0:"${PORT}" EXPOSE ${PORT} I am following some tutorials and docs and there are for sure mistakes or something I am missing. I can run the following docker build command successfully: docker build -t django-ec2-complete:latest . But, when trying to docker run: docker run -p 8000:8080 django-ec2-complete:latest I get the following Traceback error: [2024-06-03 17:00:52 +0000] [7] [INFO] Starting gunicorn 22.0.0 [2024-06-03 17:00:52 +0000] [7] [INFO] Listening at: http://0.0.0.0:8080 (7) [2024-06-03 17:00:52 +0000] [7] [INFO] Using worker: sync [2024-06-03 17:00:52 +0000] [8] [INFO] Booting worker with pid: 8 [2024-06-03 17:00:52 +0000] [8] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker worker.init_process() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.10/site-packages/gunicorn/util.py", line 371, in import_app mod = importlib.import_module(module) File … -
Doubts deployment in render web
I'm new to deploying web applications, or rather, this is my first time. I'm using the Render deployment application. It has a free plan that allows you to deploy a PostgreSQL database instance, and I also connected my GitHub repository for the application deployment. I'm working on another project and it has its own database because I test them locally on my computer. But I want to upload it to Render, that is, to create another PostgreSQL database, but it tells me that I have to pay, and yes, I am aware that a free plan has its limitations. But my question is that there are some plans that I understand are for having more database instances. There are also plans to improve web page performance. enter image description here enter image description here But some plans confuse me, indicating that they are individual, group, etc., and they are higher prices. My question is, do these prices already include the previous ones I mentioned? Or how does it work? I'm a beginnerenter image description here Help describing me wat should I do, please -
How to improve the speed of adding documents to chromaDB?
I am trying to add chunks of text into ChromaDB. While adding the chunks, the process takes more time due to vectorization. Is there any way to speed up this process? I would like to use **Celery ** for processing each chunk in **parallel **or utilize multiprocessing. This is my sample code snippet: ids = [str(Id) for Id in range(len(splitted_document))] collection.add( ids=ids, documents=splitted_document ) This line of code 'collection.add' takes more time. I want to run the process in the background, especially as a parallel process. I tried using Celery with ChromaDB, but the documents are not being added. I checked this using collection.count(), and it returned 0. Why is this happening? Here is the code: # main.py def FileLoader(file_path): # Code to split the document... ... ... ids = [str(Id) for Id in range(len(splitted_document))] collection.add( ids=ids, documents=splitted_document ) # Call the function process_file.delay(file_path) # tasks.py @shared_task def process_file(file_path): return FileLoader(file_path)Copy cod However, no documents are being added. -
Whitespace inside of social-auth-app-django created OAuth2 URLs
I'm having an issue where my Django application (using social-auth-app-django 5.4.1) is creating URLs that are giving errors when integrated with Google's sign in. The unwrapped text in this error is: Request details: redirect_uri= http://127.0.0.1:8000/accounts/complete/google-oauth2/ flowName=GeneralOAuthFlow There is a whitespace between google-oauth2/ and flowName. Google does not allow whitespace in the names of their redirect URIs. As far as I am aware, I am not in control of how this section of the URL is constructed, so I'm a bit of a loss as to how I am going to resolve this. For context, this error is encountered after attempting to press the below link, wrapped in the social:begin link provided by social-auth-app-django: <a href="{% url 'social:begin' 'google-oauth2' %}" class="btn bsb-btn-xl btn-outline-primary btn-form-orange-inv"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-google" viewBox="0 0 16 16"> <path d="M15.545 6.558a9.42 9.42 0 0 1 .139 1.626c0 2.434-.87 4.492-2.384 5.885h.002C11.978 15.292 10.158 16 8 16A8 8 0 1 1 8 0a7.689 7.689 0 0 1 5.352 2.082l-2.284 2.284A4.347 4.347 0 0 0 8 3.166c-2.087 0-3.86 1.408-4.492 3.304a4.792 4.792 0 0 0 0 3.063h.003c.635 1.893 2.405 3.301 4.492 3.301 1.078 0 2.004-.276 2.722-.764h-.003a3.702 3.702 0 0 0 1.599-2.431H8v-3.08h7.545z" /> </svg> <span class="ms-2 fs-6">Google</span> Related settings … -
Send CSRF token with PUT request by fetch in javascript
fetch("/edit_post", { method: "PUT", body: JSON.stringify({ post_id: post_id, new_message: new_message, }) }).then(response => { if (response.ok) { message_div.innerHTML = new_message; } else{ message_div.firstElementChild.innerHTML = "An unexpected error occured"; } }) I am getting Forbidden (CSRF token missing.) error with above code, how do i send csrf token in fetch? I kinda don't want to include the csrf token in the of the html page if possible. -
Configuring Python/Django to talk to Postgres
I've successfully created a Django project in Pycharm to talk to the default Sqlite3. But now I'd like to switch to Postgress. I have the following in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'jdbc:postgresql://localhost:5432/postgres', 'PORT': '5432' } } But I get this error when trying to run django.db.utils.OperationalError: could not translate host name "jdbc:postgresql://localhost:5432/postgres" to address: Name or service not known I get the same error when trying to run migrate, which I assume is necessary to create the tables -
How to disable https in nginx/django deployed app?
So the problem is that i want to intsall ssl certificate from ZeroSSL. To do this, i should disable https because im verifying domen with uploading HTTP file. Here is the settings.py of django project (related to https): X_FRAME_OPTIONS = 'SAMEORIGIN' # #HTTPS SETTINGS SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True #HSTS SETTINGS SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True myapplicationnamefile nginx configuration: server { listen 80; #listen 443 default_server ssl; server_name example.com www.example.com; return 301 https://www.example.com$request_uri; } server{ client_max_body_size 20M; listen 443 ssl ; # listen 80; server_name example.com www.example.com; ssl_certificate /home/ubuntu/Travel-agency/example.com/certificate.crt; ssl_certificate_key /home/ubuntu/Travel-agency/example.com/private.key; ssl_protocols TLSv1.2 TLSv1.3; # Recommended protocols ssl_ciphers HIGH:!aNULL:!MD5; # Recommended ciphers location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /home/ubuntu/Travel-agency/static; } location /media { alias /home/ubuntu/Travel-agency/media; } location /.well-known/pki-validation{ allow all; alias /home/ubuntu/Travel-agency; add_header Content-Type text/plain; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I've tried clearing the cache; restarting the server with specific lines commented out #listen 443 ssl ; commented this listen 80; uncommented this ; tried to disable http to https redirect in (# return 301 https://example.com$request_uri;); Also tried disabling https redirection in my … -
SELECT typarray FROM pg_type WHERE typname = 'citext' is causing stuck queries in Django 3
SELECT typarray FROM pg_type WHERE typname = 'citext' is causing stuck queries in Django 3. If I kill it, all the other queries will proceed. In this similar question (SELECT typarray FROM pg_type WHERE typname = 'citext'), it is indicated that this is now being cached in later versions of Django. But why is my app still querying it? Is there a configuration that needs to be enabled so that it will be cached? Thanks. -
Failed to load resource: the server responded with a status of 502 () after upgrade ssh server
I made a stupid decision to run do-release-upgrade in ubuntu ssh server and after that, the website is not working. It didn't show the tabs on top after upgrade and reboot of server, it gives this error: Failed to load resource: the server responded with a status of 502 () https://siteurl/api/auth/permissions?email=myemail 502 Bad Gateway nginx/1.15.12 When I tried to manually go to one of the route (for example, siteurl/finance), it gives another error: Error: Uncaught (in promise): Error: NG04002 Error: NG04002 The code is the same as before, and it works fine when running development server in localhost. I noticed that I can't roll back the upgrade, where should I start troubleshooting? (Tried to restart the portainers, they are running fine.) -
Cloudinary API fails to initialise api key when used with Django signals
I made a signal receiver for a model UserFiles and named it upload_to_cloudinary. This receiver calls a function inside it, which uploads a file to cloudinary. This works well enough if the receiver upload_to_cloudinary is inside the same models.py as UserFiles but when I refactored it to signals.py file in the same app and registered in apps.py it is starts to throw error: raise ValueError("Must supply api_key") ValueError: Must supply api_key I expected it to work similarly after refactoring but certainly it doesn't I have all the configurations down in the settings.py file. -
Django messages without reloading the screen
So I am trying to show messages to the user by using django messages when they make any mistake, like trying to add product to a cart without selecting variation, now the problem is, these are all done by js, so if they don't refresh the screen, the users cannot see what mistake they have made. So is there any way I can make django messages appear without reloading the page? If not, what are the alternatives? My base.html: {% if messages %} <div class="container mt-3"> {% for message in messages %} <div class="alert alert-{{ message.tags }}" role="alert"> {{ message }} </div> {% endfor %} </div> {% endif %} My views.py: if product.has_variations and len(selected_variations) != variation_categories: messages.error(request, f"Please select all {variation_categories} variations.") return JsonResponse({'error': f'Please select all {variation_categories} variations.'}, status=400) But this error message currently only appears after reloading the page. -
DRF Given token not valid for any token type
I am creating a simple DRF app and I have problems configuring JWT. My main view looks like this: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = [filters.SearchFilter] filterset_fields = ["category"] authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): queryset = super().get_queryset() category = self.request.query_params.get("category", None) if category: queryset = queryset.filter(category=category) return queryset My urls like this: urlpatterns = [ path("admin/", admin.site.urls), path("product-manager/", include("product_manager.urls")), path("", TokenObtainPairView.as_view(), name='token_obtain_pair') ] Now when I enter the index path and provide username and password in payload I get access and refresh tokens. I copy access token and put in into Authorization section in Postman in JWT Bearer while trying to access my ProductViewSet and I get { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } My settings: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication" ), "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 5, } INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "product_manager", "rest_framework", "rest_framework_simplejwt", ] Chat GPT tells me debug the view, but when I try it, the debugger only stops on the breakpoint on the setup, but not when I try to access the endpoints … -
How do I create a list of category pills for a media blog?
Why isn't it possible for two media articles, created from a Django model (called MediaModule), who have two separate sets of categories? I have a TextField which contains a list of related categories, separated by a comma. I just want to be able to list those categories in my Django template. Why do my articles keep getting the same categories despite having a separate word list in my Django database? models.py: from django.db import models import uuid, random, string def generate_unique_id(charlimit): '''This will generate a random set of numbers and letters which will be used to generate a unique URL for each object in the model. ''' random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=charlimit)) # Generates a random string return f"{random_string}" def generate_unique_uuid(): '''This will generate a random set of numbers and letters which are to be derrived from the UUID methodology, which will be used to generate a unique URL for each object in the model. ''' return str(uuid.uuid4())[:8] # Create your models here. class MediaModule(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_identifier = models.CharField(max_length=50, default=generate_unique_id(12), unique=True, editable=False) article_headline = models.CharField(max_length=100) article_body = models.TextField() article_synopsis = models.TextField(null=True) article_journalist = models.CharField(max_length=20) article_date = models.DateTimeField(auto_now=True) article_image = models.ImageField(upload_to='assets') article_image_summary = models.TextField(default="", null=True, blank=True) …