Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
many to one field self relationship
i used a self relation ship inside model with foreignkey , purpose was to make a replyable comment , but idk how to use it in templates, i mean whats different between 3 ManyToOne relationships i used in template , how can i know form send reply or comment? model: class Comment(models.Model): #comments model post = models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE) text = models.CharField(max_length=300) user = models.ForeignKey(get_user_model(),related_name='users',on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) parent = models.ForeignKey('self', null=True,related_name='reply',on_delete=models.SET_NULL) class Meta(): verbose_name_plural = 'Comments' ordering = ['date'] def __str__(self): return self.test[:50] template: <div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button value="submit">Send</button> </form> </div> <div> {% for comment in object.comments.all %} <p>{{ comment.text }}</p> {% for reply in object.reply.all %} <p>{{ reply.text }}</p> {% endfor %} <form method='post'> {% csrf_token %} {{ form.as_p }} <button value="submit">reply</button> </form> {% endfor %} </div> {% endblock %} can you a little explain how it works? -
How to set the extra value to 0 if the item is saved unchanged in django admin?
I use tablularinline and now when I save the item without any changes, 3 values are added to it. How can I set the extra value to 0 if the item is saved without changes? class ProductPictureAdminInline(SortableTabularInline): formset = CustomInlineFormSet fields = ("title", "image", "is_default", "order", "created_by", "created_at", "updated_at") readonly_fields = ("created_by", "created_at", "updated_at") model = ProductPicture def get_extra(self, request, obj=None, **kwargs): if obj: return 0 # For changing an item else: return 3 # For adding a new item -
How to debug 400 bad request with axios uploading file to Django restframework
I bumped into this error when uploading file from browser. Same javascript code was working yesterday ,but today it's not. I start digging into the error but not found the clue. in browser console. { "message": "Request failed with status code 400", "name": "AxiosError", "stack": "AxiosError: Request failed with status code 400\n at settle (webpack://frontend_react/./node_modules/axios/lib/core/settle.js?:24:12)\n at XMLHttpRequest.onloadend (webpack://frontend_react/./node_modules/axios/lib/adapters/xhr.js?:120:66)", "config": { "transitional": { "silentJSONParsing": true, "forcedJSONParsing": true, "clarifyTimeoutError": false }, "adapter": [ "xhr", "http" ], "transformRequest": [ null ], "transformResponse": [ null ], "timeout": 0, "xsrfCookieName": "csrftoken", "xsrfHeaderName": "X-CSRFTOKEN", "maxContentLength": -1, "maxBodyLength": -1, "env": {}, "headers": { "Accept": "application/json, text/plain, */*", "X-CSRFTOKEN": "Na6rGVCyq1lgDxeiks0LdHjrU5nLVpmp" }, "withCredentials": true, "method": "post", "url": "http://localhost:8000/api/drawings/", "data": {} }, "code": "ERR_BAD_REQUEST", "status": 400 } in django runserver console there is not almost hint. [15/Feb/2023 09:06:21] "GET /undefined HTTP/1.1" 404 3566 Bad Request: /api/drawings/ [15/Feb/2023 09:06:24] "POST /api/drawings/ HTTP/1.1" 400 36 My source code is like this below. formData.append("drawing",filePath); formData.append("detail",JSON.stringify({})); axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios.post( `http://localhost:8000/api/drawings/`,formData,{ headers: {'Content-Type': 'multipart/form-data'} } -
VS-Code Languages Mode more than one language definition
I am writing Django, Coding in template html using VS-Code IDE. When Language Mode is set on Django HTML then VSCode not autocomplete HTML codes. (e.g. not auto-closing with </html> and so one) Thus get autocomplete works on Django codes. (e.g. {% auto-closing %} and...) And vice versa. I need the VSCode Language Mode set on either Django HTML and 'HTML` same, auto complete each one codes. -
How to store and display map location in wagtails
I am trying to create an API for contact us page. The API take location through map click at wagtail admin panel and send API too. For now I want to know how can I ask user to pin a location and store it in my model. I cant think of anything to do. class Contact_UsPage(Page): pass My page name is Contact us thank you. I tried looking at official wagtails documentation and couldn't find anything that would help me. -
Django user.is active
Why when i desactive user on Django admin site in my class in post method requirement return negative first if requirement user is not None ? Probably if user desative true Django don`t look him in user table ? class LoginView(View): template_name = 'login.html' def get(self, request): form = LoginForm() return render(request, self.template_name, locals()) def post(self, request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('home') else: alert = messages.error(request, 'Twoje konto zostało zablokowane!') return render(request, self.template_name, locals()) else: alert = messages.error(request, 'Błędna nazwa użytkownika!') return render(request, self.template_name, locals()) -
List of months from django queryset
this is the model class PaymentChart(models.Model): pharma = models.ForeignKey(PharmacyProfile , on_delete=models.CASCADE) wholesale = models.ForeignKey(WholesaleProfile , on_delete=models.CASCADE) amount = models.CharField(max_length=10) reqeuest = models.BooleanField(default=False) paid = models.BooleanField(default=False) date = models.DateTimeField() credit = models.BooleanField(default=False) class Meta: ordering = ['-date'] i want to filter the list of all months, .ie [09/2021,10/2021,11/2021] -
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>'),