Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF issue while calling the api from the frontend [closed]
Create_admin.py def create_agent(request): if request.method == 'POST': name = request.POST.get('name') username = request.POST.get('username') password = request.POST.get('password') if name and username and password: agent = Agent.objects.create(name=name, username=username, password=password) return JsonResponse({'status': 'success'}) return JsonResponse({'status': 'failed'}, status=400) return render(request, 'superadmin/create_agent.html') @user_passes_test(is_super_admin) def fetch_payments(request): if request.method == 'GET': payments = Payment.objects.all().values() # Fetch all payment data return JsonResponse(list(payments), safe=False) class PaymentListView(APIView): def get(self, request): payments = Payment.objects.all() data = [ { "id": payment.id, "agent_name": payment.agent_name, "amount": payment.amount, "payment_link": payment.payment_link, "status": payment.status, "created_at": payment.created_at, } for payment in payments ] return JsonResponse(data, safe=False) create_admin.jsx const handleCreateAgent = async (e) => { e.preventDefault(); const csrfToken = getCSRFToken(); // Get the CSRF token try { const response = await axios.post('http://127.0.0.1:8000/api/superadmin/create-agent/', { username, password, name: agentName, }, { headers: { 'X-CSRFToken': csrfToken, // Include the CSRF token in the headers }, withCredentials: true }); setMessage('Agent created successfully!'); setUsername(''); setPassword(''); setAgentName(''); } catch (error) { console.error('There was an error creating the agent!', error); setMessage('Failed to create agent.'); } }; Forbidden (CSRF cookie not set.): /api/superadmin/create-agent/ [13/Aug/2024 12:32:07] "POST /api/superadmin/create-agent/ HTTP/1.1" 403 2869 This the error that i'm getting when calling the api from the frontend.isssue is that i have already set the cookies thing CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_HTTPONLY = … -
Can't use psycopg3 on Mac?
My Django project currently uses psycopg2. When I try to switch to psycopg3, I get the following error: OSError: cannot load library 'pango-1.0-0' I tried upgrading pip, reinstalling pango, and I also tried starting over with a fresh virtualenv. I still get the same error. I'm using Django 4.2 with Python 3.10 -
Django,There is no module named "myapp"
enter image description here PS C:\Users\taipe\firstproject> & C:/Users/taipe/AppData/Local/Programs/Python/Python312/python.exe c:/Users/taipe/firstproject/firstproject/urls.py Traceback (most recent call last): File "c:\Users\taipe\firstproject\firstproject\urls.py", line 19, in from myapp.views import sayhello,sayhello2,hello3 ModuleNotFoundError: No module named 'myapp' PS C:\Users\taipe\firstproject> enter image description here I don`t know why there is the problem of "no module named "myapp" ". however, there actually is a "myapp" folder in my "firstproject". -
Django generic DetailView: what is the best way to optionally include a reverse-related object?
Background Models Let's say I have a django generic DetailView that I use to display a single object instance of a model called Car. Then let's say I have another model called Race. Among many fields, this Race model has a ForeignKey field that is linked to Car (i.e., the Car that a Driver (user) used for a Race). Example models.py from django.conf import settings class Car(models.Model): """ a bunch of fields, including many fk fields """ class Race(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="races") driver = models.models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) """ a bunch of other fields, including fk fields """ View Now let's say I have a generic DetailView that my website's users have used for a long time to see a single car object. Example views.py This has a very simplified queryset (my actual queryset has the same sort of structure but more reverse-related fields with their respective related fields). from django.views import generic class CarDetailView(generic.DetailView): model = Car queryset = Car.objects.select_related( """ a bunch of related fields """ ).prefetch_related( """ some reverse related fields """, Prefetch(""" a reverse related field """, SomeReverseRelatedField.objects.select_related(""" some of its related fields """)), ) New feature :) Recently, however, I've implemented a way for my … -
Django: how do I make a dependent dropdown load a filtered list of objects on the update form?
I have multiple dependent dropdowns throughout my application. To add a new record, the form works as expected; for example, you select a Country and the list of State objects for that Country will load, you then select a State and the Suburb objects for that State will load. You save the record, it has all the fields saved correctly, you view the record and all the info can be viewed all as expected. The problem I have is when I want to change/update the record. The instantiated SuburbForm is told to first load a blank dropdown for State, and call a function load_dropdowns when the parent object Country has been set. This action of calling load_dropdowns does not seem to happen in the update form, instead it just stays blank, even if I try to re-select the parent. If I change the instantiated form to load all objects instead of the blank dropdown, the update form fills in the field correctly, but that means the add new and update forms now load all objects instead of the filtered list. models.py from django.db import models class Country(models.Model): item_name = models.CharField(verbose_name="Country") class State(models.Model): item_name = models.CharField(verbose_name="State") state_in_country = models.ForeignKey(Country, on_delete=models.SET_NULL, verbose_name="Country", … -
How to concatenate in Dango annotate()
I want to concatenate a string variable with one of my field, but can't figure out what I'm doing wrong I tried this, where prefix is a string and filename_mask is a field in the table plots = ( PlotDefinitions.objects.filter(is_active=True) .annotate( filename=Concat(Value(prefix), 'filename_mask') ) .values('name', 'description', 'filename') ) I get the error Expression contains mixed types: CharField, TextField. You must set output_field. even though I'm concatenating 2 String type. So I added output_field plots = ( PlotDefinitions.objects.filter(is_active=True) .annotate( filename=Concat(Value(prefix), 'filename_mask', output_field=CharField()) ) .values('name', 'description', 'filename') ) but this gives me the error "'CharField' object has no attribute 'get_internal_type'" -
Nested Serializer with Foreign Key and to_field
Stock model has a OneToMany relationship with Data model. I am using the to_field to link them via model_number field. class Stock(models.Model): model_number = models.CharField(max_length=100, unique=True, null=True) model = models.CharField(max_length=100) brand = models.CharField(max_length=100) msrp = models.IntegerField(default=0) def __str__(self): return f"{self.brand} - {self.model} - {self.model_number}" class Data(models.Model): model_number = models.ForeignKey(Stock, to_field='model_number', on_delete=models.CASCADE) price = models.FloatField() date = models.DateField() def __str__(self): return self.model_number I have my serializers to show each model number and then the nested relationship of data. class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' class StockSerializer(serializers.ModelSerializer): data = DataSerializer(many=True, read_only=True) class Meta: model = Stock fields = ['brand', 'model', 'model_number', 'msrp', 'data'] However the price does not return at all in my API view. Not sure where I am going wrong on this. -
Django 5 update_or_create reverse one to one field
On Django 4.x Code is working as expected from django.db import models class Project(models.Model): rough_data = models.OneToOneField( "Data", related_name="rough_project", on_delete=models.SET_NULL, null=True, blank=True, ) final_data = models.OneToOneField( "Data", related_name="final_project", on_delete=models.SET_NULL, null=True, blank=True, ) data, created = Data.objects.update_or_create( rough_project=project, defaults=data ) On Django 5.x: ValueError: The following fields do not exist in this model: rough_project I do not see any changes related to this in changelog -
Django- How to retrive ChoiceField value from a form?
I want to get the selected choice from a ChoiceField in a view. When I submit the form, I process it in a view: views.py def myFormSubmitView(request): ... if form.is_valid(): print("valid form") post = Post() post.title = form.cleaned_data["title"] post.body = form.cleaned_data["body"] **>>>>post.choice_test = form.cleaned_data["choice_test"]** post.save() return HttpResponseRedirect(request.path_info) I want to get the value of choice_test. How can I do that ? -
AttributeError: /usr/lib/libgdal.so.20: undefined symbol: OSRSetAxisMappingStrategy
I'm trying to start my project in docker, it was working great, but now something happened and it can't start. It crashes with AttributeError: /usr/lib/libgdal.so.20: undefined symbol: OSRSetAxisMappingStrategy I searched a lot but have no idea how to make it work. I've tried updating all the libs I have, but no effect whatsoever. Here's what I use: Django Postgis Docker-compose Docker My docker configuration: FROM python:3.11-buster # Set work directory WORKDIR /app # Install system dependencies RUN apt-get update \ && apt-get install -y \ binutils \ libproj-dev \ gdal-bin \ libgdal-dev \ postgresql-client \ && rm -rf /var/lib/apt/lists/* \ ENV CPLUS_INCLUDE_PATH=/usr/include/gdal ENV C_INCLUDE_PATH=/usr/include/gdal # Install Poetry COPY pyproject.toml poetry.lock* ./ RUN pip install poetry && \ poetry config virtualenvs.create false && \ poetry install --no-dev # Copy the application code COPY . . # Expose ports EXPOSE 8000 EXPOSE 8001 # Run the application ENTRYPOINT ["sh", "-c", "poetry run gunicorn app.wsgi:application --bind 0.0.0.0:8000"] -
Django complex relation with joins
I have the following models: class Position(BaseModel): name = models.CharField() class Metric(BaseModel): name = models.CharField() class PositionKPI(BaseModel): position = models.ForeignKey(Position) metric = models.ForeignKey(Metric) expectation = models.FloatField() class Employee(BaseModel): position = models.ForeignKey(Position) class EmployeeKPI(BaseModel): employee = models.ForeignKey(Employee) metric = models.ForeignKey(Metric) value = models.FloatField() def kpi(self): return PositionKPI.objects.filter(position=self.employee.position, metric=self.metric).first() I believe it's possible to rewrite the kpi method as a relation. In SQL it would look something like this: select positionkpi.* from employeekpi join employee on employee.id = employeekpi.employee_id join positionkpi on positionkpi.id = employee.position_id and positionkpi.metric_id = employeekpi.metric_id Please advise how to do it -
Huey consumer with Django on Heroku
I am trying to use Huey with Django on Heroko. The Django app starts up as well as the consumer. i can see both logfiles on my dashboard. The Django app runs without problems when a task is enqueued or called the consumer does not register the task and nothing happens. My Procfile starts the consumer with worker: python manage.py run_huey, When I run it locally everything works fine. Any pointers? -
Invalid templates library specified. ImportError raised when trying to load 'django.templates.defaulttags': No module named 'django.templates'
Can anyone help me to solve this problem? when I try to run this django "py manage.py runserver" then I received error "Invalid templates library specified. ImportError raised when trying to load 'django.templates.defaulttags': No module named 'django.templates'" I'm not using templates for this particular project because my team was planning to separate frontend and backend of our app. Anyone can help me or give advise. We're hoping to use other framework other than laravel so I hope our learning journey keeps goin before giving up *hope not Solution or Advice PLEASE -
Django annotation returns 1 for each item
I have 2 almost identical models. class FavoriteBook(models.Model): class Meta: # Model for books added as favorites verbose_name = "Favorite Book" unique_together = ['user', 'book'] user = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE, verbose_name="User", related_name="favorite_books") book = models.ForeignKey(Book, null=False, blank=False, on_delete=models.CASCADE, verbose_name="Book") def __str__(self): return "{user} added {book} to favorites".format(user=self.user, book=self.book) class SpoilerVote(models.Model): class Meta: # Model for votes of book spoilers verbose_name = "Spoiler Vote" unique_together = ['spoiler', 'user'] spoiler = models.ForeignKey(Spoiler, null=False, blank=False, on_delete=models.CASCADE, verbose_name="Spoiler") user = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE, verbose_name="User", related_name="bookspoiler_votes") choices = ( ('U', 'UP'), ('D', 'DOWN'), ) vote = models.CharField(max_length=1, choices=choices, null=False, blank=False, verbose_name="Vote") def __str__(self): return "{user} liked {book}'s spoiler".format(user=self.user, book=self.spoiler.book.book_title) Following query works fine for FavoriteBook model. most_popular = FavoriteBook.objects.values("book", "book__book_title", "book__year").annotate(count=Count("book")).order_by("-count")[:20] But this one does not work for SpoilerVote model. It returns 1 for each item. SpoilerVote.objects.values("spoiler", "user", "vote").annotate(count=Count("spoiler")).order_by("-count") What am I missing? There is no difference whatsoever. -
Error compressing download.gif: Compressed file not found: /tmp/download_compressed.gif
i am trying to compress the gif file but getting the following error. it says not able to find the file when trying to upload it to s3. MoviePy - Building file /tmp/download_compressed.gif MoviePy - - Generating GIF frames. MoviePy - - Optimizing GIF with ImageMagick. MoviePy - - File ready: /tmp/download_compressed.gif. File does not exist after retries: /tmp/download_compressed.gif Error compressing download.gif: Compressed file not found: /tmp/download_compressed.gif below is my django view that handles the conversion: import os import re import time import tempfile import boto3 from django.conf import settings from django.core.files.base import ContentFile from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from moviepy.editor import VideoFileClip import logging logger = logging.getLogger(__name__) class CompressGifView(APIView): def post(self, request, *args, **kwargs): logger.debug("Received GIF compression request") files = request.FILES.getlist('files') s3 = boto3.client('s3') bucket_name = settings.AWS_STORAGE_BUCKET_NAME folder = 'compressed_gifs/' download_links = [] success = [] converted_file_paths = [] channel_layer = get_channel_layer() def sanitize_group_name(name): sanitized_name = re.sub(r'[^a-zA-Z0-9-_\.]', '_', name) sanitized_name = sanitized_name[:99] return sanitized_name def check_file_existence(file_path): retries = 10 while retries > 0: if os.path.isfile(file_path): logger.debug(f"File exists: {file_path}") return True time.sleep(1) retries -= 1 logger.error(f"File does not exist after retries: {file_path}") return False def … -
removing data migrations in Django
I have been working on a Django app for a client. throughout development there have been data migrations (data insertions/modifications, not structural changes) that have been specific to the client. I am now working on bringing on other clients to use the same app, so I want all reminents of the client specific data removed from the migration files. I feel like the safe and simple way is to keep those migration files and just erase the data migration operations logic. I dont see any reason to keep the data migration logic around anyways, even for the initial client, as it has already been tested and applied in their production environment a while ago. My question: Is this solution sound or are there other points that should be considered? I've searched on the matter, but have not found anything relating to a situation like mine where the data migrations will be introduced to a context where they are incorrect. -
Remote tcp connexion to postgresql not responding
I can't connect to my remote postgresql server. I'm on a local network containing my server (192.168.1.2) and my development workstation (192.168.1.3). I can't connect to my database on port 5432. My server receives TCP frames but does not respond. The other protocols SSH, HTTP are working. However, I can connect to the database on my server on interfaces 127.0.0.1 and 192.168.1.2. On my server, I've modified the pg_hba.conf and postgresql.conf files, adding the lines host and listen_addresses = '*'. Port 5432 is open and listening. The strange thing is that my workstation sends requests on my server's port (tcpdump below) but doesn't respond (no ack). Everything seems correct but it doesn't work. Do you have any idea ? What am I missing? DJANGO SETTINGS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ering', 'USER': 'marika', 'PASSWORD': '123456789', 'HOST': '192.168.1.2', 'PORT': '5432', } } PG_HBA.CONF local all postgres peer local all all trust local replication all peer host replication all 127.0.0.1/32 scram-sha-256 host replication all ::1/128 scram-sha-256 host all all 0.0.0.0/0 md5 host all all ::/0 md5 SYSTEMCTL STATUS ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled) Active: active (exited) since Mon 2024-08-12 11:26:25 CEST; 4min … -
Vector Search with PGVector takes more time
I am using PGVector in Django to make a Vector Search. The time it takes to find the matching row is in few milliseconds, the code I use for it is embedding=self.get_input_embedding(inputText) output=( table.objects.annotate( distance=CosineDistance("embedding",embedding) ) .order_by(CosineDistance("embedding",embedding)) .filter(distance__lt=1-threshold)[:2] ) The output variable is of class type QuerySet. Now to get the value from it I am using the code for neigh in output: print(neigh.Link) Now this block is taking more than 3 seconds. What possibly is the reason for this? -
CSS Not Loading for Browsable APIs in Django with DRF Despite Whitenoise
I am working on a Django project utilizing Django Rest Framework for APIs. I've encountered an issue where the CSS is not loading for the browsable APIs. I am using Whitenoise to serve static files, but the problem persists. Here’s the relevant part of my settings.py: STATIC_LOCATION = "assets/" MEDIA_LOCATION = "media/" STATICFILES_DIRS = [ BASE_DIR / "assets", ] STATIC_ROOT: str = "static" MEDIA_ROOT: str = "media" STATIC_URL = "/assets/" MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", #... ] STORAGES = { "staticfiles": { "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", }, } My custom css and js are stored in assets dictory and i want to store correct static files in static dir. I've followed the standard configuration for Whitenoise, but its rendering a blank page without html and css for the DRF browsable API. I have also tried without whitenoise, and it is serving html file without statics(css and js). Any suggestions or guidance on what might be going wrong or what else I should check would be greatly appreciated! -
FAQ FUNCTIONALITY implement into blog section
Please guide me how we implement question & answer based FAQ series as per our different blog. each blog have different FAQ. How admin can add multiple FAQ as per requirement. how this functionality update the database dynamically... admin and frontend logic or provide guidance -
anymail with django framework setting the cc in the email message is not working
I am using Django+Anymail to send email notifications via mandril but if I try to add cc in the email message then that gets converted to to message and you won't see the cc details in your email client. -
How to add the evey objects to Many-to-Many relationship model
class MyUserGroup(BaseModel): my_user_types = m.ManyToManyField('MyUserType',blank=True) I have this models which has the many-to-many relation ship to type. Now I want to give the every MyUserType objects to this model such as muy = MyUserType() muy.save() muy.my_user_types.add(MyUserType.objects.all()) However this shows the error like this, TypeError: Field 'id' expected a number but got <SafeDeleteQueryset [<MyUserType:A>, <MyUserType: B>, <MyUserType: C>]>. How can I make this? -
How can I filter, search, and sort fields from a GenericForeignKey that have a GenericRelation in Django?
I have a Django model, AssetAssociation, which contains a GenericForeignKey to various models (Assets, User, Locations). The AssetAssociation model looks like this: from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey class AssetAssociation(models.Model): asset = models.ForeignKey(Assets, on_delete=models.CASCADE, related_name='asset_association') target_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) target_id = models.UUIDField() target_object = GenericForeignKey('target_type', 'target_id') # User / Asset / Location checkout_date = models.DateField(null=True, blank=True) expected_checkin_date = models.DateField(null=True, blank=True) checkin_date = models.DateField(null=True, blank=True) action_type = models.CharField(max_length=50, choices=ASSOCIATION_ACTION_TYPE_CHOICES) And here are the related models: from django.contrib.contenttypes.fields import GenericRelation class Assets(models.Model): name = models.CharField(max_length=100, blank=True, null=True) asset_tag = models.CharField(max_length=255) asset_associations = GenericRelation('AssetAssociation', content_type_field='target_type', object_id_field='target_id') class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) asset_associations = GenericRelation('AssetAssociation', content_type_field='target_type', object_id_field='target_id') class Locations(models.Model): name = models.CharField(max_length=100) asset_associations = GenericRelation('AssetAssociation', content_type_field='target_type', object_id_field='target_id') How can I effectively filter and sort on these fields using Django's ORM? Specifically, how do I write a filter function that allows filtering on these fields by using the GenericRelation? -
Django template does not inherit tag from parent
I would like to get a clarification of the following. Is it necessary to add the {% load static %} tag on every child template in my project? So far I have not been able to get my child templates to inherit this tag from their parents. However, the book I read states the following "We need to add the static files to our templates by adding {% load static %} to the top of base.html. Because our other templates inherit from base.html, we only have to add this once." This appears not be true from my experience. thanks for you help. -
How to get current user in save method of a django model?
I have the following django model: class Listing(models.Model): STATUS_CHOICES = [ ('available', 'Available'), ('rented', 'Rented'), ('unavailable', 'Unavailable'), ('fake', 'Fake'), ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) description = models.TextField() status = models.CharField(max_length=12, choices=STATUS_CHOICES, default='available') def save(self, *args, **kwargs): ## if self.status == 'fake' and ......: raise PermissionDenied("Cannot save listing with 'fake' status for non-admin users.") super().save(*args, **kwargs) I wander how I can get the current authenticated user to see if that user is superuser then they can set the status to fake, others cannot. I I try to see what is in args and kwargs. But they are empty