Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Unable to Get Redis Working with Django on Windows
I'm working on a Django Channels project that requires Redis as the channel_layer. However, I've discovered that Redis is not natively supported on Windows, as it's primarily designed for Linux environments. While I understand that I can use Docker or a Virtual Machine to run Redis on Windows, I'm looking for an alternative solution that allows me to use Redis without relying on Docker or any Virtual Machine. Is there any way to set up Redis on Windows that avoids these options? Any guidance or suggestions would be greatly appreciated. -
Server Error (500) and strange symbols inside a form
I set up a Raspberry Pi with Ubuntu server as OS. I followed this guide: Guide from digitalocean It all seemed to work good until I opened a page with a form that looks some kind of strange (unwanted brackets before and after "Name:": The code behind looks like this: # models.py class Category(models.Model): name = models.CharField(max_length=50) def __str__(self) -> str: return self.name # forms.py class CategoryForm(forms.ModelForm): class Meta: fields="__all__" model = Category widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}) } # views.py def categories(request: HttpRequest): if request.method == 'POST': filledForm = CategoryForm(data=request.POST) if filledForm.is_valid(): newCategory = filledForm newCategory.save() categoryForm = CategoryForm() categories = Category.objects.order_by('name') args = { 'categoryForm': categoryForm, 'categories': categories, } return render(request, 'categories.html', args) And the HTML code: <div class="container"> <h2>Categories</h2> <br> <form action="{% url 'categories' %}" method="post"> {% csrf_token %} {{ categoryForm }} <input type="submit" class="form-control btn-secondary" name="submit-new-category" value="Add"> </form> <br> <table class="table table-hover"> <tbody> {% for category in categories %} <tr> <td> <a href="{% url 'category_edit' category.id %}"> <div> {{ category.name }} </div> </a> </td> </tr> {% endfor %} </tbody> </table> </div> When I try to post a filled Category-Form, Apache answers with a Server Error (500). I checked the log file (/var/log/apache2/error.log), but there is … -
Class Based View for User Registraion using Django
Which Class Based View is perfect for User Registration ? from django.views.generic.edit import FormView or from django.views import View Is there any other Class Based View for User Registration ? -
TypeError: Object of type CartItem is not JSON serializable
I've a view class which stores the list of cartItem object in the session: View class: class AddCart(View): def post(self, *args, **kwargs): prod_id = self.request.POST.get('prod-id') product = Product.objects.get(pk=prod_id) quantity = int(self.request.POST.get('quantity')) cart = self.request.session.get('CART_ID') if cart is None: cart = Cart(self.request) cartItem = CartItem(product_id=prod_id, name=product.name, quantity=quantity, image=product.image, totalprice=float(product.price) * quantity, unitprice=product.price) cart.update(cartItem) print("Cart updated in View") # del self.request.session[settings.CART_ID] return JsonResponse({'status': 'Added to cart'}) Cart class looks like: class Cart(object): def __init__(self, request): # def __init__(self): self.session = request.session cart_id = settings.CART_ID cart = request.session.get(cart_id) self.cart = cart if cart else [] # self.cart = [] def update(self, cartItem): cartList = self.cart print("cart list",cartList, "cartItem:",cartItem) found = False totalquantity = 0 for cart in cartList: if cart.product_id == cartItem.product_id: found = True totalquantity = cart.quantity + cartItem.quantity cartList.remove(cart) if not found: cartList.append(cartItem) else: newItem = CartItem(product_id=cartItem.product_id,name=cartItem.name,image=cartItem.image,quantity=totalquantity,unitprice=cartItem.unitprice,totalprice=totalquantity*cartItem.unitprice) cartList.append(newItem) self.cart = cartList self.session[settings.CART_ID] = cartList def __len__(self): return len(self.cart) CartItem class looks like: class CartItem(object): def __init__(self, product_id, name, image, quantity, unitprice, totalprice): self.product_id = product_id self.name = name self.image = image self.quantity = quantity self.unitprice = unitprice self.totalprice = totalprice def __str__(self): return f"{self.product_id}-{self.name}-{self.image}-{self.quantity}-{self.unitprice}-{self.totalprice}" But when post method of AddCart view called get below error: Last few lines of stack Trace: … -
How to filter a query in Django for week_day using a specific timezone?
I am trying to filter data by the day of the week. That's easy enough with the week_day filter. The problem is, since all dates are stored as UTC, that is how it's filtered. How can I localize a query? For instance, trying to count all the records that have been created on specific days, I use this: chart_data = [ data.filter(created__week_day=1).count(), # Sunday data.filter(created__week_day=2).count(), # Monday data.filter(created__week_day=3).count(), # Tuesday data.filter(created__week_day=4).count(), # Wednesday data.filter(created__week_day=5).count(), # Thursday data.filter(created__week_day=6).count(), # Friday data.filter(created__week_day=7).count(), # Saturday ] How can I get these queries to count those records localized to the 'America/New_York' timezone, for instance? -
Postbuild command in elastic beanstalk doesn't work but command works when ssh into EC2 instance
In my current setup, I have a django backend running in Elastic Beanstalk and a private RDS instance using mysql engine. When I deploy, I want to migrate any migrations that haven't been migrated yet. This is the config file in my .ebextensions: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 /var/app/current/python/manage.py migrate --noinput" leader_only: true This deploys successfully, but when I check the logs it gives me this output: [INFO] Command 01_migrate [INFO] -----------------------Command Output----------------------- [INFO] Operations to perform: [INFO] Apply all migrations: admin, app, auth, contenttypes, sessions [INFO] Running migrations: [INFO] No migrations to apply. It says no migrations to apply when there are migrations that haven't been applied yet. I ran the same exact command after I ssh into the EC2 instance for my EB application and it applied the migrations successfully. I can't troubleshoot what the problem may be. -
Auto-fill form fields in clean() method
I use model form for editing records in DB. I have some business logic for auto-fill attributes, which should happen after passing validation of some business rules. In some cases, that auto-fill is based both on instance initial attributes values and current form fields values. For example, different rules apply whether it was a change of some attribute or not. Note: I have no such cases when auto-fill based on other models except one that model form based on. So my question: Is it correct to auto-fill attributes in form clean() method? After reading a few various sources, I'm not sure I fully understood if it's acceptable and if it is, in what cases. A few words why it's not convenient for me to separate validation and auto-fill: My case is that I have quite complex validation rules and almost every time these rules passed, I need to do some auto-filling. For now I have 2 methods, one in form clean() method for validation, and one in form save() method for auto-filling. Every time I need to change business rules, I should make changes in both these methods. It's not very convenient and besides that can lead to slowing down … -
Django: Templates template not found when attempting to access function rendering template
I have a file structure: Resilience_Radar_R2 Leadership_Questions_App Leadership_Questions templates questions.html I have defined a function, riskindex, that should render questions.html and include some text on the page. I also have an index function that simply sends an HttpResponse if teh request is blank The index function works fine at http://127.0.0.1:8000/Leadership_Questions_App/ but the riskindex at http://127.0.0.1:8000/Leadership_Questions_App/riskindex returns an error: TemplateDoesNotExist at /Leadership_Questions_App/riskindex/ Leadership_Questions/questions.html Request Method: GET Request URL: http://127.0.0.1:8000/Leadership_Questions_App/riskindex/ Django Version: 5.0.7 Exception Type: TemplateDoesNotExist Exception Value: Leadership_Questions/questions.html Exception Location: /Users/xxx/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages/django/template/loader.py, line 19, in get_template Raised during: Leadership_Questions_App.views.riskindex Python Executable: /Users/xxx/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/bin/python Python Version: 3.12.3 Python Path: ['/Users/xxx/Documents/Work/Python ' 'Projects/Dashboard/Reslience_Radar_R2', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python312.zip', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/lib-dynload', '/Users/xxx/Documents/Work/Python ' 'Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages'] Server time: Sat, 10 Aug 2024 19:44:06 +0000 Terminal directory is: (.venv) (base) xxx@MacBook-Pro Reslience_Radar_R2 % It appears to be looking in different directory than the one where the python code resides. Reslience_Radar_R2 urls.py rom django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('Leadership_Questions_App/', include("Leadership_Questions_App.urls")) ] Leadership_Questions_App urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("riskindex/", views.riskindex, name="riskindex"), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Leadership Questions") def riskindex(request): description = … -
Why is it possible to create a model with a ManyToManyField without providing a value for the ManyToManyField?
As every field in django model is required. So how when creating an object of model which is having a field with many to many relationship to another model. We can create this model object without specifying many-to-many field value ?