Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display selection field in Django template
I 'm trying to find a workable solution for my problem. I have found two similar questions answered before, but still I can't solve it. If we have a class like this: from django.db import models class Consumer(models.Model): SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) name = models.CharField(max_length=60) size = models.CharField(max_length=2, choices=SIZES) And I did in my view and template like this (Learned from one tutorial) ***view with combined queries*** def staff_filter(request): qs = Consumer.objects.all() size= request.GET.get('size') # I have some other queries in between .... if is_valid_queryparam(size) and size!='Choose...': qs = qs.filter(size=consumer.get_size.display()) return qs def filter(request): qs=staff_filter(request) context={ 'queryset':qs, 'consumer':consumer.objects.all() } return render(request, 'filter.html',context) **template*** <div class="form-group col-md-4"> <label for="size">size</label> <select id="size" class="form-control" name="size"> <option selected\>Choose...</option> {% for size in consumer.get_size.display %} <option value="{{ size }}">{{size}}</option> {% endfor %} </select> </div> How should I correct it? Thanks! Display selection field in Django template -
"Can't start a new thread" error while running django server in gunicorn
I am running a django server in gunicorn. I noticed after creating a certain number of threads it cannot start new thread. This is my gunicorn service file: So, I tried to see the status of the gunicorn service file: sudo systemctl status medai-app.service output : It's showing the limit of tasks is 1143. I want to know how to increase this number. How is it determined as I did not find any configuration setting to tune this. My user's maxproc limit is 5000. The number of threads that's been created doesn't decrease, why? Shouldn't they be killed after finishing a task? -
use regex validator in django modelforms
i want to use regex validator for name field in model form i want users just can type english in this field and if they want type with another language get a error thank you help me how do that thanks -
Django's dumpdata only dumping auth permission and contenttypes data
I use local Postgres on the dev environment and deployed my app to Heroku with Postgres as well. I migrated my database, and now I want to load my data. The app works fine on Heroku, but without data. I have different settings files for dev and prod - with local Postgres and Postgres on Heroku correspondingly. I have my data on dev Postgres, and when I launch the app on dev - I see the data. To dump data I set my dev settings where dev database settings are: ./manage.py dumpdata --indent=4 --settings=app.settings.dev > data3.json I see that only data from auth.permission and contenttypes.contenttype are there: [{"model": "auth.permission", "pk": 1, "fields": {"name": "Can add log entry", "content_type": 1, "codename": "add_logentry"}}, {"model": "auth.permission", "pk": 2, "fields": {"name": "Can change log entry", "content_type": 1, "codename": "change_logentry"}}, {"model": "auth.permission", "pk": 3, "fields": {"name": "Can delete log entry", "content_type": 1, "codename": "delete_logentry"}}, {"model": "auth.permission", "pk": 4, "fields": {"name": "Can view log entry", "content_type": 1, "codename": "view_logentry"}}, {"model": "auth.permission", "pk": 5, "fields": {"name": "Can add permission", "content_type": 2, "codename": "add_permission"}}, {"model": "auth.permission", "pk": 6, "fields": {"name": "Can change permission", "content_type": 2, "codename": "change_permission"}}, {"model": "auth.permission", "pk": 7, "fields": {"name": "Can delete permission", "content_type": 2, … -
Rewrite top menu by DeleteView
I have a section 'About' which is rarely updated. I want each time this section is updated, the popup menu is re-generated. Thanks to Lucas Grugru see my previous question, I've partially solved the problem, but not fully. I rewrite the menu in my views which change the structure of the section (specifically, PageUpdateView and PageDeleteView). For this, I rewrote their standard get_success_url method, assuming that, it is the one which implements at the very last moment of page update / deletion (or not?). In this method, I select all objects (pages with their prefetched subpages), then generate an HTML code with the 'render_to_string' function, and then write it to a file. With PageUpdateView this works fine, but when I use PageDeleteView, the deleted page is not removed from the top menu. It happens because when I select objects with a queryset (see the code below), the deleted object is still there. about_list = Page.objects.filter(parent=None).order_by("order")./ annotate(num_subs=Count('subs')).prefetch_related( Prefetch( 'subpages', Page.objects.annotate(num_subs=Count('subs')), 'subpage') ) Of course, I could exclude this object by its slug name (exclude(slug=self.kwargs['slug'])), but I suspect that there should be a more proper way to update a menu once the structure of the site changes. -
"detail": "JSON parse error - Expecting ',' delimiter:
I dont know what is wrong with json, trying to pass a post request but its giving me this error ' "detail": "JSON parse error - Expecting ',' delimiter: line 3 column 34 (char 36)" ' This is what i passed as my post request { "song" :{"artiste": ["first_name": "Kizz", "last_name": "Daniel", "age": 30], "title": "Buga", "likes": 3}, "content": "chilled music" } My model: class Song(models.Model): artiste = models.ForeignKey(Artiste, on_delete=models.CASCADE, null=True) title =models.CharField(max_length=100) date_released = models.DateTimeField(auto_now_add=True, null=True) likes = models.IntegerField() # artist_id = models.CharField(max_length=50, null=True) def __str__(self): return self.title class Lyrics(models.Model): song = models.ForeignKey(Song, on_delete=models.CASCADE) content = models.TextField() rest_framework serializer: class LyricsSerializers(serializers.ModelSerializer): song = SongSerializers(many=True) class Meta: model = Lyrics fields = ["song", "content"] rest_framwork Api views: class lyricsApiView(APIView): def get(self, request): lyrics = Lyrics.objects.all() serializer = SongSerializers(lyrics, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = LyricsSerializers(data=request.data) if serializer.is_valid(): artiste = serializer.validated_data.pop('artist') artiste_create = Artiste.objects.create(**artiste) song = serializer.validated_data.pop('song') song_create = Song.objects.create(**serializer.validated_data, artiste=artiste_create) lyrics_create = Lyrics.objects.create(**serializer.validated_data, song=song_create) return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django CSRF token in template outdated after login
Django allows adding CSRF token to webpage by rendering it to the template with {% csrf_token %} Now here is the situation. I have two tabs opened with public pages of my website which don't require login, and is viewing them as anonymous user. Both tabs of course share the same CSRF token. Now I perform user login using tab 1. This triggers rotation of the CSRF token and updates the cookie with the new token. This means the CSRF token rendered to the webpage of tab 2 is now outdated. So any further POST or AJAX requests sent from tab 2 will return 403, making my website on tab 2 behave incorrectly until I reload the page. Does this mean, that to avoid this problem I should never rely on {% csrf_token %} and always retrieve csrf token from the cookie before posting any ajax requests? This sounds a little strange so maybe I'm missing something. I was expexting {% csrf_token %} to be a reliable source of the csrf token, but seems like it is not. -
Connection Error while creating Database in Django
I got this error while running python manage.py migrate --run-syncdb Error msg- conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "hbhavane" does not exist My settings.py file database DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "hbhavane", "USER":"postgres", "PASSWORD": "honey111", "HOST":"localhost", "PORT":"5432" } } -
how to get only values from query dict
if request.method == 'POST': product=request.POST.get('product') upload_month = request.POST.get('upload_month') un_month= Planning_quantity_data.objects.values('month').filter(product=product,upload_month=upload_month).distinct() print(un_month) <QuerySet [{'month': 'Mar_22'}, {'month': 'Apr_22'}, {'month': 'May_22'}, {'month': 'Jun_22'}]> i want to get only the values without key and store it in a new list in views.py file like newlist = ['Mar_22' , 'Apr_22', 'May_22','Jun_22'] while i am using un_month1=list(un_month.values()) print(un_month1) it is showing like this [{'id': 1, 'upload_month': 'Mar_22', 'product': 'MAE675', 'material_code': 'MAE675 (MEMU â OB) RCF', 'order_type': 'Onhand', 'BOM_CODE': '675MEMU', 'month': 'Mar_22', 'quantity': 3, 'po_value': '37/5', 'remarks': 'Qty in Rakes. 3-5 rakes partial qty dispatched', 'empid': None}, {'id': 2, 'upload_month': 'Mar_22', 'product': 'MAE675', 'material_code': 'MAE675 (MEMU â OB) RCF', 'order_type': 'Onhand', 'BOM_CODE': '675MEMU', 'month': 'Apr_22', 'quantity': 3, 'po_value': '37/5', 'remarks': 'Qty in Rakes. 3-5 rakes partial qty dispatched', 'empid': None}, {'id': 3, 'upload_month': 'Mar_22', 'product': 'MAE675', 'material_code': 'MAE675 (MEMU â OB) RCF', 'order_type': 'Onhand', 'BOM_CODE': '675MEMU', 'month': 'May_22', 'quantity': 3, 'po_value': '37/5', 'remarks': 'Qty in Rakes. 3-5 rakes partial qty dispatched', 'empid': None}] -
Unsafe redirect to URL with protocol django rest framework
When the user completes the registration process, I want to redirect her to the login page, where I get the following error. Unsafe redirect to URL with protocol 'accounts' What method should I use to solve this error? class RegisterUser(APIView): serializer_class = RegisterSerializer def post(self, request): serializer = self.serializer_class(data=request.POST) serializer.is_valid(raise_exception=True) serializer.save() return HttpResponseRedirect('accounts:login') -
Check how much progress is done in the backend using Django?
I have been developing a machine learning web app and I am using Django as backend. Now the task has to be done by 3 models, so it takes some time to finally generate predictions. Can you please guide me how can I show the progress to the user at the front end so that he can know how much is done at the backend. Thanks! I found out a module name celery in python, but can you please guide me a little bit more if you have done any similar task before. -
Trying to implement uploading products via excel sheet python react
I have a simple dashboard built in react and backend with django. I want to implement the feature where user can import an excel sheet from the frontend and be able to add products to the database. I am not sure how I'd be able to do that. Can anyone point me to the right direction? -
Django: how do I implement a functional delete button for an object where the view loops thru api request data?
Basically I have this little weather application from a tutorial I followed and am trying to extend functionality. The app will take a city input POST request from user, call openweather api, loop through all cities then appends that openweather api (dict) data into a python list. The list is then called by 'context' variable to render the data in template. I am trying to add a functional delete button to each city shown on the page, sounds easy but since the view is making an api call and putting it in a list, that data doesn't have a city.id. This results in a NoReverseMatch error in my template. I tried to split the view up into parts. If I segregate the cities = City.objects.all() and just set context = {'cities': cities}, my city_delete function works properly with the city.id. I was able to delete the City from the template. But am not able to render the api data into the same bootstrap card because of the context dict. Views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView import requests from environs import Env from .models import City, Words from .forms import CityForm env = Env() env.read_env() WEATHER_API_KEY = … -
how can i fix django lazy reference to app?
i had this problem when i create abstract user model , because i need multiuser in my app web raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'accounts.user', but app 'accounts' doesn't provide model 'uoesn't provide model 'user'. how can i solve it and thanx -
Django form data loop
How can I loop through form data where the ending part could be 1,2,3,4 and so on, and store in the DB without hardcoding the DB like below so each description would be on its own line but one person could post description1-10 and the other 10-27 and so on for example instead of say this order.description_1 = request.POST.get('description1') order.length_1 = request.POST.get('length1') order.width_1 = request.POST.get('width1') order.depth_1 = request.POST.get('depth1') order.weight_1 = request.POST.get('weight1') order.description_2 = request.POST.get('description2') order.length_2 = request.POST.get('length2') order.width_2 = request.POST.get('width2') order.depth_2 = request.POST.get('depth2') order.weight_2 = request.POST.get('weight2') currently the form passes request.POST.get('description1') and with a limit of request.POST.get('description5') but would like each description on its own row and not be subject to a hardlimit and uses a bit of javascript to append the x value to the name. The postdata form is also hardcoded so not using forms.py -
Django Return redirect working for one view but not for the other
I cannot understand why it is working in one instance but not the other. I am working with django and output in django template. The only difference between the views/functions are in the second one (the one that is not working) I update the field with time. Time updates, saves in the model and displays updated time correctly. It is just the redirect that is not working. The working redirect code- Template, this code takes me to the edit page. Name of the url is "update" - <td><a href="{% url 'update' i.id %}"><button>Edit</button></a></td> The form on the dit page- {% block content %} <div class="wrapper"> <h1 class="ok">Entry Form</h1> <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" value="submit"> </form> </div> <br> {% endblock content %} url- path('update_entry/<str:pk>/', views.update, name = "update"), And views.py- def update(request, pk): order=Bank1.objects.get(id=pk) form = Bank1Form(instance=order) if request.method == 'POST': form = Bank1Form(request.POST, instance=order) if form.is_valid(): form.save() return redirect('/bank1') context = {'form':form} return render(request, 'myapp/entry.html', context) Now here is the non working code. Template, the line that takes me to the update page. Name of the url is "update_enter_workout.- <td><a href="{% url 'update_enter_workout' i.id %}"><button>Start Time</button></a></td> Form on the Edit page. Didn't add the entire form … -
DJANGO SENDING ORDERS TO THE DATABASE WITHOUT ANY PAYMENT GATEWAY
How do i send my order to my database in django i'm beginner in django, and i'm trying to build an ecoomerce sute . although i'm not using the same payment gateway so its difficult for me to fllow up. i want the order details to be saved in the database. help my orders view from django.shortcuts import render from django.http.response import JsonResponse from django.shortcuts import render from cart.cart import Cart from .models import Order, OrderItem Create your views here. def add(request): cart = Cart(request) if request.POST.get('action') == 'post': user_id = request.user.id carttotal = cart.get_total_price() # Check if order exists if Order.objects.filter(order_key=order_key).exists(): pass else: order = Order.objects.create(user_id=user_id, full_name='name', address1='add1', address2='add2', total_paid=carttotal, order_key=order_key) order_id = order.pk for item in cart: OrderItem.objects.create(order_id=order_id, product=item['product'], price=item['price'], quantity=item['qty']) response = JsonResponse({'success': 'Return something'}) return response def payment_confirmation(data): Order.objects.filter(order_key=data).update(billing_status=True) def user_orders(request): user_id = request.user.id orders = Order.objects.filter(user_id=user_id).filter(billing_status=True) return orders {% extends "../store/base.html" %} {% load static %} {% block title %}Order{% endblock %} {% block content %} <style> .account-form input, { border: 2px solid #ccc; height: calc(2em + .75rem + 2px); } .form-control { border: 2px solid #ccc; } .account-form input:focus { border-color: #1497ff; box-shadow: inset 0 0px 0px rgba(0, 0, 0, 0.075), 0 0 0px … -
ImportError: cannot import name 'ToDoList' from 'MyApp.models'
from django.db import models # Create your models here. class ToDolist(models.Model): name = models.CharField(max_length=200) def _str_(self): return self.name class Item(models.Model): ToDolist = models.ForeignKey(ToDolist, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() def _str_(self): return self.text >>> from MyApp.models import Item, ToDoList Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name 'ToDoList' from 'MyApp.models' (/home/x390/Desktop/Project/MyProject/MyApp/models.py) Noob to Django, Stack overflow and development in general. Can import 'Item' module but not 'ToDoList' Module resulting in ImportError -
Pass data as list of dictionaries to Django Formset?
I have a model called Reporter and a straight-forward ReporterForm and a formset based on it called ReporterFormset as below: class Reporter(models.Model): name = models.CharField(max_length=100) class ReporterForm(forms.ModelForm): class Meta: model = Reporter fields = '__all__' ReporterFormset = modelformset_factory(Reporter, form=ReporterForm, extra=1, can_delete=True) I want to save new data coming as list of dictionaries like: data = [ {'name': 'x'}, {'name': 'y'} ] So, I tried to do: reporters_formset = ReporterFormset(initial=data) But it shows that the formset is not valid after executing reporters_formset.is_valid() and with empty reporters_formset.errors. So, how can I achieve such? -
useState is not working inside of useMutation mutate, during cloudflare image upload
I'm such a newbie in programming. Start to build Website with these things Django : backend React.JS-TypeScript : Frontend Chakra-UI : CSS While I'm build my site, I want to use "cloudflare" as an image source. And made post request page below. root/src/api.tsx export interface IUploadQuestionVariables { pk: string; title: string; contents: string; tags: number[]; terms: number[]; photos: FileList; } export const uploadQuestion = (variables: IUploadQuestionVariables) => instance .post(`questions/`, variables, { headers: { "X-CSRFToken": Cookie.get("csrftoken") || "", }, }) .then((response) => response.data); export const getUploadURL = () => instance .post(`medias/photos/get-url`, null, { headers: { "X-CSRFToken": Cookie.get("csrftoken") || "", }, }) .then((response) => response.data); export interface IUploadImageVariables { file: FileList; uploadURL: string; } export const uploadImage = ({ file, uploadURL }: IUploadImageVariables) => { const form = new FormData(); form.append("file", file[0]); return axios .post(uploadURL, form, { headers: { "Content-Type": "multipart/form-data", }, }) .then((response) => response.data); }; export interface ICreatePhotoVariables { questionPk: string; file: string; } export const createPhoto = ({ questionPk, file }: ICreatePhotoVariables) => instance .post( `questions/${questionPk}/photos`, { file }, { headers: { "X-CSRFToken": Cookie.get("csrftoken") || "", }, } ) .then((response) => response.data); root/src/route/QuestionUpload.tsx .../ interface IForm { pk: string; title: string; contents: string; tags: number[]; terms: number[]; photos: FileList; … -
Django 4.1 delete posts, checkboxes not spam wtf
i have big issue, i am confusing and I don't know how can I make it. I am trying to create app where user can create posts, view all posts and delete it with checkboxes and one button. I have all withnout this delete posts with checkboxes.In bulk. It is tough for me. I heard that it goes through django forms, but I couldn't find anything anywhere and I don't understand it. Could you help me please? This is my piece of code: def delete_post(request): if request.method == 'POST': pk_list = request.POST.getlist('mylist[]') for posts_pk in pk_list: data = TodoModel.objects.filter(id=posts_pk) print(data) data.delete() return redirect('current') {% for model_attribute in mydata %} <h3>{{ model_attribute.title }}</h3><input type="checkbox"> <p>{{ model_attribute.memo }}</p> <p>{{ model_attribute.created }}</p> {% csrf_token %} {% endfor %} path('delete/<int:pk>', views.delete_post, name='deletepost'), class TodoModel(models.Model): title = models.CharField(max_length=100) memo = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) important = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.user.id) + " " + self.user.username + " " + self.title I tried searching all over the internet but it either didn't work or I couldn't find it. I asked people, but no one gave me specific advice. Please give me advices or guide how can I … -
Python 2D Data Dictionary using Django model query
I am trying to create a 2D python data dictionary using the output of Django Querysets. I have a data model that looks like this; class vascProsthesis(models.Model): prosthesisID = models.IntegerField(primary_key = True) prosthesisCategory = models.CharField(max_length=255, blank=True, null=True) prosthesisSubCategory = models.CharField(max_length=255, blank=True, null=True) prosthesisCompany = models.CharField(max_length=255, blank=True, null=True) prosthesisName = models.CharField(max_length=400, blank=True, null=True) prosthesisDetails = models.TextField( blank=True, null=True) class Meta: ordering = ['-prosthesisID'] I want to create an ordered "Tree structure" using the data in the model that looks like this; -prosthesisCategory1 |__prosthesisCompany1 | |__prosthesisName1 | |__prosthesisName2 |__prosthesisCompany2 | |__prosthesisName3 To achieve this, I tried to create a Python 2D Data dictionary that I can pass as to my template to generate the tree structure. proc = {} prosth = vascProsthesis.objects.order_by().values_list('prosthesisCategory', flat=True).distinct() companyList = vascProsthesis.objects.order_by().values_list('prosthesisCompany', flat=True).distinct() for procCat in prosth: proc[procCat] = {} for company in companyList: proc[procCat][company] = vascProsthesis.objects.filter(prosthesisCategory=procCat, prosthesisCompany=company).values('prosthesisID', 'prosthesisName') But I keep getting a "KeyError". What is the mistake I am making? Is there a better way to achieve this? I am using JS and CSS to generate my tree view. <ul class="tree"> <li> <input type="checkbox" checked="checked" id="c1" /> <label class="tree_label" for="c1">Level 0</label> <ul> <li> <input type="checkbox" checked="checked" id="c2" /> <label for="c2" class="tree_label">Level 1</label> <ul> <li><span class="tree_label">Level 2</span></li> … -
how do I add emojis to django url patterns?
I want to make an api that has the heart emoji in it , for example api.com/❤ it is possible , check this out for instance https://techmighty.in/%E2%9D%A4-emoji-use-in-domain-name-or-urls-of-website-%E2%9D%A4/ this is what my urlpatterns are like urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('<slug:slug>', views.index2) ] I tried going to localhost:8000/omg21😊 and this is the error that I get Not Found: /omg21😊 [04/Nov/2022 22:24:03] "GET /omg21%F0%9F%98%8A HTTP/1.1" 404 2378 as you can see, the emoji gets converted to its hex form , that's why slug:slug is supposed to pick it up , but it simply doesn't I tried searching the following on google "how to add an emoji to a url in django in 2022" "how to add an emoji to a url in django in 2021" "how to add an emoji to a url in django in 2020" "how to add the heart emoji to a url in django" and got nowhere -
Chave primaria composta em Django (Python)
Eae galera, preciso urgente entender como faz para ter chave primaria composta em nos models do Django. Também precisaria fazer esses dois campos virarem chave estrangeira de outra Tabela. Meus models estão assim até agr, porem a unica chave primaria ainda é o Id. class Create_CRM(models.Model): STATUS = ( ('Em processo', 'em processo'), ('Finalizadas','finalizadas'), ('Pendentes', 'pendentes') ) COMPLEXIDADE = ( ('Alta', 'alta'), ('Media','media'), ('Baixa', 'baixa') ) class Meta: db_table = 'create_crm' constraints = [ models.UniqueConstraint(fields = ['id', 'versao'], name ='double_constraint') ] id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') versao = models.IntegerField(null=False, default=1) data_criacao = models.DateField() descricao = models.TextField() objetivo = models.TextField() justificativa = models.TextField() dependencia = models.BooleanField(default=False) mostrar_crm = models.BooleanField(default=True) empresa = models.CharField(max_length=50) status_crm = models.CharField(max_length=50, choices=STATUS, default='Pendentes') complexidade_crm = models.CharField(max_length=50, choices=COMPLEXIDADE, blank=True) file = models.FileField(blank=True, upload_to='files/%Y/%m/',) solicitante = models.ForeignKey(CustomUser, on_delete=models.CASCADE) setor = models.ManyToManyField(Setor, related_name='setores_crm') def __str__(self): return f'CRM - {self.id}' E eu precisaria fazer os campos id e o campo versão virar chave estrangeira de outra tabela Tem como fazer isso? E se tiver, como? E eu precisaria fazer os campos id e o campo versão virar chave estrangeira de outra tabela Tem como fazer isso? E se tiver, como? -
The nonetype value comes from the django form
I am a beginner in Django. I have a form with a field "count_cont" . And i want to get integer value from this field, but i have "nonetype". count_cont = forms.IntegerField(max_value=5, min_value=1) And i want to get integer value from this field, but i have "nonetype". n=int(str(request.POST.get("count_cont"))) I try to convert it with int() and str() functions, but i get error "invalid literal for int() with base 10: 'None'"