Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to pass Django template language variables to JavaScript files
The question is partially related to this one here. In addition it should be noted that the notation used below is no safe. For more details see this blog post. I have a Django project that references multiple JS files. Initial the contents of those files were in the HTML but it slowly became too cluttered. The problem is that inside these files I am referencing image files, which are used for creating button elements (in my case easyButton instances from Leaflet). I am looking for a way to somehow fix these references. Note that I have called collectstatic and my HTML is using {% load static %} to load the static content. My JS files are also defined as Django template language variables themselves. I am thinking of perhaps at least loading all the references to the static files inside the HTML and then using those inside my JS files. Here is an example code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="Content-Type" content="text/application/html; charset=iso-8859-1"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="#" /> <title>Test</title> </head> <body> ... </body> </html> <script> const TEST = {{ test }}; // The 'test' variable unwraps … -
Django queryset show english translations
This is my Django models.py: from django.db import models class Blog(models.Model): pub_date = models.DateTimeField('date published') def __str__(self): return self.pub_date class LanguagesCode(models.Model): code = models.CharField(max_length=5) def __str__(self): return self.code class BlogTranslation(models.Model): name = models.CharField(max_length=250) content = models.TextField(blank=True, null=True) blog_id = models.ForeignKey(Blog, related_name='translations', on_delete=models.CASCADE) language_code = models.ForeignKey(LanguagesCode, related_name='languages', on_delete=models.DO_NOTHING) class Meta: unique_together = ('blog_id', 'language_code') def __str__(self): return self.name I want to show the list of blogs those have english translation, with name in english. How do I need to write my query to get this data: [ { "name": "1st Blog name in english", "content": "content in english", "pub_date": "XXX" }, { "name": "2nd Blog name in english", "content": "content in english", "pub_date": "XXX" }, ] I use Django 4 with Django Rest Framework. This is my best try, which doesn't give me the result I want: Blog.objects.filter(translations__language_code = 2) -
Having both .filter() on query_param and .all() functionality without adding another ViewSet and end-point
I'm trying to avoid making another end-point to handle this query, but thinking there isn't a way around it. Wanted to run it by ya'll before doing so. Basically, I have Documents related to Customers and Products. I want to retrieve only the Documents for a specific Customer and Product. Here are the views.py: class DocumentsViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'filename', ] queryset = Documents.objects.all() serializer_class = DocumentsSerializer class DocumentToCustomerViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'customer_id', 'document_id' ] queryset = DocumentToCustomer.objects.all() serializer_class = DocumentToCustomerSerializer class DocumentToProductViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filter_fields = [ 'id', 'product_id', 'document_id' ] queryset = DocumentToProduct.objects.all() serializer_class = DocumentToProductSerializer I'm thinking I can do something like this shorthand: class DocumentsViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'filename' ] queryset = Documents.objects.filter(document_to_product__product_id=id, document_to_customer__customer_id=id) serializer_class = DocumentsSerializer Which does seem to work when I tested it. But then it I think I'd need to make another end-point to accommodate both the .all() and .filter()... I think. Additionally, haven't been able to get the filter_fields = [] to work with the relationship either. Trying to do something like /api/documents/?customer_id=123&product_id=123. I get a: TypeError: 'Meta.fields' must not contain non-model field names: Here are the models … -
Why doesn't my article send after I wrote two mixins?
I have written a view to send my form, but I had to level users, so I wrote two mixins, but now my author user can't send an article. View: from .mixins import FieldsMixin, FromValidMixin class ArticleCreate(LoginRequiredMixin, FromValidMixin , FieldsMixin , CreateView): model = Article template_name = "registration/article-create-update.html" Mixins: from django.http import Http404 class FieldsMixin(): def dispatch(self, request, *args, **kwargs): if request.user.is_superuser: self.fields = ["author" ,"title" , "slug" , "category" , "description" , "thumbnail" , "publish" , "status"] elif request.user.is_author: self.fields = ["title" , "slug" , "category" , "description" , "thumbnail" , "publish" , "status"] else: raise Http404("You can't see this page") return super().dispatch(request, *args, **kwargs) class FromValidMixin(): def form_valid(self, form): if self.request.user.is_superuser: form.save() else: self.obj = form.save(commit=False) self.obj.author = self.request.user self.obj.status = 'd' return super().form_valid(form) -
How do I not be placing login_required() in each of my views AND Place for all without having to write it in each one Python (Django)
Ej: **Quiero saber si hay alguna forma de indicarle a login_required algunas vistas en especificas sin tener que hacer esto en cada una Gracias ** ` @login_required() def vista1(request): pass @login_required() def vista2(request): pass @login_required() def vista3(request): pass @login_required() def vista4(request): pass @login_required() def vista5(request): pass ` algo Asi: nose si exista esa posibilidad ` login_required(vista1,vista2,vista3...etc) ` -
Acces static files in javascript on django
i am bilding a online music player from scrach and i moved to django . but i cant change my music from my js file like music.src = "{% static 'music/music.mp3' %}:" and i am loading the static files to , how can i accces the my music folder from inside the js file , btw my js and music are in the same static folder i have the music folder then the assets folder where my js files are . or can i just use music.src = "music/music.mp3" i loaded the files with {% load static %} and tryed to load the files with music.src = "{% static 'music/music.mp3' %}" but no results -
The calculated field on my django admin page is returning the average grade for the wrong column
I'm trying to add a computed column to one of my models on the admin page, specifically adding an average mark from a foreign key in my Mark model, and adding it to the relevant Student in my student model. When I run an aggregate avg command within my StudentAdmin class, it returns the average of the grades id field, not the mark field. Here is the relevant code: models.py class Student(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) def __str__(self) -> str: return self.last_name class Meta: ordering = ['last_name'] class Module(models.Model): module = models.CharField(max_length=255) class Grade(models.Model): mark = models.PositiveSmallIntegerField(null=True) module_id = models.ForeignKey(Module, on_delete=models.PROTECT) student_id = models.ForeignKey(Student, on_delete=models.PROTECT) def __str__(self) -> str: return self.mark ... admin.py ... @admin.register(models.Student) class StudentAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name', 'average_grade'] def average_grade(self, student): return student.average_grade def get_queryset(self, request): return super().get_queryset(request).annotate( average_grade = Avg('grade') ) How do I specify which column from Grade to use? -
how can I change a button value to remove from cart if product is already in session
I been trying to changing the button add to cart to remove from cart if it happens that products is in session. This is the template: products.html ... <div id="products-list" class="grid grid-cols-4 gap-4"> {% for product in products %} <div class="card"> <div class="image-container"> <img class="img" src="{% static product.image %}" alt="Card image cap"> </div> <div class="container"> <h5 class="card-title">{{ product.product_name }}</h5> <p class="card-text">{{ product.description }}</p> <p class="card-text">Price - &#8358;{{ product.price }}</p> <form action="{% url "add-cart" %}" method="POST"> {% csrf_token %} <input type="hidden" name="product_id" value= "{{ product.id }}"> from here is where I have problems. I am trying to put an if condition that changes the value of the button e.g if product is in session it will show the remove from cart button, else it will show the add to cart button. {% comment %} {% if {{ request.session.stored_item }} %} {% endif %} {% endcomment %} {% comment %} document.getElementById("btn-green").addEventListener("click", function() { document.getElementById("btn-green").innerText = "remove from cart" }) {% endcomment %} </form> </div> </div> {% endfor %} # views.py # def products(request): # stored_items = request.session.get("stored_items") # product_item = Product.objects.filter(id__in=stored_items) products = Product.objects.all() if 'query' in request.GET: query = request.GET['query'] multiple_q = Q(Q(product_name__icontains=query) | Q(description__icontains=query)) products = Product.objects.filter(multiple_q) # products = …