Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass a csrf token between django and javascript
I know very little about javascript. I have a GeoDjango project, and am adding a map view of some of the data using Leaflet. There is a lot of data so I am using a Leaflet uGeoJSON Layer to display the data (this allows leaflet to post a bounding box so Django can filter results and only pass visible data). I am adding leaflet to a django view. I have this working with a function based view in django which I decorate with @csrf_exempt, but would like to pass the proper csrf headers so I can use the generic class based django views. The documentation for [Leaflet uGeoJSON Layer][1] suggests: var headers = {}; // CSRF headers var token = jQuery("meta[name='_csrf']").attr("content"); var header = jQuery("meta[name='_csrf_header']").attr("content"); if (header) { headers[header]= token; } var customers = new L.uGeoJSONLayer({ endpoint : "/layers/customers", headers: headers }).addTo(map); I added this to my javascript but token and header are always null. Here is my javascript. map.js var headers = {}; // CSRF headers var token = jQuery("meta[name='_csrf']").attr("content"); var header = jQuery("meta[name='_csrf_header']").attr("content"); if (header) { headers[header]= token; } // Point Styles var DmseJobStyle = { fillColor: "#FFFFE0", color: "#FFFF00", opacity: 1, fillOpacity: 0.8 } var ... DmseJobData … -
Validation for current user
How to realize checking 'name' for current user in forms.py in ValidationError('Same name already added, change name'). views.py @login_required def main_page(request): form = URL_listForm(request.POST) if request.method == "POST": if form.is_valid(): name = form.cleaned_data['name'] if URL_list.objects.filter(user=request.user, name=name).exists(): return HttpResponse('Same name already added, change name') new_post = form.save(commit=False) new_post.user = request.user new_post.save() return HttpResponse("Data added") return render(request, 'link/main.html', {'form': form}) -
Django Queryset - get related objects
I would like to get the related objects of each object in a queryset. Example: from django.contrib.contenttypes.fields import GenericRelation from django.db import models class Synonym: value = models.CharField(max_length=100) class Name: synonyms = GenericRelation(Synonym) qs = Name.objects.all() synonyms = qs.values_list('synonyms', flat=True) # <- returns the database id but not the object But the value_list method returns only the id of the objects within the queryset. I could flatten the output propably like this: [synonym for synonyms in list(qs) for synonym in synonyms] But I wondered if there is a way to directly get the objects? -
Passing value from Django custom command to a view
I want to pass value from django custom command to a view. Custom command: GDA_frontend/GDA_datatables/management/commands/gda_start.py class Command(BaseCommand): help = 'Starts the GDA app with API key for typesense search engine' def add_arguments(self, parser): parser.add_argument('api_key', type=str) def handle(self, *args, **options): try: # HERE I WANT TO PASS api_key VALUE TO A VIEW call_command("runserver", "0.0.0.0:8000") except Exception as e: self.stdout.write(self.style.ERROR('ERROR: ' + str(e))) View where i want to pass that value: GDA_frontend/GDA_datatables/views.py @csrf_protect def parsing_triggered(request): frontendTracker = FrontendTracker() if request.method == "POST" and not frontendTracker.parsingStarted: # GET THAT API KEY VALUE HERE return redirect("index") -
user selected objects per page in Django
I made pagination for my page but I want to let the user choose how many records does the page display e.g. 10, 15, 25. This is my views.py def finished_ads_view(request): queryset = Campaign.objects.filter(completion_percent=100) per_page = request.GET['dropdown'] page = request.GET.get('page', 1) paginator = Paginator(queryset, per_page) try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = { 'posts': posts, } return render(request, 'finished_campaigns.html', context) And this is part of my template where I want to let the user choose. <select name="dropdown"> <option value="1">1</option> <option value="2">2</option> <option value="15">15</option> <option value="20">20</option> </select> <input type="submit" value="Submit"/> Now the error I'm getting is: MultiValueDictKeyError at /finished_campaigns/ 'dropdown' Can anyone help with this? -
What's the correct datetime format for this string date generated by python?
I have this date example '2022-08-30T11:53:52.204219' stored in database, when I get it from database it's type is string so I wanted to convert it to a date type by using this python code datetime.strptime('2022-08-30T11:53:52.204219', "%Y-%m-%d'T'%H:%M:%S.%f") I also tried this one datetime.strptime('2022-08-30T11:53:52.204219', "yyyy-MM-dd'T'HH:mm:ssZ") But I always get this error response 'time data '2022-08-30T11:53:52.204219' does not match format "%Y-%m-%d'T'%H:%M:%S.%f' I need help to convert this string date to an actual date -
Django model field or filter?
I have a general question regarding performance when it comes to database management. I have created a social network application where you can like post and follow other users. My question is: When I want to display the number of likes for a post or the number of followers for a user I'm wondering what would be the best way to get this number. My options are to create an Integerfield in my model that I update every time someone follows or unfollows a user. Or I can filter the models that this user is present in and take the length of that resulting queryset. What would be best way of doing this? -
Why is the download attribute no longer working after running my Django App in a docker image?
After running a docker image of my django app, I notice that downloading files is no longer available. The only thing I get is a copy of the website page I am currently on and not the requested file. Locally, it is working fine. Here is how my code is organized : In main/views.py : path_to_report = f"media/Reports/{request.user.username}/{request.user.username}{now.hour}{now.minute}{now.second}.txt" return render(request, "main/result.html", {"dic_files": dic_files, "nbr":len(files), "dic_small":dic_small, "dic_projects":dic_projects, "path_to_report":f"app/{path_to_report}"}) In main/result.html <a href=/{{path_to_report}} download> <button class="btn btn-success" name="rapport" value="rapport"> Télécharger votre rapport</button> </a> Here is my dockerfile : # Use the official lightweight Python image. # https://hub.docker.com/_/python FROM python:3.8 # Allow statements and log messages to immediately appear in the Knative logs ENV PYTHONUNBUFFERED True EXPOSE 8000 ## api-transport-https installation RUN apt-get install apt-transport-https ca-certificates gnupg # Copy local code to the container image. ENV APP_HOME /app WORKDIR $APP_HOME COPY . ./ # Install production dependencies. RUN pip3 install --upgrade pip setuptools wheel RUN pip3 install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate RUN python manage.py collectstatic --no-input ENTRYPOINT ["gunicorn", "myteam.wsgi:application", "--bind=0.0.0.0:8000", "--workers=4", "--timeout=300", "--log-level=debug"] -
django generic foreign keys alternative
So, I've a transfer model where sender can be of either two models and the same for receiver I used generic foreign key but I read it's slower than normal foreign keys as it has to get the table first to get to parent and from parent to children it has to do real evaluation as the parent id is just an integer column, so should I keep using it, or add two state columns and 4 foreign keys, one state and two foreign keys for each of sender and receiver or just keep the generic foreign key? -
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?