Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
celery inspect shows no task, but on purge returns a int > 0
The problem we are facing is that our redis memory grows with time. When, I inspected the memory usage by redis key celery it returns ~72 MB. Then, I run LLEN celery from redis-cli and it returns 79945. But, when I try to inspect the tasks from celery itself, it doesn't reveal anything. django@celeryworker-7b69cddf7c-86jq5:/app$ celery -A config.celery_app inspect scheduled -> celery@celeryworker-7b69cddf7c-86jq5: OK - empty - 1 node online. django@celeryworker-7b69cddf7c-86jq5:/app$ celery -A config.celery_app inspect revoked -> celery@celeryworker-7b69cddf7c-86jq5: OK - empty - 1 node online. django@celeryworker-7b69cddf7c-86jq5:/app$ celery -A config.celery_app inspect reserved -> celery@celeryworker-7b69cddf7c-86jq5: OK - empty - 1 node online. django@celeryworker-7b69cddf7c-86jq5:/app$ celery -A config.celery_app inspect active -> celery@celeryworker-7b69cddf7c-86jq5: OK - empty - 1 node online. When I run celery -A config.celery_app purge it returns Purged 79945 messages from 1 known task queue. -
Django annotation multiply fields
When I try to annotate my model I face an issue that two fields multiply each other def get_queryset(self): return self.queryset.annotate( my_votes=Count("votes", filter=Q(votes=self.request.user), distinct=False) vote_count=Count("votes", distinct=False) comments_count=Count("comments", distinct=True) ) I know that there is an issue with multiple aggregations Combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries django docomentation Is there another way to accomplish this? -
Keep track of objects created in the child model by updating the parent model
I have 2 models Parent, Child class Parent(models.Model): description = models.CharField(max_length=250, null=True, blank=True) child_list = models.CharField(max_length=250, null=True, blank=True) class Child(models.Model): price = models.CharField(max_length=250, null=False, blank=False) I need to populate child_list whenever a Child object is created I don't know if there is a predefined tool in Django for that, the goal is basically for each 'parent' to know how many children it has (with a list of the ids of its children). What I had thought was to create a list with the ids of the children, but I think it is not efficient/elegant at all. Does anyone know what would be the right way to do it? -
How to correctly display a table inside another table with Django templates
i'm using a table to display values in a django template, and I have a secondary table inside my principal table (the grey one in the image below) : image of my table The two tables uses the same columns, and my problem is that the columns are not aligned (for example, the "n" cell in my first line is not aligned with my "n" cell in the second table, because values don't have the same size, and it's gonna be hard to know than "n" is in the "n" column when I will have "real" values) (I've created a secondary table to fix this problem : DJANGO - close two collapse buttons with one, but if you think there is a better way to do it, and avoid my alignment problem, dont hesitate to tell me) Is there a way to "glue" the table to the side of the cell, or to specify the size of the columns to "force" alignment ? Here is a simplified version of my code : <div class="card"> <div class="card-body p-0"> <table class="table" style="width: 100%;"> <tbody> <tr> <th bgcolor="gray" style="color: white">aaaaaaaa</th> <th bgcolor="gray" style="color: white">bbbbbbbb</th> ... <th bgcolor="gray" style="color: white">uuuuuuuu</th> <th bgcolor="gray" style="color: white">vvvv</th> … -
err_too_many_redirects django 3 ( login logout session ) [closed]
I am learning session in Django. Got the error below. views.py Django error: err_too_many_redirects django 3 from doctest import master import re from django.shortcuts import render, redirect from .models import * from django.contrib import auth from django.core.files.storage import FileSystemStorage from django.http import HttpResponse def Index(request): if 'user' in request.session: current_user = request.session['user'] param = {'current_user': current_user} return render(request, 'dataentryview.html', param) else: return redirect('index') return render(request, 'dataentryview.html') -
AttributeError: 'dict' object has no attribute 'Keys'-Python Django
I am super new so excuse my mistakes. Python-3.10 Django-4 I am trying to create an index page in Django to show a list of Monthly To-Do. I have created a dictionary having detail of monthly todo. monthly_challenges_dict = { "jan": "jan works", "feb": "feb works" } however, when I am using the below function to use this dictionary key list ..it is showing me an error- AttributeError: 'dict' object has no attribute 'Keys' [30/Aug/2022 14:24:09] "GET /challenges/ HTTP/1.1" 500 61337. def index(request): list_items = "" months = list(monthly_challenges_dict.Keys()) for month in months: capitalized_month = month.capitalize() month_path = reverse("month-challenge", args=[month]) list_items += f"<li><a href =\"{month_path}\"> {capitalized_month}</a><li>" response_data = f" <ul> {list_items} </ul>" return HttpResponse(response_data) Can anybody suggest what I am doing wrong? Thank you, AKM -
POST id objects and retriving nested tables related to it
Can someone advise me on how to deal with how to retrieve data such as this example JSON: [ { "deviceid": 4, "devicename": "###", "device_measurment": { "deviceid": 4, "measurement": "31.8", } }, ] How is it right now: [ { "deviceid": 4, "devicename": "###", }, { "deviceid": 4, "measurement": "31.8", }, ] I understand the problem and why I am getting such a response, but I cannot handle this problem via the serializer. at the moment, I have the following Views from itertools import chain class RetrieveSpecificDevicesView(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = SpecificDeviceSerializer def get_object(self, queryset=None): obj = self.request.data return obj def post(self, request): if self.request.method == 'POST': self.object = self.get_object() serializer = SpecificDeviceSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if serializer.is_valid(): obj1= Devices.objects.using('yelcloud').filter(deviceid=serializer.data.get("deviceid")) obj2= Measurements.objects.using('yelcloud').filter(deviceid=serializer.data.get("deviceid")) dats= chain(obj1, obj2) if Devices.objects.using('yelcloud').filter(deviceid=serializer.data.get("deviceid")).exists(): data = serializers.serialize('json', dats) return HttpResponse(data, content_type="application/json") return JsonResponse(serializer.erorr, status=status.HTTP_201_CREATED) Serializer class SpecificDeviceSerializer(serializers.Serializer): deviceid = serializers.CharField(required=True) class MeasurmentsSerializer(serializers.ModelSerializer): class Meta: model = Measurements fields = ('measurementid','measurement') Models enter image description here -
Django replaces underscore with whitespace
I have a django app where user can upload a pdf and get it converted to .png. The upload part is working fine but when I try to convert the pdf file, it says file not found. I noticed something weird that the filename contains _ but when I print the name of the file uploaded, it converted _ to whitespace ( "file_1.pdf" to "file 1.pdf") and hence the reason for the error file not found! Why is django doing this? I haven't written any code to do so!! models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import FileExtensionValidator class UploadPdf(models.Model): resumes = models.FileField(blank=True, null=True, validators=[FileExtensionValidator(allowed_extensions=['pdf'])]) forms.py from django import forms from app1.models import UploadPdf from django.forms import ClearableFileInput class ResumeUpload(forms.ModelForm): class Meta: model = UploadPdf fields = ['resumes'] widgets = { 'resumes': ClearableFileInput(attrs={'multiple': True}), } views.py from django.shortcuts import render, redirect from app1.forms import ResumeUpload from app1.models import UploadPdf from app1.convert import convert_file import os def home(request): if request.method == 'POST': form = ResumeUpload(request.POST, request.FILES) files = request.FILES.getlist('resumes') if form.is_valid(): f = form.save() f.user = request.user f.save() f_list = [] file_name = form.cleaned_data['resumes'].name if files: for i in files: file_instance = UploadPdf(resumes=i) f_list.append(file_instance.resumes.path) file_instance.save() for j … -
I have made changes in my model. and committed in aws server....Now how to run python manage.py makemigrations and python manage.py migrate
I have made changes in my model. and committed in AWS server. Now how to run python manage.py make migrations and python manage.py migrate because i want changes in my live database also -
Post html input date to sql query as parameter with Django using pyodbc and refresh page
I have this project at work which consists in building a dashboard of quantities of interest to help with decision making. The information I need to achieve this is stored in a read-only mssql database from a third party software. I can access the information I need using pyodbc and writing raw sql queries and store the results in pandas DataFrames using pandas.read_sql_query(my_raw_query_as_string, connection). This solution comes in handy as sometimes I rework the query results to calculate indicator values. My team and I decided to display this dashboard on an internal website to increase the visibility of the indicators. We chose to use the Django Framework as, because it runs with python, we can still use our data processing routines previously written using pyodbc and pandas. Building the dashboard, I realised I could ( and don't know if I should) completly forget about the Django ORM and still manage to display charts (using pychart.js) of the indicators. I would like the user to input html Dates on the dashboard interface, pass these dates to my queries as parameters, gather another result which I process and refresh the graphs. I tried to do it with htlm forms but I can't … -
Spotipy redirect uri opening on server instead of users browser?
I built a web app using Django and the wrapper for the Spotify api, Spotipy, and deployed it to Heroku. The problem I am facing is that the redirect uri opens on the machine running the code, which in this case is the linux server used by heroku. Because of this, the user never actually sees the page prompting them to authenticate the app and login to their Spotify accounts, resulting in a request timeout from Heroku. This happens when my REDIRECT_URI is set to http://localhost/. I have tried to set the REDIRECT_URI to https://nameofmyapp.herokuapp.com which then resulted in an EOFError from the Spotipy module. I have not been able to find a solution for this. For context, my authentication flow is set up as follows: def index(request): cache_handler = spotipy.DjangoSessionCacheHandler(request=request) auth_manager = spotipy.oauth2.SpotifyOAuth( env("CLIENT_ID"), env("CLIENT_SECRET"), env("REDIRECT_URI"), scope=env("SCOPE"), cache_handler=cache_handler) session = spotipy.Spotify( oauth_manager=auth_manager, requests_session=True) -
Django unnamed default logger is overridden by imported package
In my django app, I have defined the logging configuration: default_config = { 'handlers': handlers_to_use, 'level': 'WARN', } LOGGING: Dict[str, Any] = { 'version': 1, 'disable_existing_loggers': False, 'handlers': handler_configs, 'root': default_config, 'loggers': { '': default_config } } So you can see Im using the unnamed logger '' and the root logger, which should set the default logging level to WARN. However, there are some packages (factory_boy and PIL) that are giving me DEBUG logs, which doesnt make sense because WARN should only give me ERROR and WARN logs, based on the heirarchy. How are they overriding the default? If I add factory and PIL to the list of loggers, things work correctly, but Im wondering why the unnamed nor the root logger doesnt catch the debug logs Any help would be greatly appreciated -
Django - schedule time WhatsApp message send through Twilio
I want to send WhatsApp messages as per the scheduled time selected same as SMS schedule_type and send_at on Twilio. Can we send it the same way with WhatsApp? I have researched a lot about it but didn't get a response. Can anyone help? If we can do it with Twilio then how and no then another way to perform this. -
Django Raw Query wants ID but sstill doesent work
im a new Programmer and i have a issue with Django. I wrote a raw Query but it wont work. Can anynone help me please? This are my Models: class Kunde(models.Model): kunden_id = models.IntegerField(db_column='Kunden_ID', primary_key=True) vertragspartner = models.CharField(db_column='Vertragspartner', max_length=45, blank=True, null=True) labor = models.CharField(db_column='Labor', max_length=45, blank=True, null=True) def __str__(self): return str(self.kunden_id) class Meta: managed = True db_table = 'kunde' class Objekte(models.Model): objekt_id = models.CharField(db_column='Objekt_ID', primary_key=True, max_length=50) rechnungsempfaenger = models.CharField(db_column='Rechnungsempfaenger', max_length=50, blank=True, null=True) kundecenter = models.CharField(db_column='Kundecenter', max_length=50, blank=True, null=True) twa_nr = models.IntegerField(db_column='TWA_Nr', blank=True, null=True) karte = models.IntegerField(db_column='Karte', blank=True, null=True) def __str__(self): return self.objekt_id class Meta: managed = True db_table = 'objekte' ordering =['objekt_id'] The Objekte Model is a bit bigger but i cut it so it is a bit "prettier". My Views looks like this def kunde_all (request): sql = "SELECT k**unde.kunden_id as id**, kunde.Vertragspartner, kunde.Labor, objekte.Objekt_ID, COUNT(objekte.Objekt_ID) AS anzahl FROM kunde LEFT JOIN objekte ON kunde.kunden_id = objekte.kunden_id GROUP BY kunde.kunden_id" sql_data= Kunde.objects.raw(sql) p = Paginator(Kunde.objects.raw(sql_data), 20) page = request.GET.get('page') kunden=p.get_page(page) context={ 'kunden': kunden, } return render(request,"kunde.html", context=context) What im trying to do here is that i want to count the objects in Objekte that belong to the Kunde and give them in a Tabel back. The problem is that … -
How can we save all the logs in a database with some extra columns?(django)
I am working on a Django project in which I have to save all the logs(not just the error logs), for example when a user clicks on a tab or even a button, I should save its log. And I want to save them in my database(or better a separate database) because I need to analyze the logs and extract some information from them. I have seen some posts in StackOverflow, but they were not very useful for me. In this post some answers have been provided, and I tried django-db-logger package in the third answer. I have added the below code to settings.py based on the README file of this project: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(asctime)s %(message)s' }, }, 'handlers': { 'db_log': { 'level': 'DEBUG', 'class': 'django_db_logger.db_log_handler.DatabaseLogHandler' }, }, 'loggers': { 'db': { 'handlers': ['db_log'], 'level': 'DEBUG' }, 'django.request': { # logging 500 errors to database 'handlers': ['db_log'], 'level': 'ERROR', 'propagate': False, } } } I have added some logs to one of my APIs in the below code: import logging db_logger = logging.getLogger('db') # _____________ user Management ______________ @api_view(['POST']) … -
How to cache dynamic content with signal-based caching?
I have an expense tracker application where I display a list of expense categories which can be changed by user. So I'm trying to cache the data as follows: class ShowCategories(LoginRequiredMixin, ListView): paginate_by = 10 model = Category context_object_name = 'categories' template_name = 'expense_tracker/category_list.html' def get_queryset(self): category = cache.get('category') if category is None: category = Category.objects.filter(user=self.request.user) cache.set('category', category) return category def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Категории' return context And I use signals to invalidate the cache: @receiver(post_delete, sender=Category) def category_post_delete_handler(sender, **kwargs): cache.delete('category') @receiver(post_save, sender=Category) def category_post_save_handler(sender, **kwargs): cache.delete('category') But the page displays new categories only after deleting one of the old categories. How can I fix this? -
Best way to add bool field to Django queryset/serializer
I have two models class A(models.Model): name = models.CharField(max_length=32) ... class B(models.Model): fkey = models.ForeignKey("A", on_delete=models.CASCADE) ... I want to create queryset of objects A based on condition if some of B objects is referring to A in my DRF serializer a1 = A.objects.create(name="1") a2 = A.objects.create(name="2") b1 = B.objects.create(fkey=a1) a_objs = A.objects.filter() serializer = ASerializer(a_objs, many=True) serializer.data { { "name": "1" }, "b_attached": true }, { { "name": "2" }, "b_attached": false } What is the best way to achieve this? -
Python Django-Guardian: How to suggest a selection at dropdown menu on the admin site
I am using django-guarian to handle permissions comforable. How can I suggest my favorite permission at admin site when adding a permission (dop down menu). How can I filter the permission selection? Admin Site at Django admin.py class DeploymentUserObjectPermissionAdmin(GuardedModelAdmin): list_display = ('permission', 'user', 'content_object') search_fields = ('permission', 'user', 'content_object') ordering = ('-permission',) models.py class DeploymentUserObjectPermission(UserObjectPermissionBase): content_object = models.ForeignKey(Deployment, on_delete=models.CASCADE) -
Django foreign key as options for autocomplete, error: Select a valid choice
Thanks in advance for your help. I am building my first Django project, a ticketing application that will have over 100 items to choose from. I'm trying to display a list of Items(foreign key objects) for the user to choose from when creating a ticket in an MDBootstrap autocomplete field. The items have both a name and ID and I want both to appear in the autocomplete options when the user is searching. My form works when I display only the 'item_id' from the Item model in the autocomplete data (found in the script tags at the bottom of the template). But when I display the string with both 'item_name" and 'item_id'(as you see below), my form won't submit and I get the error "Select a valid choice. That choice is not one of the available choices." How can I display both 'item_name' and 'item_id' from the Item model in the autocomplete options but then have my form submit properly recognizing the 'item_id' for its 'item' foreign key field? models (each of these models is in a different app within the django project) class Item(models.Model): item_name = models.CharField(max_length=200) item_id = models.CharField(max_length=200, primary_key=True) class Ticket(models.Model): ticket_id = models.AutoField(primary_key=True, null=False, blank=False) item … -
I want to add manual key in serializer.data in generic.ListAPIView with filter and pagination
As per title i want to add manually "InWishList" key into serializer.data, i am sharing my current response where i want to add "InWishlist" key. in simple word i want to add manual key into serializer method fields it depend on request has valid token or requested by valid user.in both case i want to add manual key inside the serializer methed field with True and False value. "count": 2071, "next": "http://admin.vaniprakashan.in/book_store/book_filters/?page=2", "previous": null, "results": [ { "id": 10658, "hindi_title": null, "title": "Ravi Katha : Andaaz-E-Bayan Urf Ravi Katha", "unique_code": "498", "genres_names": [ "Memories" ], "slug": "ravi-katha-andaaz-e-bayan-urf-ravi-katha", "variations_dics": { "Paperback": true, "Hardcover": true }, "printed_book_details": { "Hardcover": { "name": "Hardcover", "id": 3607, "isbn_code": "9789389915631", "slug": "ravi-katha-andaaz-e-bayan-urf-ravi-katha-hindi-hindi-hardcover", "original_price": 595.0, "discountable_price": 595.0, "pages": 220, "is_in_stock": true, "languages": "Hindi", "in_print": "Vani Prakashan", "in_print_2": "Vani Prakashan", }, "Paperback": { "name": "Paperback", "id": 3606, "isbn_code": "9789389915648", "slug": "ravi-katha-andaaz-e-bayan-urf-ravi-katha-hindi-hindi-paperback", "original_price": 299.0, "discountable_price": 299.0, "pages": 220, "is_in_stock": true, "languages": "Hindi", "in_print": "Vani Prakashan", "in_print_2": "Vani Prakashan", } }, "ebook_details": {}, "audio_book_details": {}, "book_reviews": { "avg": 0, "one_stars": 0, "two_stars": 0, "three_stars": 0, "four_stars": 0, "five_stars": 0, "total_counts": 0 }, "description":"...", "images": [ ... ], "authors": [ ... ] },....] in this response we can see there is … -
Db logger auto delete data after a time interval
Trying to implement a DB logger in my Django project but I am facing a problem in managing the logs in my DB so how can I automatically delete the old records from DB settings.py INSTALLED_APPS = ['django_db_logger',] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'error': { 'class': 'django_db_logger.db_log_handler.DatabaseLogHandler', 'filename': 'errors.logs', 'backupCount': 4, 'when': 'D', 'interval': 1, 'encoding': 'utf8', 'level': 'ERROR' }, 'console': { 'class': 'django_db_logger.db_log_handler.DatabaseLogHandler', 'filename': 'info.logs', 'backupCount': 4, 'when': 'D', 'interval': 1, 'encoding': 'utf8', 'level': 'INFO', }, }, 'loggers': { 'ERROR_LOG': { 'handlers': ['error'], 'propagate': True, 'level': 'ERROR' }, 'INFO_LOG': { 'handlers': ['console'], 'propagate': True, 'level': 'INFO' } } } and also created a function in the helpers.py file for for managing the logs helpers.py import Logging class Logging: def __init__(self,request): self.request = request def log(self, message=None): url =self.request.build_absolute_uri() logger = logging.getLogger('ERROR_LOG') logger.error(f'ERROR: {url} {self.request.data} {self.request.headers} {message}') def info(self, message=None): url = self.request.build_absolute_uri() logger = logging.getLogger('INFO_LOG') logger.info(f'INFO: {url} {self.request.data} {self.request.headers} {message}') And if have better way of logging please do suggest me -
About PWA progressive web apps
enter image description hereI have started building the basic PWA app using django as per the site "https://www.geeksforgeeks.org/make-pwa-of-a-django-project/" Everything works fine except with the 5th step mentioned in the above URL. It is informed to enter the PWA settings in the settings.py file of the django project and so i did, but it doesn't create any manifest.json file anywhere and yet im stuck here. The service worker works fine. when i open the app in the developer tools its says no manifest detected as shown in the shared picture. Thanks in advance. -
Can you recover an object from a failed request in django?
I am processing a lot of data and build dataframes through a django api on an ubuntu server, in which i instance an object that loads a dataframe, a couple of dictionaries and then makes a big data reconstruction process, that takes long. I have been running a request for 3 days, an probably have one day left until it ends, but i need to know, in case it fails, can i recover the object and its data? because the object it's not deleted when the server has an internal error, and i haven't catched in every step of the process. -
HTMX + Django - Edit a ModelForm in a HTML Table
New to HTMX and Django, what I'm trying to achieve is to have a ModelForm on the page with a button that allows the user to 'Edit' the field values directly on the page. After pressing the 'edit' button, the page should display a 'cancel' and 'submit' button. It's basically the same as this example on the HTMX website: Edit Row Cancel should discard the edits and show the table again (as it was) Submit should post the changes made back into the model View on the index page: Here's what I have so far (when user presses 'Edit Entry') but it's not working as intended: There are a few issues: When the 'edit' button is pressed, the ModelForm is loading everything into the first column of the HTML table. Ideally, I would want each field of the Model to be in the 'correct' location in the table. When the 'cancel edit' button is pressed, it's swapping the ModelForm back to the HTML template. I don't want this but just want the table row to go back to how it was previously. The submit button is not posting the data back to the Model. I'm not sure how to really … -
Pattern matching in LDAP Distinguished Name Template
I am trying to authenticate users using django_auth_ldap. I have users in 2 different groups (say= Theta & Gamma, Alpha & Rho), Currently, to search users I have created 2 authentication backends & mapped USER_DN_TEMPLATE like this: 'CN=%(user)s,OU=Television,OU=Theta,OU=Gamma,DC=example,DC=com' to first backend & like this : 'CN=%(user)s,OU=Television,OU=Alpha,OU=Rho,DC=example,DC=com' to the second backend. All my other settings are same. I know, this is not ideal setup but I want to know what should my DN_TEMPLATE look like if I need to find all users in one authentication backend only? There should be some REGEX like pattern to replace Theta/Gamma/Alpha/Rho & then it should work (similar to %(user)s in above patterns. The other approach will be to set some SCOPE_SUBTREE (& other variables) so that, it searches all users in 'DC=example,DC=com'. I need help on those variables & values.