Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Everytime Celery is restarted all the scheduled tasks are acknowledged first and if takes 20 minutes if there are 100 thousands of tasks
I mean every time when we restart our Celery workers because of our App being deployed - they are not actually executing any tasks from the Q until all the tasks are received/acknowledged first. Which take a huge amount of time given our amount of the tasks in the Q - close to 100K tasks and close to 20 minutes of lag accordingly. This question was already asked in 2016 here, here is what I can come up with given that, but I hope there is a better way: We can support multiple celery Qs inside a single RMQ and do this: tasks by default go to the new Q upon every deploy we move all thousands of the tasks from the new to old Q (dunno how quickly this can be done) different workers deal with old and new tasks That way at least the new incoming tasks won't be waiting for the old ones to be acked. But imagine - what if in the old tasks there is a task which should be executed during this period while the old tasks are still being fed to the workers - this approach won't solve it. -
`Django` cannot be imported after Ubuntu upgrading
After upgrading my Ubuntu from 20.04 to the latest version, my website cannot be deployed. Here is my /var/log/apache2/error.log: Wed Feb 15 15:16:56.565327 2023] [wsgi:error] [pid 1940107] [client 159.226.116.208:56112] Traceback (most recent call last): [Wed Feb 15 15:16:56.565340 2023] [wsgi:error] [pid 1940107] [client 159.226.116.208:56112] File "/home/djuser/djsites/mgkd/mgkd/wsgi.py", line 12, in <module> [Wed Feb 15 15:16:56.565344 2023] [wsgi:error] [pid 1940107] [client 159.226.116.208:56112] from django.core.wsgi import get_wsgi_application [Wed Feb 15 15:16:56.565351 2023] [wsgi:error] [pid 1940107] [client 159.226.116.208:56112] ModuleNotFoundError: **No module named 'django'** **No module named 'django'** I have another server which has not been upgraded, and the django websites there deployed normally. It seemed that django cannot be imported after Ubuntu upgrading. Then I checked my django virtualenv. I have really installed django in my virtualenv, but I cannot import it. -
Django url which accept both with parameter or without
I want to accept the both url such as /top/ /top/1 I tried a few petterns path('top/<int:pk>/', views.top, name='top_edit'), path('top/(<int:pk>)/', views.top, name='top_edit'), path('top/(<int:pk>)/$', views.top, name='top_edit'), def top(request: HttpRequest,pk = None) -> HttpResponse: return render(request, 'index.html', context) It accept /top/1 however /top/ is not accepted. How can I make it work? -
object.save() not working for arrayfield django
I have a ArrayField and want to change, but when I use .save(), object didn't update. from django.contrib.postgres.fields import ArrayField dates = ArrayField(models.CharField(max_length=10), size=300) object.dates += new_list object.save() -
How to get the authentication information in ModelViewSet?
I am using rest framework with ModelViewSet class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer filterset_fields = ['user'] def list(self, request): queryset = m.Drawing.objects.all() serializer = s.DrawingSerializer(queryset, many=True) return Response(serializer.data) With this script, I can use filter such as /?user=1 Howver this user=1 is not necesary when authentication information is used in script. (Because one user needs to fetch only data belonging to him/herself) How can I get the authentication data in list? -
Django filter in operation is not working with DateTimeobject
In Django ORM, I want to filter records using in-operation. Earlier when I was running the below query it was working fine: EndTime = 2023-02-01 (Varchar) week_list = ['2023-01-01','2023-01-21','2023-02-02','2023-02-12'] Query : count = Stats.objects.filter(EndTime__in = week_list).values('EndTime ').annotate(dcount=Count('EndTime ')) From this query, I was getting the proper result. But when I am trying the same with the below values it is not working. EndTime = 2023-02-01 12:00:09 (DateTimeobject) week_list = ['2023-01-01','2023-01-21','2023-02-02','2023-02-12'] count = Stats.objects.filter(EndTime__in = week_list).values('EndTime').annotate(dcount=Count('EndTime')) In this case, it is not returning the output but I want the same data as the earlier query was giving with the DateTime object field. can anyone please help ?? how can I achieve this? -
React tables change to something like Jquery Datatables
I am new in react. I am working on project Django api and react, I made CRUD operations successfully with axios and now I want to make my tables in better way; I tested Datatables but not successed with it and also tested Materail UI and not successed. now the question is what is the best way to get nice and elegant tables the sourcecomes from api using axios. I want tables like datatables with pagenation search and sorting. please help me import React, { Component } from "react"; import ModalEmployees from "../../components/Modal/ModalEmployees"; import axios from "axios"; class Employees extends Component { constructor(props) { super(props); this.state = { // viewCompleted: false, employeesList: [], modal: false, activeItem: { Employee_code: "", Full_Name: "", Profession: "", Location: "", Cost_Code: "", active: false, }, }; } componentDidMount() { //1 this.refreshList(); } refreshList = () => { //2 axios .get("http://127.0.0.1:8000/api/employees/") .then((res) => this.setState({ employeesList: res.data })) .catch((err) => console.log(err)); }; toggle = () => { //3 this.setState({ modal: !this.state.modal }); }; handleSubmit = (item) => { //4 this.toggle(); if (item.id) { axios .put(`http://127.0.0.1:8000/api/employees/${item.id}/`, item) .then((res) => this.refreshList()); return; } axios .post("http://127.0.0.1:8000/api/employees/", item) .then((res) => this.refreshList()); }; handleDelete = (item) => { //5 axios .delete(`http://127.0.0.1:8000/api/employees/${item.id}/`) .then((res) … -
mod_wsgi django not working with Apache24
I am using a MS Windows 11 Machine running Python 3.11 with virtualenv package installed. I am using Apache24 httpd.exe web server for my django app production server. My app is called mysite and it is fully functional inside a virtual environment (called venv) with the folowing packages (requirements.txt): django django-extensions django-iprestrict mod-wsgi Pillow pyOpenSSL odfpy werkzeug whitenoise pandas plotly matplotlib I can fully run the server in DEBUG mode with the virtual environment activated: (venv) python.exe manage.py runserver And, on the other hand, I was able to make the Apache web server to run a test website without problems. The issue is when I edit httpd.conf files to integrate with my django app thorugh mod_wsgi: # httpd.conf (...) LoadFile "C:/Users/myuser/AppData/Local/Programs/Python/Python311/python311.dll" LoadModule "C:/Users/myuser/mysite/mysite_venv/venv/Lib/site-packages/mod_wsgi.cp311-win_amd64.pyd" WSGIScriptAlias / C:\Users\myuser\mysite\mysite\wsgi.py WSGIPythonHome C:\Users\myuser\mysite\mysite_venv\venv WSGIPythonPath C:\Users\myuser\mysite <Directory /> <Files wsgi.py> Require all granted </Files> </Directory> # media files hosting Alias /media "C:/Users/myuser/mysite/media/" <Directory "C:/Users/myuser/mysite/media/"> Require all granted </Directory> (...) My directory tree is: . ├── mainapp │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── mainapp.sqlite3 ├── manage.py ├── media ├── … -
Django -- foreign key doesn't seem to be working
I have the following models in my Django app: class Dataset(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False ) name = models.CharField(max_length=100, blank=False) created_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) class Imagefile(models.Model): uuid = models.CharField(max_length=36, default="") name = models.CharField(max_length=100, default="") file = models.FileField(upload_to=image_directory_path) dataset = models.ForeignKey( Dataset, on_delete=models.CASCADE, related_name="imagefiles", blank=False, null=False, ) class Annotation(models.Model): image = models.FileField(upload_to=image_annotation_directory_path) json = models.JSONField(default=dict) imagefile = models.ForeignKey( Imagefile, on_delete=models.CASCADE, related_name="annotation", blank=False, null=False, ) What I want to achieve is to store one Dataset that has multiple Imagefiles, and each Imagefile can have either 0 or 1 related Annotation. I am able to create a Dataset and Imagefiles that belong to it. When I try to create the Annotation, however, it is not registered in the Imagefile. In other words, the Annotation refers to the Imagefile, but the Imagefile sees an empty Annotation. This is how I create my test case: dataset = Dataset.objects.get(uuid=..., name='test_dataset') new_imagefile = Imagefile.objects.create( uuid=..., dataset=dataset, name='test_image.png' ) new_imagefile.file.save('/some/existing/path/image.png', open('test_image.png', "rb")) new_annot = Annotation.objects.create(imagefile=new_imagefile) new_annot.image.save('/some/other/existing/path/annot.png', open('annot.png', "rb")) When the above process is done, printing new_imagefile.annotation results in dataset.Annotation.None. I've been fighting with this for several hours, any hint is appreciated. -
DJANGO - access form data in javascript in template
How can I access form data in javascript in template? I have a bootstrap 4 tabbed interface. Each tab renders a dynamic django form. Each form has dynamic 'command' buttons. All form field and button data is coming from a json file. So something like this... The command buttons are handled by ajax, which basically calls a url based on the button clicked. All of the tab forms are rendered by a single template. How can I access the form data (different for each tab) in the javascript function? ( In the js function, look at 'SAVE FORM DATA HERE' and 'PASS FORM DATA HERE' ) template {% load static %} <table class="" id="tabCmdTbl"> <div class="btn-group"> <tr> {% for btn in btns %} <td width="125px"> {% if btn.btnText != "" %} {% if btn.btnText == "End" %} {% comment %} <!-- Handle the exit button, its an anchor, all the other tabs are ajax --> {% endcomment %} <a type="button" class="btn btn-sm btn-outline-secondary w-100" target="_blank" href="/frontOffice">End</a> {% else %} <button type="button" class="btn btn-sm btn-outline-secondary w-100" onclick="tabBtn('{{btn.btnCmd}}')"> {{ btn.btnText }} </button> {% endif %} {% endif %} </td> {% endfor %} </tr> </div> </table> <div id="tabloading" style="height:50px"> <p><img src="{% static 'FhHRx.gif' … -
django.core.exceptions.SuspiciousFileOperation: The joined path (D:\img\favicon.ico) is located outside of the base path component (D:\test\static)
i have facing this issue when i am trying to give favicon to my admin portal it was working completely fine till debug was True when i switch to debug False it start showing me this error which i mention in tittle. here is my code : templetes/admin/base_site.html : {% extends "admin/base_site.html" %} {% load static %} {% block extrahead %} <link rel="shortcut icon" href="{% static '/img/favicon.ico' %}" /> {% endblock %} And if you are intresting in my static files settings then here it is : STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' Thank you in advance if i get it done. i dont know why it happening in debug is working smoothly now it showing me this strange error 400 in browser and in terminal i got this : raise SuspiciousFileOperation( django.core.exceptions.SuspiciousFileOperation: The joined path (D:\img\favicon.ico) is located outside of the base path component (D:\Social_login\staticfiles) -
How to by default not show list of items?
There is a page where the list of elements is displayed. Also on this page there is a search by value. When I enter a value, the page only displays elements with that value. I need to make the page show nothing but the search by default. And only after the query, the page shows the elements with the entered value. How to do it? Home.html <div class="headtext"> <form method="GET" action="{% url 'search' %}"> <input type="search" type="text" name="q" prequired placeholder="Put appnumber"> <button type="submit">Find</button> </form> </div> <div> {% for application in object_list %} <div> <p>Application: {{ application.appnumber }}, status: {{ application.status }}</p> </div> {% endfor %} </div> Urls.py from django.urls import path from .views import HomeView, Search urlpatterns = [ path('', HomeView.as_view(), name="home"), path('search/', Search.as_view(), name="search"), Views.py class HomeView(ListView): model = Application template_name = 'home.html' class Search(ListView): template_name = 'home.html' def get_queryset(self): return Application.objects.filter(appnumber__icontains=self.request.GET.get("q")) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["q"] = self.request.GET.get("q") return context Not all questions benefit from including code, but if your problem is better understood with code you’ve written, you should include a minimal, reproducible example. -
I Want to post class object id and and get the name of class in django generics api view
I Want to post class object id and and get the name of class but when i send post request from postman the foreing key value become null serializer.py Class Serializer class ClassSerializer(serializers.ModelSerializer): subjects = serializers.SlugRelatedField(many=True, read_only=True, slug_field='sub_name') class Meta: model = Class fields = '__all__' Student Serializer class StudentSerializer(serializers.ModelSerializer): class_id = serializers.SlugRelatedField(read_only=True,slug_field='class_id') class Meta: model = Student fields = '__all__' # depth = 1 View.py class StudentListAPIView(generics.ListCreateAPIView): """Student GET and POST Api """ queryset = Student.objects.all().prefetch_related() serializer_class = StudentSerializer Model.py class Class(models.Model): """Class""" name = models.CharField(max_length=25, null=False) subjects = models.ManyToManyField(Subject) department = models.CharField(max_length=50, null=True) fee = models.IntegerField(null=False) def get_subjects(self): return "\n".join([sub.sub_name for sub in self.subjects.all()]) def __str__(self): return '{} {} {} {}'.format(self.name, self.fee, self.subjects, self.department) class Student(models.Model): """Student""" created = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=25, null=False) last_name = models.CharField(max_length=25, null=False) contact = models.CharField(max_length=25, null=False) age = models.IntegerField(null=False) gender = models.CharField(max_length=10, null=False) father_name = models.CharField(max_length=25, null=False) address = models.TextField(max_length=150, null=False) section =models.CharField(max_length=25, null=False) class_id = models.OneToOneField(Class, on_delete=models.CASCADE, null=True) def __str__(self): return '{} {} {} {} {} {} {} {} {} {}'.format(self.created, self.first_name, self.last_name, self.father_name, self.contact, self.gender, self.age, self.address, \ self.class_id, self.section) I Want to post class object id and and get the name of class but when i send post request … -
Sum in Django Rest Framework (DRF) Serializer
Excuse me devs, i wanna ask about how to sum on drf serializer, i need codes that can serialized fields plant from table A and it relations with another table B with sum of them "plants_active" Here's my code: class MainMenuSerializer(serializers.ModelSerializer): plants_active = serializers.IntegerField(source="plant") class Meta: model = TableSitePlant fields = ['plants_active'] What i expecting is i can sum how many plants that have status online -
Getting error in creating new django program
this is the error i am getting. i have even dine reinstalling python but it's showing me this only. i am actually trying to create new django program and this happend out of the blue Fatal error in launcher: Unable to create process using '"C:\Users\Aadil\AppData\Local\Programs\Python\Python39\python.exe" "C:\Users\Aadil\AppData\Local\Programs\Py thon\Python39\Scripts\django-admin.exe" ': The system cannot find the file specified. -
How to configure WSS connection on Django Azure Web App
I've attempted to make an Azure Web App using Django. For the past couple days, I've mingled with Websockets for use for a real-time chat locally using the ws protocol. But, when deploying on Azure, I am forced to use the wss protocol due to the website being hosted on https. I've done some research on how to configure wss to no avail. Can anyone help? I initiate the connection using: if (window.location.protocol == 'https:') { wsProtocol = 'wss://' } else {wsProtocol = 'ws://'} const chatSocket = new WebSocket(wsProtocol + window.location.host + "/"); This gives: "WebSocket connection to 'wss://pharma-send.azurewebsites.net/' failed: In the Startup Command of my Azure app I've tried running the Gunicorn server with ASGI using "gunicorn pharmasend.asgi:application --bind 0.0.0.0:8000 -w 2 -k uvicorn.workers.UvicornWorker" Although, this hasn't changed anything. Thanks for helping! -
Django template variable removes content after whitespace
I am having this very confusing issue and I could only find someone who had the same issue 9 year ago but it wasn't solved : Posting a hidden field with whitespace removes content after whitespace. First of all I'm very new to programming so pardon me if this is a very obvious issue and if my bug is very ugly ! Basically I am trying to pass the content of a variable through the value parameter of an input tag inside of a form. This variable contains strings separated by whitespaces ("test space space") My goal is to then manipulate this data in a view through request.POST The issue is that the first word gets passed just fine but anything after the first whitespace isn't passed to the database. Note that I am using the same variable elsewhere in the same template and the entire title is displayed without issue Here is my view : @login_required def watchlist(request): if request.method == "POST" : auction_info = request.POST user_id = auction_info.get('user_id') auction_id = auction_info.get('auction_id') title = request.POST.get('title') # #creating a watched auction auction_to_watch = WatchedAuction(user_id=user_id, auction_id=auction_id, is_watched=True, title=title) # #preventing duplicates already_watched = WatchedAuction.objects.filter(auction_id=auction_id) if not already_watched : auction_to_watch.save() all_watched_auctions = … -
Django runserver
When I run my django server this occurs: Page not found (404) Request Method:GETRequest URL:http://127.0.0.1:8000/myapp/ Using the URLconf defined in djproject.urls, Django tried these URL patterns, in this order: admin/ The current path, myapp/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my djproject urls.py file: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include('myapp.urls')), ] this is myapp urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='my app-home'), ] my app views.py: from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('<h1>Hello</h1>'), -
Django 4.1, social auth with GIT, error: http://127.0.0.1:8000/complete/github/?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST
I have been asking everywhere I could, I saw some answers here that mentioned adding a host entry for 127.0.0.1 but since my dev serve is on an Ubuntu VM locally I am not sure how that would work. Anyways, I actually copied the URI from GitHub and added it to my settings file: SOCIAL_AUTH_GITHUB_KEY = os.environ.get('SOCIAL_AUTH_GITHUB_KEY') SOCIAL_AUTH_GITHUB_SECRET = os.environ.get('SOCIAL_AUTH_GITHUB_SECRET') SOCIAL_AUTH_GITHUB_REDIRECT_URI = 'http://127.0.0.1:8000/complete/github/' I look at http vs https and everything else. I even typed instead of pasting. If you have any other suggestions how I could fix that, I would be so very happy. I have a feeling it is because maybe I am using 127.0.0.1 instead of a domain, but google worked fine like that... -
Django DRF & Updating multiple partial records
I'm attempting to update a model that has more fields than what I want to pass to it. I've read the DRF documentation and I'm not finding the right approach. I came across using the UpdateModelMixin but I cannot seem to find a way to implement it successfully. I've taken a few approaches so far, including using APIView in addition to the methods seen below. Ultimately, I wish to pass the following to my view and have it update just the "order" field in my model. My model has many fields. ''' [ { "id": "1", "order": "5" }, { "id": "2", "order": "3" } ] ''' This is my view: class WaitlistListGen(generics.ListCreateAPIView): queryset = Waitlist.objects.all() serializer_class = WaitlistSerializer class WaitlistDetailGen(RetrieveUpdateDestroyAPIView): queryset = Waitlist.objects.all() serializer_class = WaitlistSerializer And, this is my serializer: class WaitlistSerializer(serializers.ModelSerializer): class Meta: model = Waitlist fields = '__all__' -
xml.etree.ElementTree.ParseError deploy lambda django with zappa
Traceback (most recent call last): File "C:\Users\kevin\AppData\Local\Programs\Python\Python39\lib\site-packages\botocore\parsers.py", line 504, in _parse_xml_string_to_dom root = parser.close() xml.etree.ElementTree.ParseError: no element found: line 1, column 0 raise ResponseParserError( botocore.parsers.ResponseParserError: Unable to parse response (no element found: line 1, column 0), invalid XML received. Further retries may succeed: b'' I tried to deploy my django project through zappa to create lambda and I got this error, can anyone help me with this? -
How to search for exact values in Django?
I have created a search function. However, it searches for all elements that contain the entered value. For example, there are the following elements: 44564, 76436, 445. When I enter "445", it shows "44564" and "445", but I need only 445. Or if I enter "64", then nothing should be shown, but "44564" and "76436" are shown. How to fix it? case_list.html <div> <h3>Search</h3> <form method="GET" action="{% url 'case_search' %}"> <input type="search" type="text" name="q" prequired placeholder="Put value"> <button type="submit">Find</button> </form> </div> <div> {% for case in object_list %} <div> <p>{{ case.name }}</p> </div> {% endfor %} </div> Views.py class CaseView(ListView): model = Case template_name = 'case_list.html' class CaseSearch(ListView): template_name = 'case_list.html' def get_queryset(self): return Case.objects.filter(name__icontains=self.request.GET.get("q")) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["q"] = self.request.GET.get("q") return context Urls.py path('case_list/', CaseView.as_view(), name='case_list'), path('case_list/search/', CaseSearch.as_view(), name="case_search"), -
How to display only search results in Django?
I have created a page where all objects are displayed. Also, there is a search. If you enter a query into a search, the page will display the search results. I would like nothing to be shown on the page by default, only the search bar. And only after entering a value in the search, the page shows the search results. How to do it? Home.html <div class="headtext"> <form method="GET" action="{% url 'search' %}"> <input type="search" type="text" name="q" prequired placeholder="Put appnumber"> <button type="submit">Find</button> </form> </div> <div> {% for application in object_list %} <div> <p>Application: {{ application.appnumber }}, status: {{ application.status }}</p> </div> {% endfor %} </div> Urls.py from django.urls import path from .views import HomeView, Search urlpatterns = [ path('', HomeView.as_view(), name="home"), path('search/', Search.as_view(), name="search"), Views.py class HomeView(ListView): model = Application template_name = 'home.html' class Search(ListView): template_name = 'home.html' def get_queryset(self): return Application.objects.filter(appnumber__icontains=self.request.GET.get("q")) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["q"] = self.request.GET.get("q") return context -
error: "Refused to apply style from ./static/css/main.739.css' because its MIME type ('text/html') is not a supMIME type, and strict MIME checking
I have a problem that I have wasted too much time on it. I would really appreciate some help. I try to serve my django (react at front) staticfiles with AWS s3. When I in DEBUG=True everything works fine (Due to the fact that it really uses the local files and not S3), but when I move to DEBUG=False I get the error and white screen: Refused to apply style from 'http://localhost:8000/static/css/main.7f770239.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Refused to execute script from 'http://localhost:8000/static/js/main.c2ee425b.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. and the network: Request URL: http://**localhost:8000**/static/js/main.c2ee425b.js Request Method: GET Status Code: 200 OK Remote Address: 127.0.0.1:8000 Referrer Policy: no-referrer-when-downgrade 2 NOTES: [1] It looks like is still try to serve from my local host and not from s3, and I checked all the appropriate configurations (see below). [2] I have no problem with the media files, I manage to upload files and view them using s3 bucket. I've followed quite a few guides, and no configuration has worked so far, currently I'm working like this: from storages.backends.s3boto3 import S3Boto3Storage … -
CRLF Injection with python
How can I write a simple web app that includes the CRLF vulnerability with python to test the vulnerability described here? https://www.geeksforgeeks.org/crlf-injection-attack/ I want to know if it is possible to do this with python.