Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload image from request.POST in django
I have a class 'product' with a field Imagefield called 'image'. I want to make an upload form for change the image. product.image= request.POST.get('image',product.image) In this mode, i'm able to change the image with a new one, but if i don't want to change it, the image uploaded before doesn't exists anymore. In the db, the field 'image' is empty. def update_product(request,id): templ="products/update_product.html" ctx={} product= Product.objects.get(id=id) if product.type == "computer": computer= Computer.objects.get(product_id=id) ctx={ "prodotto":product, "computer":computer} if product.type == "smartphone": smartphone= Smartphone.objects.get(product_id=id) ctx={ "prodotto":product, "smartphone":smartphone} if request.method=="POST": product.image = request.FILES.get('image',product.image) product.name= request.POST.get('name',product.name) product.product_code=request.POST.get('product_code',product.product_code) product.productor=request.POST.get('productor',product.productor) product.color=request.POST.get('color',product.color) product.size=request.POST.get('size',product.size) product.weight=request.POST.get('weight',product.weight) product.price= request.POST.get('price',product.price) quantity= int(request.POST.get('quantity',product.quantity)) if quantity>0: product.available=True else: product.available=False product.quantity=quantity product.save() if product.type == "computer": computer.display_size=request.POST.get('display_size',computer.display_size) computer.display_resolution=request.POST.get('display_resolution',computer.display_resolution) computer.cpu=request.POST.get('cpu',computer.cpu) computer.ram=request.POST.get('ram',computer.ram) computer.disk_size=request.POST.get('disk_size',computer.disk_size) computer.disk_type=request.POST.get('disk_type',computer.disk_type) computer.operating_system=request.POST.get('operating_system',computer.operating_system) computer.graphic_card=request.POST.get('graphic_card',computer.graphic_card) computer.battery_autonomy=request.POST.get('battery_autonomy',computer.battery_autonomy) computer.additional_function=request.POST.get('additional_function',computer.additional_function) computer.save() if product.type =="smartphone": smartphone.display_size=request.POST.get('display_size',smartphone.display_size) smartphone.cpu=request.POST.get('cpu',smartphone.cpu) smartphone.ram=request.POST.get('ram',smartphone.ram) smartphone.disk_size=request.POST.get('disk_size',smartphone.disk_size) smartphone.operating_system=request.POST.get('operating_system',smartphone.operating_system) smartphone.battery_autonomy=request.POST.get('battery_autonomy',smartphone.battery_autonomy) smartphone.camera= request.POST.get('camera',smartphone.camera) smartphone.additional_function=request.POST.get('additional_function',smartphone.additional_function) smartphone.save() return redirect('home') return render(request,template_name=templ,context=ctx) -
How I can implement this logic in Django where seller user can only sale products and buyer can only buy product?
I have scenario in which seller can only sale products while buyer can only buyer products I am new in Django I have no idea how can i implement this logic? -
Django template doesn't display dictionary elements
I have a dictionary named Rooms. I am sending the dictionary elements to home.html Views.py from django.shortcuts import render # Create your views here. rooms = [ {'id': 1, 'name': 'Lets learn Python!'}, {'id': 2, 'name': 'Front-End Developer'}, {'id': 3, 'name': 'Back-End Developer '}, ] def home(request): context = {'rooms': rooms} return render(request, 'base/home.html', context) def rooms(request, pk): room = None for i in rooms: if i['id'] == int(pk): room = i context = {'room': room} return render(request, 'base/room.html', context) home.html {% extends 'main.html' %} {% block content %} <h1>Home Template</h1> <div> <div> {% for room in rooms %} <div> <h5>{{room.id}} -- <a href="/room/{{room.id}}">{{room.name}}</a></h5> </div> {% endfor %} </div> </div> {% endblock content %} Home.html displays <h5> text but does not display the dictionary elements.I have tried renaming context variable. -
Django queryset: annotate with calculated value
I am making a very simple notification system for my website, powered by a Django REST Framework API. It's for sending website updates and things to all users, everyone gets the same notifications, and they can then mark it as read / archive it. I have come up with the following model: class Notification(models.Model): title = models.CharField(max_length=255) text = models.TextField() type = models.CharField(max_length=255, blank=True) read_by = models.ManyToManyField(User, blank=True, related_name="read_notifications") archived_by = models.ManyToManyField(User, blank=True, related_name="archived_notifications") created_at = models.DateTimeField(auto_now_add=True, db_index=True) updated_at = models.DateTimeField(auto_now=True) So there is no receiver field or something like that, as all users get all notifications anyway. Now I am trying to write the view logic, notably the following 2 things: only fetch non-archived notifications made after the user was created, and add a calculated "is_read" field to it, in a way that doesn't do extra queries for every single notification / user combination. The query looks like this now: queryset = Notification.objects .order_by("-created_at") .filter(created_at__gt=self.request.user.created_at) .exclude(archived_by=self.request.user) This does indeed filter out archived queries as expected, and I think it's doing it without an extra query for every notification: SELECT "notifications_notification"."id", "notifications_notification"."title", "notifications_notification"."text", "notifications_notification"."type", "notifications_notification"."created_at", "notifications_notification"."updated_at" FROM "notifications_notification" WHERE ("notifications_notification"."created_at" > 2022-09-26 12:44:04.771961+00:00 AND NOT (EXISTS(SELECT 1 AS "a" FROM … -
Overwriting save method to create entry in related table automatically django
After registration email with email confirmation is sent to a new user. I created model UserWithConfirmation with new field is_email_confirmed. I was following this https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#extending-the-existing-user-model. I want to have UserWithConfirmation created for each new user when user is saved. For now I have sth like this. from django.db import models from django.contrib.auth.models import User class UserWithConfirmation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_with_confirmation") is_email_confirmed = models.BooleanField(default=False) def __str__(self): return self.user.username class User: def save(self, *args, **kwargs): super().save(*args, **kwargs) create_user_with_confirmation(User) def create_user_with_confirmation(user): UserWithConfirmation(user=user) UserWithConfirmation.save() How to make it works? -
django REST framework - AttributeError: 'ResetPasswordRequestSerializer' object has no attribute 'id'?
I am trying to set-up RequestPasswordResetAPI endpoint. # Serializer class ResetPasswordRequestSerializer(serializers.Serializer): email = serializers.EmailField(min_length=2) class Meta: fields = ['email'] def validate(self, data): print(data) # Check if email exists if data.get('email', ''): try: # Get the user user = User.objects.get(email=data.get('email', '')) print(f"User from validate {user}") return user except: print('exception') raise serializers.ValidationError("Email is not registered") raise serializers.ValidationError("Email is not registered") api.py class ResetPasswordRequesAPI(generics.GenericAPIView): serializer_class = ResetPasswordRequestSerializer def post(self, request, *args, **kwargs): print('make request') serializer = self.get_serializer(data=request.data) print('first line done') serializer.is_valid(raise_exception=True) # user = serializer.save() user = serializer.validated_data print(user) user = ResetPasswordRequestSerializer( user, context=self.get_serializer_context()) print(f"user is {user}") uidb64 = urlsafe_base64_encode(user.id) token = PasswordResetTokenGenerator().make_token(user) print(f"second user is {user}") print(token) At the uidb64 = urlsafe_base64_encode(user.id) I get: AttributeError: 'ResetPasswordRequestSerializer' object has no attribute 'id' When I look at the output of various print(user) statements I have added all over: user: ResetPasswordRequestSerializer(<User: john>, context={'request': <rest_framework.request.Request: POST '/api/auth/reset_password/'>, 'format': None, 'view': <accounts.api.ResetPasswordRequesAPI object>}) Trying to understand why: # In serializer user = User.objects.get(email=data.get('email', '')) Is only giving the User without id and other fields. When I try to generate token for reset I get more AttributeErrors. -
Specifying view function in Django
I'm practicing in Django and I want to know how requests and view mechanisms work correct in Django. I started an app called ghcrawler in my django project. I designed like it has to send responses that recevied from localhost/ghcrawler and localhost/ghcrawler/results So this is the urls.py in ghcrawler/ app folder. from django.urls import path, include from .views import main_view, results_view urlpatterns = [ path('', main_view.as_view() , name='ghcrawler'), path('ghresults', results_view.as_view(), name='getresults') ] localhost/grcrawler page works well as expected. I just want to wire the requests coming to localhost/ghcrawler/results to getresults() function in results_view class defined in views.py, however it doesn't even write the 'h1' to the console ghcrawler/views.py: from django.views.generic import TemplateView from django.shortcuts import render from django import forms from django.http import HttpResponse from .github_requester import search_user class main_view(TemplateView): template_name = 'ghcrawler.html' # Handle the post request received from /ghcrawler/ def post(self, request, *args, **kwargs): if request.method == 'POST': user = search_user(request.POST.get("username", "")) if user == None: print("User not found.") else: print(user) return HttpResponse("OK") class results_view(TemplateView): template_name = 'ghresults.html' def getresults(self, request, *args, **kwargs): print('h1') -
Exception Type: OperationalError at /admin/firstapp/employee/ Exception Value: no such column: firstapp_employee.user_id
Hi i'm new to django & was trying to migrate my model when i received this error.Any suggestions? this is my models.py (i'm trying to create one to one relationship b/w user & Employee model) from django.db import models from django.contrib.auth.models import User # Create your models here. class Employee(models.Model): First_Name = models.CharField(max_length=200,blank=False,null=False) Last_Name = models.CharField(max_length=200) DOB = models.DateField() Primary_skill=models.TextField(max_length=1000) user = models.OneToOneField(User,on_delete=models.CASCADE,default='') def __str__(self): return self.First_Name -
Call django context_processor without request as normal function
I have a model and when I create a new record it must send a signal to the context_processor to display a popup in the Django admin site telling the user that there is a new record in that model that has been created. -
How to change the value stored in name based on previous input from user in html?
Good day. I am building a website using python django. I am trying to change a value in a table in the database containing student marks based on the student number(row) and assignment name(column). I have a function in views.py that uses if else statements to change the value which works fine as long the name="A1" is fixed to A1 (in the html code below) or fixed to any other assignment name but I have multiple assignment names ranging from A1 to A6. I would would like to change the value of name based on what assignment the user selects the html code: <h1>Fill in student assignment marks below</h1> <form action= "" method="POST">{% csrf_token %} <input type="text" class="field" placeholder="student ID" name="student"> <label for="name">Choose an Assignment:</label> <select name="name" id="name"> <option value="A1">A1</option> <option value="A2">A2</option> <option value="A3">A3</option> <option value="A4">A4</option> <option value="A5">A5</option> <option value="A6">A6</option> </select> <input type="text" class="field" placeholder="percentage" name="A1"> <button type="submit" class="btn">save</button> </form> The following is the view.py function to update the table: def upload_A_marks(request): if request.method == 'POST': student = request.POST['student'] name = request.POST['name'] print(name) if name == 'A1': A1 = request.POST["A1"] new_Amark = MarksTable.objects.get(student=student) new_Amark.A1 = A1 new_Amark.save() if name == 'A2': A2 = request.POST["A2"] new_Amark = MarksTable.objects.get(student=student) new_Amark.A2 = A2 … -
Apache2 not redirecting non-www request to www
I am trying to redirect my all non-www requests to www. Here is my apache config setting. RewriteEngine on RewriteCond %{SERVER_NAME} =example.com [OR] RewriteCond %{SERVER_NAME} =www.example.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] -
whenever i click on add more button only first data is storing into database [closed]
<input type="text" name="quantity" id="quantity" placeholder="QUANTITY"> <!-- <label for="phone">phone</label><br> --> <!-- <input type="text" name="phone" id="quantity-type" style="width:180px;"> --> <select name="quantity_type" id="quantityType"> <option value="kg">Kg</option> <option value="ton">Ton</option> <option value="peices">No's</option> </select> </div> <div> <select name="brand_name" id="brand_name" class="brand_name" onChange="check(this);"> <option value="Shyam Steel Industries Ltd.">Shyam Steel Industries Ltd.</option> <option value="JSW ( Jindal South West ) Steel Ltd.">JSW ( Jindal South West ) Steel Ltd.</option> <option value="Tata Steel Ltd.">Tata Steel Ltd.</option> <option value="Steel Authority of India (SAIL)">Steel Authority of India (SAIL)</option> <option value="Essar Steel Ltd.">Essar Steel Ltd.</option> <option value="Jindal Steel and Power Ltd.">Jindal Steel and Power Ltd.</option> <option value="VISA Steel">VISA Steel</option> <option value="SRMB Steel">SRMB Steel</option> <option value="Electro Steel">Electro Steel</option> <option value="MESCO Steel">MESCO Steel</option> <option value="Kamdhenu Steel">Kamdhenu Steel</option> <option value="Rathi">Rathi</option> <option>others</option> </select> <input id="other-div" name="brand_name" style="display:none;" placeholder="Enter Brand Name*"> <button class="addNewProd" id="addNewProd" type="button">+Add more</button> <div id="newProduct"></div> </div> </div> </div> enter image description here function addHtml(event) { console.log(event.target) let parentDiv = event.target.parentElement; console.log(parentDiv) count += 1; console.log(count) let html = `<div id="prodcount-${count}"> <select name="materials" id="prodVariety">{% for m in material_data %}<option value="{{m.variety_name}}">{{m.variety_name}}</option>{% endfor %}</select><br><input type="text" name="phone" id="quantity" placeholder="QUANTITY"><select name="quantity_type" id="quantityType" ><option value="ton">Ton</option><option value="cft">CFT</option><option value="kg">KG</option></select><br><select name="brand_name" id="brand_name" onChange="check2(this);"> <option value="Shyam Steel Industries Ltd.">Shyam Steel Industries Ltd.</option> <option value="JSW ( Jindal South West ) Steel Ltd.">JSW ( Jindal South West ) Steel Ltd.</option> … -
Des the django queryset annotation performs before slicing
I basically wanted to know, the order of execution for Django queryset actions annotation and slicing. Let Books is a model with around 1000 values in it. some_books = Books.objects.annotate( test_field=some-actions.... ).filter( some-other-filters )[:100] When I perform the above query, would the annotation of test_field will perform only for 100(sliced) objects or it will perform for all the objects matching with filters and then do the slicing? -
How to do SELECT UNNEST ARRAY on a list not stored in the db in django
I'm trying to reproduce this simplified Postgres query in Django (where [v1, v2, ...] is a python list): SELECT * FROM UNNEST(ARRAY[v1, v2, ...]) objs (obj) WHERE EXISTS( SELECT "table"."field1" FROM "table" WHERE "table"."field2" = 'value' AND "table"."field1" = fp ) But I cannot find a way to use UNNEST(ARRAY(... on something that is not a table. -
change attribute values of a django model object using a variable [duplicate]
I have this model : class Project(models.Model): name = models.CharField(max_length=200, verbose_name="project name", default="") price = models.FloatField(verbose_name="Price", default=0) description = models.TextField(verbose_name="Description du projet", blank=True, null=True) state = models.CharField(max_length=7, choices=STATES, verbose_name="Statut", default='not started') ...a lot of other fields... If I have this object : name : "test_project" price : 200 description : "this is a project" state : "not started" I can change any value like this : project.name = "new project" project.price = 300 project.description = "new description" project.state = "new state" project.save() But I want to know if it's possible to access attribute's values by replacing fields names with a variable (iterating through all the fields) It can look like something like this: new_values = ["new_name", 300, "new description", "new state"] fields = ["name", "price", "descrition", "state"] for i in range(len(new_values)): project.{fields[i]} = new_values[i] project.save() And know the object look like this : name : "new_name" price : 300 description : "new description" state : "new state" Does anyone know if there is a way to do this ? Thanks -
When I edit a profile, how do I make the system automatically send a confirmation email if the email is changed - Django
So... My main intention is that when a user edits his/her account and changes the email, the system has to change all the other info except email and send an email to the new email (inputted by the user) with a confirmation link. And once clicked, the system has to redirect the user to another page and change the email for that account. Please tell me how I can do this. my view: class NormalUserEditView(generic.UpdateView): form_class = EditProfileFormNormal template_name = 'authentication/edit_normalprofile.html' success_url = reverse_lazy('profile') def form_valid(self, form): messages.success(self.request, f'Account Edit: Successful') return super().form_valid(form) def get_object(self): return self.request.user For the email thing I was referring to this view: def register_user(request): if request.method == "POST": form = RegisterUserForm(request.POST) if form.is_valid(): myuser = User.objects.create_user( username=form.cleaned_data['username'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], password=form.cleaned_data['password1'], ) myuser.is_active = False myuser.save() # "Thank You For Registering" Email subject = "Welcome To some website" body = "Hello " + myuser.first_name + "!\n" + "Thank you for registering to some website. Your account has been registered. However, it has not been activated. We have sent you another email that contains a link. In order to activate your account you must click on that link. The email will be sent shortly. \nNOTE: If … -
How to correct the timezone django python
I have a date data that saved in my postgresql it looks like this I'm getting the date using this django models: ddate = list(MyModel.objects.values('created_at')) getDates = [d['created_at'] for d in ddate if 'created_at' in d] print(getDates) the print output will look like this which is, if I compared the time zone from postgres and time zone from my python they are not accurate. How can I fix this? my model.py looks like this: class MyModel(models.Model): created_at = models.DateTimeField(auto_now=True) class Meta: db_table = "tablename" -
Store Subtitles in a Database
I'm working on a project that uses AI to recognise the speech of an audio file. The output of this AI is a huge JSON object with tons of values. I'll remove some keys, and the final structure will look as follows. { text: "<recognised text>", language: "<detected language>" segments: [ {startTimestamp: "00:00:00", endTimestamp: "00:00:10", text: "<some text>"}, {startTimestamp: "00:00:10", endTimestamp: "00:00:17", text: "<some text>"}, {startTimestamp: "00:00:17", endTimestamp: "00:00:26", text: "<some text>"}, { ... }, { ... } ] } Now, I wish to store this new trimmed object in a SQL database because I wish to be able to edit it manually. I'll create a React application to edit segments, delete segments, etc. Additionally, I want to add this feature to the React application, where the information will be saved every 5 seconds using an AJAX call. Now, I don't understand how I should store this object in the SQL database. Initially, I thought I would store the whole object as a string in a database. Whenever some change is made to the object, I'll send a JSON object from the React application, the backend will sanitize it and then replace the old stringified object in the database with … -
How to subclass or patch the query when user is being populated by AuthenticationMiddleware
I have extended the Django default AbstractUser by creating this Visitor model that has more information on user. class Visitor(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='visitor') By looking at the wonderful Django Debug Toolbar, I noticed that both the User model and this Visitor model cause a database query on every request. That go me thinking that it might worth while to put .select_related("visitor") in the query that gets the User model. By following the rabbit hole starting from AuthenticationMiddleware, I was able to deduce that user model is fetched in django.contrib.auth.backends.ModelBackend.get_user(). I manually edited the file in my environment to include the .select_related("visitor") and it worked like a charm. Obviously editing package files in environment is not optimal. So the question now becomes: how would I proceed to subclass, patch or otherwise accomplish this in a clean manner? Using Django 3.2.12 with Python 3.10 btw -
Django : How to check a list of values is exists in a table or not in a single query in django?
user entered category = [1,2,3,............] for catId in categoryIds: if Category.objects.filter(id = catId).exist(): -------------- ----single opertions like adding value in to dict.----- else: -------------- I need to avoid unnecassary iteration by checking it in a single query. check the entered values is valid and then I can add to dict in a single step. how can I do it with django ORM ? -
Django Q objects vs python code better performance?
What would provide better performance using filtering conditions with Q in django ORM or simply fetching unfiltered objects and comparing in python. employee_qs = employee.objects.filter(state=States.ACTIVE, topic_assn__topic_id=instance.ss_topic_id).select_related('c_data').filter( Q(c_data__is_null=True) | Q(c_budget__gt=F('c_data__budget_spent') + offset_amt)) V/s employee_qs = employee.objects.filter(state=States.ACTIVE, topic_assn__topic_id=instance.ss_topic_id).select_related('c_data') for employee in employee_qs: if not employee.c_data or float(employee.budget)-employee.c_data.budget_spent > offset_amt: #do something... Which of these two choices would be better performance wise? -
Serializer class as property of Model class - is it bad practice?
I want to write a custom command that requires separate serializers for multiple Model classes. In order to make that iterable, I thought it might be a good idea to add a custom property to the Models involved. Following is a short example of what I envisioned, inside an app: # models.py from django.db import models class Foo(models.Model): # field properties, etc. command_serializer_class = FooCommandSerializer # serializers.py from rest_framework.serializers import ModelSerializer class FooCommandSerializer(ModelSerializer): class Meta: model = Foo # management/commands/foo_command.py from django.core.management.base import BaseCommand class FooCommand(BaseCommand): for model_class in [Foo, OtherModels]: qs = Foo.objects.all() # do things serializer = model_class.command_serializer_class(qs, many=True) print(f"Model has {len(serializer.data)} records.") At a first glance, it seems redundant to specify the Serializer to the Model, since it's a one-to-one association the other way around - as in, a Serializer must have one specific Model defined in the metaclass. However, I've found no way to list Serializers using a specific Model, so this seems to cleanest solution for me. Is it good practice, or can bite me in the long run? Is there any reason for me not to do it, or find another way to iterate through Models this way? -
Error: No file was submitted. Check the encoding type on the form
Please I’m having issue with register vendor, all was working fine before, so I just decided to retest everything have done, to my surprise the code thats working perfectly before is no more working. please help me out guys............................................................................................................................................................. views.py def registerRestaurant(request): # this restrict user from going to Vendor Registration Page after Logged in if request.user.is_authenticated: messages.warning(request, "You are already logged in!") return redirect('dashboard') if request.method == 'POST': form = UserForm(request.POST, request.FILES) v_form = vendorForm(request.POST, request.FILES or None) if form.is_valid() and v_form.is_valid(): password = form.cleaned_data['password'] # clean_data will return 'dict value' user = form.save(commit=False) user.set_password(password) user.role = User.VENDOR user.save() vendor = v_form.save(commit=False) vendor.user = user user_profile = UserProfile.objects.get(user=user) vendor.user_profile = user_profile vendor.save() mail_subject = 'Please Activate your Account' email_template = 'accounts/emails/account_verification_email.html' send_verification_email(request, user, mail_subject, email_template) #send_verification_email is function created in utils.py messages.success(request, "Your Account has been Registered Successfully, Please Wait for Approval") return redirect('registervendor') else: messages.error(request, 'An Error occurred during registration!') else: form = UserForm() v_form = vendorForm() context = { 'form': form, 'v_form': v_form, } return render(request, 'vendor/registervendor.html', context) model.py (vendor) class Vendor(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) user_profile = models.OneToOneField(UserProfile, related_name='userprofile', on_delete=models.CASCADE) vendor_name = models.CharField(max_length=50) vendor_lincense = models.ImageField(upload_to='vendor/lincense') is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now_add=True) … -
Django: how to do a group by on a field that is an indexed varchar?
I have a model Product like this: class Product(models.Model): manufacturer = models.CharField(max_length=32, null=True, blank=True) product_model = models.CharField(max_length=32, null=True, blank=True) description = models.CharField(max_length=32, null=True, blank=True) The field manufacturer is not a primary key, but it's an index. I would like to do a query that group all the products by manufacturer. Something like: Product.objects.all().group_by(manufacturer). (This is for use in Django Rest Framework where I have to return an array of manufacturer and for each manufacturer, an array of all the Product's of the manufacturer). How would yo do? -
AttributeError: module 'django.contrib.gis.db.models' has no attribute 'JSONField'
I'm using a Postgis database for my Django Project which has a field of JSONField in its database. When I run it, I get this error AttributeError: module 'django.contrib.gis.db.models' has no attribute 'JSONField' How to solve this issue?