Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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'" -
Django - SubQuery e function F()
I have 2 models (author and book). I want to annotate in the author model the highest book price for every authors (in order to manipulate it later). I would like to make a query with an internal sub-query using the F() function but the problem is that the F() is refered to the book model but I would like to refer it to the author model. I'll show that with an example. The models are shown below: class author: authorID = models.AutoField(primary_key = True, auto_created = True, unique = True) name = models.CharField(max_length=100) surname = models.CharField(max_length=100) class book: ownerID = models.ForeignKey(author, on_delete = models.CASCADE, related_name='hook') title = models.CharField(max_length=100) price = models.IntegerField() The query in question is as follows: value = author.objects.annotate(maxPrice = (book.objects.filter(ownerID = F('authorID')).order_by('-price') [0])) F('authorID') is refered to the book DB and so Django returns an error but I want to refer it to the author DB to achieve my goal. How can I do that? Thanks -
TypeError at /vendor/add-Menuproduct/ __init__() takes 2 positional arguments but 3 were given
form.py from django.forms import models from django.forms import ModelForm, Textarea from product.models import Product,MenuProducts from django import forms class ProductForm(ModelForm): class Meta: model = Product fields = ['category', 'image', 'title', 'description', 'price','stock'] class MenuProductForm(ModelForm): # Time = models.DateTimeField(widget=forms.DateInput(attrs={'class': 'form-control'})) class Meta: model = MenuProducts fields = [ 'YourProduct', 'Stock', 'Day', 'Time','city', 'address', 'ingredientA', 'ingredientB', 'ingredientC', 'PriceRange','city'] def __init__(self, user, **kwargs): super(MenuProductForm, self).__init__(**kwargs) self.fields['YourProduct'].queryset = Product.objects.filter(vendor__name=user) # widgets = { # 'Time': forms.DateInput(attrs={'class': 'form-control'}) # } form.py @login_required def add_Menu_product(request): if request.method == 'POST': print("Add Menu Product") print(request.user.vendor) form = MenuProductForm(request.POST, request.FILES) if form.is_valid(): Menuproduct = form.save(commit=False) # Because we have not given vendor yet Menuproduct.vendorfk = request.user.vendor # Menuproduct.slug = slugify(Menuproduct.title) Menuproduct.save() #finally save return redirect('vendor:vendor-admin') else: print("Form ") form = MenuProductForm(user=request.user.vendor) print(request.user.vendor) return render(request, 'vendor/add_menu_product.html', {'form': form}) What should be done in order to resolve this issue TypeError at /vendor/add-Menuproduct/ init() takes 2 positional arguments but 3 were given What should be done in order to resolve this issue TypeError at /vendor/add-Menuproduct/ init() takes 2 positional arguments but 3 were given -
query to get every user data belong
I want to write Query Set that show every User Access To Own IP and Asset_Name from django.db import models from django.contrib.auth.models import User class Asset(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) IP = models.GenericIPAddressField() Asset_name = models.CharField(max_length=255) I want every user see details(IP,Asset_Name) in own user Profile The problem comes when trying to query the database, and using a string compared to an auth.User object. I do not know how to get around this? -
How to create model object that via user foreignkey, FOREIGN KEY constraint failed?
In my view I am creating the object, and in this model that I am creating is one field, name=models.ForeignKey(User, on_delete=models.CASCADE). And I am using ForeignKey because in this oject can be made multiple time by a single user. And I get an error django.db.utils.IntegrityError: FOREIGN KEY constraint failed Here is the model: from django.contrib.auth.models import User ... class Customer_status(models.Model): name = models.ForeignKey(User, null=True, on_delete=models.CASCADE) creation_date = models.CharField(max_length=28) status=models.CharField(max_length = 8) def __str__(self): return str(self.name) + '_' +str(self.id) And in this view I am creating this model: def status_create(request): Customer_status.objects.create ( name=request.user, creation_date=datetime.datetime.now(), status='Pending' ) The thing is that I had OneToOne field on name and I had Unique integrity error, after I changed it to ManyToMany I have the this error django.db.utils.IntegrityError: FOREIGN KEY constraint failed. I am thinking that the error is causing the "name=request.user" in creating step -
How can I implement delete action in viewset in django?
Here is my view file. import json from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.parsers import JSONParser from django.http import JsonResponse from django.core import serializers from .serializers import TodoSerializer from .models import Todo # Create your views here. class TodoView(APIView): def post(self, request): serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() print(serializer.data) return JsonResponse(serializer.data, status=200) def get(self, request): obj_list = [] for item in Todo.objects.all(): if item.todo_delete is False: obj_list.append({"todo_id": item.todo_id, "todo_desc": item.todo_desc, "todo_complete": item.todo_complete, "todo_delete": item.todo_delete}) return JsonResponse({"todo": obj_list}, status=200) def update(self, request): return Response("Hello") def delete(self, request): print (request.data) return Response("Hello") I am going to implement delete action for specific todo by passing id. Front End Part is here. try { const res = await axios.delete(`${BASE_URL}/api/todo/${id}/`) } catch (e) { return { success: false, error: e } } And url file is here path('todo/', TodoView.as_view()), But I can see this error Not Found: /api/todo/e709750f-5bb6-4dba-b6b1-966beeeb9c3d/ How can I fix this error? How to set correct delete endpoint and get id from client? -
Django - How to redirect users without hard-coding URLS
I am creating Django Application. We want user to be redirected to new screen on button click, but we don't want to have to hardcode URL. We have a top level screen, and we want to redirect user to screens after they click a button on the Level screen, However, we have multiple level screens so it would't make sense to hardcode each URL for each section of the Level screen. Here is the view for the Level1 Screen as an example: def level1(request): return render(request, 'Levels/level/Welcome1.html') As you can see, we render out Welcome1.html, however, we also have other Welcome screens assosiated with level 1, like Welcome2.html and Welcome3.html. This is the URL for level 1: path('levels/level1/', views.level1, name = "level1") Again, it would't make sense for us to have a URL for each level (level 1, level2) and then all the subscreens for them such as Welcome1, Welcome2. How can I make it so I can associate different screens with a URL and not have to render them out individually? I am not sure how to go about doing this problem. We are working on big project and can give part of budget to someone who helps solve. -
Printing username on stdout with Django + Gunicorn Application
Right now my Django + Gunicorn app is printing only this info: [03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 If request is authorized, I would like to show also user (username/email) behind the status code, something like: [03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 - useremail@outlook.com If the request is not authorized then write UNAUTHORIZED: [03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 - UNAUTHORIZED How can I achieve this with a combination of Django and Gunicorn? Thank you