Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending emails in Celery tasks not executing
I have a view function in Django, which receives a post request with the data of sending letters (the poster post, the topic of the letter, message, etc.) from the user and transmits them to Celery Tasks, to send letters through standard function of the Django send_mail. For some reason, Celery Task is not performed. Using: Django, Redis, Celery, Docker Project structure: sender sender -- init.py -- asgi.py -- celery.py -- settings.py -- urls.py -- wsgi.py emails -- migrations -- init.py -- admin.py -- apps.py -- forms.py -- models.py -- tasks.py -- tests.py -- views.py templates venv db.sqlite3 docker-compose.yml Dockerfile manage.py views.py: from django.shortcuts import render, redirect from .tasks import * from .models import * from .forms import * def send_some_email(request): if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): from_mail = form.cleaned_data['from_mail'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] cat = form.cleaned_data['cat'] limit = form.cleaned_data['limit'] try: send.delay(from_mail, subject, message, cat, limit) return redirect('home') except Exception as ex: print(ex) return redirect('errorpage') else: form = EmailForm() return render(request, 'emails/index.html', {'form': form}) tasks.py: from celery import shared_task from .forms import * from django.core.mail import send_mail @shared_task def send(from_mail, subject, message, cat, limit): for element in Emails.objects.filter(active=True, category__name=cat)[:limit]: send_mail(subject=subject, from_email=from_mail, message=message, recipient_list=[str(element), ]) print(str(element)) … -
Django-guest-user custom name
I am using 'julianwachholz/django-guest-user' library to login as a 'guest user'. The generated user name is long (based on uuid). The library has 3 functions: generate_uuid_username (default) generate_numbered_username generate_friendly_username It uses NAME_GENERATOR (in the AppSettings) to point the desired function. I am new to Django and want help to use this customization. -
Defining the unit of measurement when annotating a django queryset using Distance
I am very new to django / python. I am currently experimenting building a web application using GeoDjango on MySQL/Spatialite (later I will move to postgres/postGIS when I decide to pay for a dedicated environment). I use the following expression to get a queryset which is annotated with the distance of each Splitter's company's service_area's centroid (point field). sl = Splitter.objects.filter(company__in=companies, seats__gte=int(seatval), selfhire=selfval).annotate(distancefrom=Distance('company__service_areas__centroid', postcode_location)).order_by('distancefrom') Not sure if this is important, but I am importing Distance from django.contrib.gis.db.models.functions It works fine, however the default value for the "Distance" calculation is in metres. As such I get annotated values generated that look like this: 46035.39602585269 m I'd much rather get these values in miles or km. How can I alter the expression to force the annotation to be in these units instead? Alternatively what method could I use to update the annotations? I'd rather not iterate over the queryset. Typically distance.mi or distance.km would give me these values, but I am not sure how to do this as part of an annotation? What I tried: I tried simply adding .mi into the expression but it does not seem to work. sl = Splitter.objects.filter(company__in=companies, seats__gte=int(seatval), selfhire=selfval).annotate(distancefrom=Distance('company__service_areas__centroid', postcode_location).mi).order_by('distancefrom') I am reluctant to use a … -
I try to test django model method __str__()
I trying to test str method in model but it do not working. It is my Student model class Student(models.Model): name = models.CharField(max_length = 100) email = models.EmailField(max_length = 277) created_at = models.DateTimeField(auto_now_add = True, null = True) updated_at = models.DateTimeField(auto_now_add = True, null = True) degree=models.BooleanField(default=False) def __str__(self) -> str: return self.name It is my tests.py class StudentCreateTests(TestCase): def create_student(self): student=Student.objects.create( name="tami", email="tami@mail.ru" ) self.assertEqual(student.name, "tami") self.assertEqual(student.email, "tami@mail.ru") self.assertEqual(str(student), student.name) #self.assertEqual(student.__str__(), student.name) What is problem? -
Django managed=False option will not create migrations but will it run manual migration on the table?
I wanted to understand the working of managed = False option in Django models. If managed is set to False then the migrations for the table are not created by issuing the makemigrations command. However, I wanted to know that if there is a manual migration file created and there are altertable commands in the manual migration file for the table for which managed is set to False will running the migrations change the database. Thank you. -
Sorl-thumbnail dont create folder in cache
I get an error instead of thumbnail `[Errno 2] No such file or directory: 'D:\\developer\\love\\love_prim\\media\\Photo object (11)' Remote file [Photo object (11)] at [960x339] does not exist [25/Feb/2023 17:07:53] "GET / HTTP/1.1" 200 3634 Not Found: /media/cache/e5/e6/e5e60125af238c62ca330679f6c18c56.jpg [25/Feb/2023 17:07:53] "GET /media/cache/e5/e6/e5e60125af238c62ca330679f6c18c56.jpg HTTP/1.1" 404 5065 ` Cache directory not created in media folder. The cache directory is not created in the media folder. The image is immediately saved to folder profiles. [[enter image description here](https://i.stack.imgur.com/8NJCD.jpg)](https://i.stack.imgur.com/PrkIg.jpg) Tried to execute commands thumbnail cleanup and thumbnail clear. I also tried to create the cache folder myself with permissions 777. No result. -
how get the count of enum field items in django
I have a field of type enum: place_menu=models.CharField(choices=placeMenu.choices) How can I get count item with value enum? My enum field has four values. And I want to get the count of each value Optimally. -
Why the first() method and slices works differently in Django?
I have this code: print(Pet.objects.all().first()) print(Pet.objects.all()[:1].get()) it seemed to me that the same objects should be displayed, but different ones are returned. What's going on, isn't it an identical design? -
django add url parameter in a view function
I am building a follower list view, frontrend allows user to search followers on a specific user by request.GET After adding the pk on the url in frontend, we use something like /?user=2 To find all followers of user 2. Here’s the issue. The frontend must have user parameter to indicate who you searching, show a user card in the search box. And the backend, if there is no user Param set, will target followers of request.user. When the url is /, I am actually going for /?user=request.user.pk, can I add this parameter in view function? Or how can I re-parse the url and call the view function again when default? Something to add manipulate param before redirect def userFollowerView(request): user = request.GET.get('user', None) if not user: request.path.setParam('user', request.user.pk) return userFollowerView(request) # or redirection return ... The reason I am not using a regex pattern to indicate user Pk and another url for redirection, is that, this is a minimised example, in real life I am dealing with a pk list on other scenario that must be passed as url param. -
command not found - Python Django app deployment issue with DigitalOcean
I’m having a problem with the package gunicorn on the app platform while it’s present in my requirements.txt file. bash: gunicorn: command not found With app platform, I am not able to find the flexibility to change the system configurations. Is there a way I can add the gunicorn binary to $PATH or add a symlink somehow? I tried to build the app again and changed my run configuration but it didn't help. The deployment fails after the build step. This error might make me to configure a bare metal server droplet which would be a bit tedious. Probably a noob question, but could someone help on this? I am blocked by this, so would really appreciate your help! Thank you in advance. -
Getting the most recent versions of entries in a Django model with versioned data
The application I'm working on has a schedule which assigns workers to work in different locations at different time blocks. The schedule is versioned through a ChangeSet model. Each ScheduleEntry references a ChangeSet. class Worker(models.Model): name = models.CharField(max_length=100) class Location(models.Model): name = models.CharField(max_length=100) class TimeBlock(models.Model) start_date = models.DateField() end_date = models.DateField() class ChangeSet(models.Model): published_on = models.DateTimeField(null=True) class ScheduleEntry(models.Model): change_set = models.ForeignKey(ChangeSet, on_delete=models.CASCADE) worker = models.ForeignKey(Worker, on_delete=models.CASCADE) time_block = models.ForeignKey(TimeBlock, on_delete=models.CASCADE) location = models.ForeignKey(Location, null=True, on_delete=models.CASCADE) A worker can only be assigned to one location for each time block. This location is is determined by the ScheduleEntry with the most recent non-null change_set.published_on for that worker and time block. A Worker could be unscheduled (have None for their location) either because there aren't any schedule entries for the worker in that time block, the entries are all linked to unpublished change sets, or the most recent published entry specifies null as the location. Getting the current published schedule location in a specific time block for a worker is easy: ScheduleEntry.objects.filter( change_set__published_on__isnull=False, worker=my_worker, time_block=my_time_block, ).order_by('-change_set__published_on').first() However, I can't figure out how to perform a query to get things like: Full schedule for a worker, across all time blocks All workers scheduled to … -
Django doesn't run if I remove 'command' from docker-compose
Here's how I want to run my container with the following commands: docker-compose up -d --build docker compose up -d docker exec -it app_api bash From there I will have a shell where I can run ./manage.py runserver 0.0.0.0:8000 or makemigrations etc. This docker-compose runs if I uncomment the 'command' line. However, I don't want runserver to run automatically, I just want the shell. docker-compose.yml version: '3.8' services: web: container_name: app_api build: . # command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/project ports: - 8000:8000 depends_on: - db db: image: postgres container_name: app_db environment: POSTGRES_PASSWORD: postgres volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: Dockerfile FROM python:3.9 ENV PYTHONDONTWRITEBYTECODE 1 WORKDIR /project COPY requirements.txt /project/ RUN pip3 install -r requirements.txt COPY . /project/ With the command line commented out and after running docker compose up -d I get: [+] Running 2/2 ⠿ Container app_db Running 0.0s ⠿ Container app_api Started As you can see, app_api is started but not running. -
Properly Structure Multi-app Django Graphene Queries
I started moving my REST API endpoints to using GraphQL with Graphene. Seems pretty straightforward so far, but one of the things that I like about the REST API (and I cannot figure out in Graphene) is the structure of "endpoints" for each app. I have a lot of apps in my Django application, and I would like to group the Graphene queries and mutations of each app under a single "endpoint" (just like you would do in REST by sending a request to app_1/endpoint and app_2/endpoint). Currently I have a graphql folder inside of each app, with files for my queries and mutations inside. Then, under my main schema file, I just create a giant query and mutation objects that inherit from the elements of all other apps. # app1/graphql/queries.py class Endpoint1(DjangoObjectType): class Meta: model = Element1 fields = ("id", "name", "date") # app2/graphql/queries.py class Endpoint2(DjangoObjectType): class Meta: model = Element2 fields = ("id", "name", "date") # Place where my main schema is located # django_project/graphql/queries.py class Queries(Endpoint1, Endpoint2): pass Would it be possible to group queries and mutations from a single app and then just inherit from each of the app's mutations and queries in the main schema, … -
"permission_classes = [IsAuthenticated]" causes error - 'dict' object has no attribute 'exception'
Whenever I add this permission " permission_classes = [IsAuthenticated]" to my viewsets in drf (django rest framework) it throws this exception on the browser when I am not logged in 'dict' object has no attribute 'exception' but if I am logged in everything works fine. If I am not logged in, I want a message like this. {"detail": "Authentication credentials were not provided."} on the browser, which tells the client side what the issue is. This is my views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet, GenericViewSet from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin from rest_framework.decorators import action from .serializers import CategorySerializer, StoreSerializer, SubCategorySerializer, ProductSerializer, LikeProductSerializer, CartSerializer, CartitemSerializer, AddCartItemSerializer, UpdateCartItemSerializer, ReviewSerializer, CustomerSerializer, OrderItemSerializer, OrderSerializer, CreateOderSerializer, UpdateOrderSerializer, SimpleProductSerializer from .models import Category, SubCategory, Products, Cart, CartItems, Reviews, Customer, Order, OrderItem, Store from rest_framework.parsers import MultiPartParser, FormParser from rest_framework import parsers from django.contrib.auth import get_user_model from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter # Create your views here. class ProductViewSet(ModelViewSet): queryset = Products.objects.all() serializer_class = ProductSerializer parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.FileUploadParser) filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields = ["category_id", "subcategory_id"] search_fields = ["name", "description"] permission_classes = [IsAuthenticated] This is the error … -
what kind of the error is these [Errno 111] Connection refused and how to solved it?
i try to send mail using django send_mail but when i try send mail from local it can be work properly but production it say error "[Errno 111] Connection refused" -
I can't make an image as a background in Django
I want to make an image in this /static/img/background.jpg/ directory to become a background-image, but the css is not showing the background image. I think that the problkem is in the header styles but I can't find anythging wrong in there. #index.html <style> .start { background-image: url("{% static 'img/background.jpg' %]"); background-color: #cccccc; height: 500px; background-position: center; background-repeat: no-repeat; background-size: cover; position: relative; } </style> <div class="start"> <img src="{% static 'img/background.img' %}" alt="background"> <h1>DO YOU WANT TO GET BETTER?</h1> </div> #layout.css * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Montserrat', sans-serif; text-decoration: none; list-style: none; } body { min-height: 100vh; } header { width: 100%; top: 0; right: 0; z-index: 1000; display: flex; align-items: center; justify-content: space-between; background: black; padding: 28px 12%; transition: all .50s ease; } -
Django url not matching in production
I have a web app which uses Django4.0.6 and Python3.9. urlpatterns += [ re_path(r'^payment/payment-history/(?P<cand_id>\d+)/(?P<curr_year>\d+)/(?:/(?P<payment_id>-?\d+))?/(?:/(?P<is_email_sent>\d+))?/?$', views.payment_history, name='payment_history') ] I have this regex which works fine when I run my code on my machine using Django runserver command. URL I am trying to match is https://something.com/tenant/payment/payment-history/9299/2023// I deployed the webapp on Python anywhere and suddenly this url patterns don't match. So I did some debugging and found that on production the url that it tries to match is https://something.com/tenant/payment/payment-history/9299/2023/. It ignores the empty part of the url //. I tried to change the regex to urlpatterns += [ re_path(r'^payment/payment-history/(?P<cand_id>\d+)/(?P<curr_year>\d+)/(?:/(?P<payment_id>-?\d+))?/?(?:/(?P<is_email_sent>\d+))?/?$', views.payment_history, name='payment_history') ] The pattern matches but it breaks the feature. Is it possible to force url to match with the empty part of it. Thank you in advance. -
Call OpenAI API inside Django, which way is right way to handle the sync call?
I am trying to call OpenAI API which is synchronous API call, it may block for several seconds. But as my site has many users, so can't afford to wait on the blocking call. I am wondering is there any standard way to handle this situation, like: Client issue ajax request to django The django server queue the request and notify another server task The server task dequeue the request and process it in blocking way After the process done, the task notify django, and then the client get the response -
I have a project given named backend,I created login api and email sending app in different folder,How do I merge them to backend project,
I have project named backend,,I created login api and email sending from django in different directory,,NOw I have to merge login api and email to "backend"project and push to github,,I got error while merging I tried to merge by combininig all views.py to backends view.py,all serializers.py to backends serializers.py and others too..It still shows some error -
Talk to Docker containers using Django App
So I have an python application with multiple files and some data. I am creating a website in which I want to use that application, the way I have to use it is using Docker containers. So basically I will create a docker image of the application, now I want to send data and receive data to that image using my Django backend. Is there a way to do it? I am trying to find resources related to this, but online everywhere it shows How to Dockerize your Django App rather than how to communicate with docker images using Django App. I would be grateful if someone could point me to any resources where I can learn this, any code examples or any tutorials will be very helpful. -
Django-guardian has_perm("codename", obj) is False even if group has the permission
I'm trying to implement django-guardian permissions in my project. In the TestCase below, I assigned view_income permission to staff group. That means, also user_c has the permission. The problem is that self.user_c.has_perm("view_income", income) returns False. To be clear, I understand how it works and that I can check first the group permission without object. I'm curious if there is a shortcut that will tell me whether a given user has a permission to a given object no matter if it is defined in a group, if it is an object permission or general permission etc... I don't want to write multiple different checks every time I want to check permissions. class IncomePermissionsTestCase(TestCase): def setUp(self): self.user_a = baker.make(settings.AUTH_USER_MODEL) self.user_c = baker.make(settings.AUTH_USER_MODEL) staff_group:Group = baker.make('Group', name='staff') assign_perm('view_income', staff_group) self.user_c.groups.add(staff_group) def test_permissions(self): income = baker.make("clients.Income", client=self.user_a) self.assertTrue(self.user_a.has_perm("view_income", income)) self.assertTrue(self.user_c.has_perm("view_income", income)) -
How can I optimize this code and/or make it DRYer?
I'm just getting started with the django ORM and i have this code. # if UP object exists, update it if UserProgress.objects.filter( user=current_user, card=Card.objects.get(id=submitted_card_id) ).exists(): # if card is understood, update the date_understood datetime field if submitted_understood == True: UserProgress.objects.filter( user=current_user, card=Card.objects.get(id=submitted_card_id) ).update( is_understood=submitted_understood, date_understood=datetime.now(), times_seen=F("times_seen") + 1, ) # if not, simply update the object else: UserProgress.objects.filter( user=current_user, card=Card.objects.get(id=submitted_card_id) ).update( is_understood=submitted_understood, times_seen=F("times_seen") + 1, ) # if UP object does NOT exist, create it else: if submitted_understood == True: UserProgress.objects.create( user=current_user, card=Card.objects.get(id=submitted_card_id), is_understood=submitted_understood, date_understood=datetime.now(), times_seen=1, ) else: UserProgress.objects.create( user=current_user, card=Card.objects.get(id=submitted_card_id), is_understood=submitted_understood, times_seen=1, ) i've tried to make this code a little cleaner and potentially optimize how many times the DB is being queried, but can't think of any other way to do it. both submitted_card_id and submitted_understood are form fields. -
Custom permission in django rest framework
I want to write a custom permission to restrict access to the display picture of a user. My user profile model is called Member and the implementation is as follows: # imports class Member(models.Model): created_at = models.DateTimeField(auto_now_add=True) user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=True) sex = models.IntegerField(choices=[(0, 'Unknown'), (1, 'Male'), (2, 'Female'), (9, 'Not Applicable')]) date_of_birth = models.DateField() bio = models.TextField(null=True) def __str__(self) -> str: return self.user.username def _display_picture_upload_path(instance, filename: str): return f'members/display/{instance.member}.jpg' class MemberDisplayPicture(models.Model): created_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to=_display_picture_upload_path) member = models.OneToOneField(to=Member, on_delete=models.CASCADE, related_name='display_picture', unique=True) The serializer for MemberDisplayPicture: class MemberDisplayPictureSerializer(serializers.ModelSerializer): class Meta: model = MemberDisplayPicture fields = ['id', 'image'] def create(self, validated_data): member_id = self.context['member_id'] instance = MemberDisplayPicture.objects.create(member_id=member_id, **validated_data) return instance A view at /{app_name}/members/{pk}/display-picture/ allows to retrieve, create and delete a display picture: class MemberDisplayPictureAPI(RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, GenericAPIView): http_method_names = ['get', 'post', 'delete'] serializer_class = MemberDisplayPictureSerializer def get_member_id(self): member_id = self.kwargs['pk'] return member_id def get_queryset(self): return MemberDisplayPicture.objects.filter(member_id=self.get_member_id()) def get_object(self): queryset = self.filter_queryset(queryset=self.get_queryset()) obj = get_object_or_404(queryset) self.check_object_permissions(self.request, obj) return obj def get_serializer_context(self): return {'member_id': self.get_member_id()} def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) The custom permission should: Only allow authenticated … -
Persist user options, React
I am using JWT in a React-Django app to handle user authentication. I can register, login, and logout successfully. However, user data does not persist on the frontend. All of the tutorials and articles I've seen online suggest storing user data in local storage to persist the data, but I've also heard this isn't an excellent choice. Is there a better option? Can y'all point me towards articles/resources that cover any better options? Thanks -
Relative path import not working in main.js inside Django project
I have a javascript file main.js inside my Django project. I need to import into main.js the papaparse javascript module. I downloaded and saved papaparse.min.js inside my static folder. When I try to import papaparse into main.js, my script fails. My folder structure is set up like this: static .....js ..........main.js ..........papaparse.min.js I should mention, I tried running papaparse functions in-line in my html file and it works. So, I know there is no problem with the papaparse.min.js itself. Additionally, my settings life should be good since the main.js file is read in perfectly fine in my index.html: </div> <script src="{% static 'js/main.js' %}"></script> </body> </html> ^ This works fine. I've tried to do the import several ways. import * as pp from './papaparse.min.js'; console.log('made it past import'); import Papa from './papaparse.min.js'; console.log('made it past import'); import {Papa} from './papaparse.min.js'; console.log('made it past import'); When commenting out the import statement, the console will print "made it past import." If left uncommented, the console prints nothing. For troubleshooting purposes, the import statement and the console.log state are the only uncommented lines in main.js to verify that it's the import statement that's the problem. I've had some more experienced javascript coders (I'm …