Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django update related objects on save using signals
I am coming across an issue that I cannot figure it out. I have created a simple multi step form to help the user to create a Project. A brief explanation: Project is the main model ProjectDetails add information to the Project. There can be 'n' ProjectDetails to one Project. Every details include a Trade that is a ForeignKey of ProjectDetails. There can be only one Trade for every ProjectDetail class Trade(models.Model): ... shipped_quantity = models.IntegerField(default=0) status = models.IntegerField( choices=Status.choices, default=Status.CREATED ) class Project(models.Model): ... quantity = models.IntegerField(default=0) status = models.IntegerField( choices=Status.choices, default=Status.INIT ) class ProjectDetail(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, default='', blank=True, null=True, related_name='details') trade = models.ForeignKey(Trade, on_delete=models.SET_NULL, default='', blank=True, null=True, related_name='project') quantity = models.IntegerField() Once the user complete the last step and finalize the creation of the Project, I would like to update some related fields: a) adding up all the Trades quantity and update the Project Quantity b) update for each Trade the shipped_quantity c) update status of each Trade Here it is my view.py code: def project_create_complete(request, *args, **kwargs): # Final step to complete the project creation # update the status to SAVED and delete the session if request.POST: project = Project.objects.get(id=request.POST['project_id']) if project.status < Project.Status.SAVED: project.status … -
How To: For...Else in a Django template (if/else inside a for loop)
I apologize in advance if this has already been asked, but I couldn't find any answers that answered the problem I'm having: I need to do something similar to a For...Else loop in a Django template. I need to show a button on a template base on an if condition: If the user has already bought this product, then show button 1 If the user has not bought this product, then show button 2 For each product, I have to go through the user's purchases, and then show one button or the other depending on whether they have already bought the product or not. A simplified (and wrong) version of the code would be like: {% for product in products %} //other code here {% for purchase in purchases %} {% if purchase.service_id.id == product.id %} // show button 1 {% else %} // show button 2 {% endif %} {% endfor %} {% endfor %} However, this code doesn't work, as it shows both buttons as it goes through the for loop. I can't do a For...Empty because the user may have other purchases (so the for loop wouldn't be empty), but none of them coincide with this product. … -
Django Rest Framework Filtering does not response 'No Data Found' when no data found
I have a very simple DRF ListApiView which is using filters.SearchFilter as filter_backend. But the problem is it is returning an empty list if no data is found on the queryset. My Code: serializers.py class PhoneSerializer(serializers.ModelSerializer): brand_name = serializers.CharField(source='brand') class Meta: model = models.Phone fields = '__all__' views.py class PhoneApiView(generics.ListAPIView): filter_backends = [filters.SearchFilter] serializer_class = serializers.PhoneSerializer queryset = models.Phone.objects.all() search_fields = ['model_name', 'jan_code'] Result for a successful search [ { "id": 6, "brand_name": "Oppo", "model_name": "Oppo Reno 5", "image": "http://127.0.0.1:8000/media/phone/reno-5-black-2.jpg", "colors": "Red, Blue", "jan_code": "785621716768184", "brand": 6 } ] Expected Result if nothing found (Currently returning an empty list []) { "response": 'No Data Found' } Now, How do I do that? Thanks -
Get latest record in Django from two tables by comparing the date
I have two models - New User Request and Existing User Request which contain exactly the same fields class new_user_request(models.Model): request_id = models.AutoField(primary_key=True) emp_id = models.CharField(max_length=70) request_date = models.DateTimeField(auto_now_add=True) expiration_date = models.CharField(max_length=15, blank=True, null=True) class existing_user_request(models.Model): request_id = models.AutoField(primary_key=True) emp_id = models.CharField(max_length=70) request_date = models.DateTimeField(auto_now_add=True) expiration_date = models.CharField(max_length=15, blank=True, null=True) My task is to send notification mails to employees starting from 3 days before their access expires. I need help in getting the records of employees based on the following conditions: If record exists in existing_user_request get the records whose expiry is in the next three days. If record does not exist in existing_user_request, get the records from new_user_request where the expiry date is in the next three days. If there is a django way of doing this please let me know, if not please help me with the sql query so that I could run this as a cron job. -
name 'cache' is not defined django
class CourseListView(TemplateResponseMixin, View): model = Course template_name = 'eschool/course/list.html' def get(self, request, subject=None): subjects = cache.get('all_subjects') if not subjects: subjects = Subject.objects.annotate(total_courses=Count('courses')) cache.set('all_subjects', subjects) all_courses = Course.objects.annotate(total_modules=Count('modules')) if subject: subject = get_object_or_404(Subject, slug=subject) key = f'subject_{subject.id}_courses' courses = cache.get(key) if not courses: courses = all_courses.filter(subject=subject) cache.set(key, courses) else: courses = cache.get('all_courses') if not courses: courses = all_courses cache.set('all_courses', courses) return self.render_to_response({ 'subjects': subjects, 'subject': subject, 'courses': courses }) -
how users in a plateform made with django can voice call each others
hello in my plateform I want the users to call each others , like this scenario A : call B , B : receive a call from A. maybe this time B : call C C : receive a call from B and so on what do you suggest me, to make it work -
Django Raw Query does not Output
views.py def dashboard(request): employee = Employee.objects.count() position = Position.objects.raw('SELECT employee.stat, count(position.position_id) as NO FROM employee, position WHERE employee.id = position.employee_id AND position.position_id="1" GROUP BY employee.stat') context = { 'employee ': employee , 'position': position, } return render(request, 'dashboard/dashboard.html', context) I can output the employee count by using {{employee}} but when I use {{position}} the position output is "RawQuerySet". This is the output in MariaDb using the raw query. employee.stat NO 1 100 2 20 3 30 How can I output all the value of each employee.stat in the dashboard.html? Also can I output each employee.stat NO seperately? -
How to add image for image field for a model instance in django admin panel on heroku?
I added a few books on heroku data. Every model is displayed on heroku app site. My models have the field "image". I add these images from my PC folder and when I open this app after 2-3 hours the book images dissapear. I think it's because I turn off a PC, where I took these images. How do I have to do it correctly that these images don't dissapear? -
'NoneType' object has no attribute 'negate'
I'm getting the error when trying to get all the Urls for which the limited field is True. I've tried deleting the migrations and creating new migrations, but still getting the same error. these are the installed dependencies: asgiref==3.4.1 backports.zoneinfo==0.2.1 Django==4.0 django-cors-headers==3.10.1 django-shell-plus==1.1.7 djangorestframework==3.13.1 djongo==1.3.6 dnspython==2.1.0 gunicorn==20.1.0 pymongo==3.12.1 python-dotenv==0.19.2 pytz==2021.3 sqlparse==0.2.4 tzdata==2021.5 models.py: class Urls(models.Model): _id = models.ObjectIdField() record_id = models.IntegerField(unique=True) hash = models.CharField(unique=True, max_length=1000) long_url = models.URLField() created_at = models.DateField(auto_now_add=True) expires_in = models.DurationField(default=timedelta(days=365*3)) expires_on = models.DateField(null=True, blank=True) limited = models.BooleanField() exhausted = models.BooleanField() query: Urls.objects.filter(limited=False) error: Traceback (most recent call last): File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 116, in __init__ super().__init__(*args) File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 152, in parse self.where = WhereConverter(self, statement) File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/converters.py", line 27, in __init__ self.parse() File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/converters.py", line 119, in parse self.op = WhereOp( File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 476, in __init__ self.evaluate() File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 465, in evaluate op.evaluate() File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 258, in evaluate self.rhs.negate() AttributeError: 'NoneType' object has no attribute 'negate' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/cursor.py", line 51, … -
MultipleObjectsReturned at /course/eyime/user_library/
I am building a website where users can buy courses and the courses will display on their users library, a site similar to gumroad, but i am getting this error when i clicked on the payment option on my code. Here is the error messages i am getting MultipleObjectsReturned at /course/eyime/user_library/ get() returned more than one UserLibrary -- it returned 2! here is the Views.py codes @login_required def user_library(request, username): user = get_object_or_404(User, username=username) my_library = UserLibrary.objects.filter(user=user) if request.method == 'POST': course_id = request.POST['course_id'] course_price = request.POST['course_price'] course = UserLibrary.objects.get(courses__id=course_id) """for c in course.courses.all(): print(c.name)""" context = { 'course': course, 'course_price': course_price, 'email': request.user.email, 'phone': request.user.phone_number, } return render(request, 'courses/content/pay_for_courses.html', context) return render(request, 'courses/content/user_library.html', {'my_library': my_library}) here is the html codes for payment of the courses {% extends "jtalks/base.html" %} {% load static %} {% block title %}Payment With Paystack{% endblock %} {% block content %} <div class='container' onload="payWithPaystack()"> <div class='row justify-content-md-center'> <div class='col-md-auto'> <div id="output"> </div> <div id="success"> </div> <div id="display_info" style="display: none"> <p>Click <a href="{% url 'courses:print_course_pdf' course.id %}" target="_blank">Here</a> to print receipt of your purchase</p> <p id="home">Go Back Home <a href="{% url 'jtalks:jtalks-home' %}">Homepage</a></p> </div> </div> </div> </div> {% endblock content %} {% block js %} <script … -
Django on Heroku continues to process an old worker request on repeat?
I finally set up RQ on Django, and for some reason the worker dyno continues to run on repeat with old values I was testing. As soon as the job results return, it once again starts. I tried FLUSHALL with redis, I tried stopping my front end app engine, I tried restarting and redeploying my Django app on Heroku, but the only thing that seems to temporarily work is turning off the worker dyno until I turn it back on. My current add on list is Heroku Postgress, Heroku Redis, and Heroku Redis To Go. I don't know why it continues to restart the worker queue with the same values, and no amount of fiddling is working. -
When I try to validate 'username' field in Django form with clean_method I get a NameError
Here is my forms.py file. I got a "NameError: name 'username' is not defined" on this row: def clean_username(self): trying to submit this form, but, AFAIK, there are nothing wrong with it. from .models import Blog from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.exception import ValidationError class PostForm(forms.ModelForm): class Meta: model = Blog fields = ('title', 'description',) class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30) first_name = forms.CharField(max_length=150) #, help_text='First Name') last_name = forms.CharField(max_length=150) #, help_text='Last Name') email = forms.EmailField(max_length=200, help_text='Required. Enter a valid email address') def clean_username(self): nom_de_guerre=self.cleaned_data['username'] if User.objects.filter(username=nom_de_guerre).exists(): raise forms.ValidationError('User with this name is already exists!') def clean_email(self): addresse_de_mail=self.cleaned_data['email'] if User.object.filter(email=addresse_de_mail).exists(): raise forms.ValidationError('User with this email is already exists!') class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2', ) ``` -
Is there a way to create a back button in Django that understands a tree structure?
I have a Django website that looks like this: The arrows represent hyperlinks that take you to the next page. All pages except the Main Page need a "Back" button. For Page A and Page B, the back button is pretty simple - it always takes you to the Main Page. For Page C however, there are 2 different ways to get to it (technically 3, if you count the back button on Page D), so it's no longer obvious where the back button should take you. The way it should work is this: If the user came from Page A to get to Page C, the Back button should take them back to Page A If the use came from Page B to get to Page C, the Back button should take them back to Page B If the user didn't come from either Page A or Page B to get to Page C (they could have just entered the URL of Page C into their browser), default to having the Back button take them to Page A This has been asked before, and none of the answers/suggestions make sense for anything other than the most basic scenario, where … -
TypeError: Planet() got an unexpected keyword argument 'name'
from django.db.models.fields import CharField # Create your models here. class Planet(models.Model): name: models.CharField(max_length=50) number: models.IntegerField() I used python shell to run: python manage.py shell from planet_universe.models import Planet large_jupiter = Planet(name="Jupiter1", number=1) I get the following error: TypeError: Planet() got an unexpected keyword argument 'name'. How do I correct this error? -
I'm trying to deploy django web app on heroku but i couldn't after deploy heroku shows first method not allowed then bad request
[here is project structure ][1] when I write Heroku local then enter terminal shows an error no procfile but here we can see above [1]: https://i.stack.imgur.com/d54wN.png -
How to use clickhouse in django project?
I have a Chat model that is stored in postgresql class Chat(StatusModel, MyTimeStampedModel): closed_at = MonitorField(monitor='status', when=['closed']) channel = models.ForeignKey(Channel, on_delete=models.PROTECT, null=True) I need to count the number of open and closed chats using clickhouse. How can I do this? -
How can show django auth-views URLs on swagger?
I set the Urls like belows. users>urls.py from django.urls import path from django.contrib.auth import views as auth_views from users import views .... path( "changePassword/", auth_views.PasswordResetView.as_view(), name="password_reset" ), # 비밀번호 변경 (링크 발송) path( "changePasswordDone/", auth_views.PasswordResetDoneView.as_view(), name="password_reset_done", ), # 비밀번호 변경(링크 선택 후 화면) path( "changePasswordConfirm/<uidb64>/<token>/", auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm", ), # 비밀번호 변경(사용자 전송 링크) path( "changePasswordComplete/", auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete", ), # 비밀번호 변경(사용자 새 비밀번호 입력 후) ] but the auth_views doesn't appear in the swagger like below images. I guess there is some problem in the settings.py.... but don't know the detail. config>settings.py # Rest_Framework JWT REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ( # 'rest_framework.permissions.IsAuthenticated', #401 에러 회피 "rest_framework.permissions.AllowAny", # 401 에러 회피 ), "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.BasicAuthentication', ), } could you help kindly please? -
can i let the field in the html to have a specific layout when this value is not the default values
i made some fields useing Django as models.CharField and set the default values to default="-" i also made the html tamplat to show the fields. so can i let the field in the html to have a specific layout or text effect when this value is not the default values default="-" modeks.py Iron_Fe = models.CharField(max_length=100, default="-", blank=True, null=True) Carbon_C = models.CharField(max_length=100, default="-", blank=True, null=True) html <td id="Fe" title="Iron"><sup>{{ object.Iron_Fe }}</sup>Fe</td> <td id="C" title="Carbon"><sup>{{ object.Carbon_C }}</sup>C</td> -
Django, looping inside a father-child tree
I am trying to loop over a father-child tree relationship were the child also can be a father and print it's children for the far being i'v only been able to print the primitive father and the children (but i cant figure out how to print the children's children) Here is the Model : class Component(models.Model): component_name = models.CharField(max_length=100) component_manufacturer = models.CharField(max_length=100) component_model = models.CharField(max_length=100) component_number = models.CharField(max_length=255) component_price = models.IntegerField() component_note = models.TextField() parent_component = models.ForeignKey("self", verbose_name=( "Parent Component"), blank=True, null=True, related_name='children', on_delete=models.CASCADE) is_child = models.BooleanField(default=False) def __str__(self): return f"{self.id}, {self.component_name}" the view : def index(request): f = Component.objects.all() context = { 'f': f } return render(request, 'maintenance/index.html', context) the template : <div class='component'> Components<ol> {%for f in f%} {%if f.is_child is False %} <li> {{f.component_name}}</li> <ol> {% for f in f.children.all %} <li> {{f.component_name}}</li> {%endfor%} </ol> {%endif%} {%endfor%} </ol> </div> Thanks plenty! -
Value errror don't mix args and kwargs
ValueError at /postsignin Don't mix *args and **kwargs in call to reverse()! Request Method: POST Request URL: http://127.0.0.1:8000/postsignin Django Version: 3.2.3 Exception Type: ValueError Exception Value: Don't mix *args and **kwargs in call to reverse()! Exception Location: C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\django\urls\resolvers.py, line 624, in _reverse_with_prefix Python Executable: C:\Users\ASUS\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.6 Python Path: ['S:\Work\Fortech', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39', 'C:\Users\ASUS\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\win32', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\win32\lib', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\Pythonwin'] Server time: Sat, 25 Dec 2021 14:45:40 +0000 Views def postSignIn(request): try: email = request.POST.get('email') password = request.POST.get('password') auth.sign_in_with_email_and_password(email, password) return redirect('/', request) except error: return redirect(reverse('signin', args=request, kwargs={'msg': 'id'})) urls urlpatterns = [ path('', views.index, name='index'), path('signin', views.signIn, kwargs={'msg': 'None'}, name='signin'), path('postsignin', views.postSignIn, name='postsignin'), ] -
Why does model not connect with user?
I have a model that appers in admin. But it doesn't connect with user automatically. I always have to specify user in admin. I have a form for creation. But when I create with this form it doesn't appear on the screen. Models class Notion(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='notions', null=True, blank=True) title = models.CharField(max_length=100) body = models.TextField() -
How to print many-to-many field
models.py: from django.db import models class Course(models.Model): course = models.TextField(blank=True) class Student(models.Model): first_name = models.TextField() last_name = models.TextField() course = models.ManyToManyField(Course) forms.py: from django import forms from .models import Student, Course class StudentForm(forms.ModelForm): class Meta: model = Student fields = ['first_name', 'last_name', 'course'] class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['course'] views.py: def students_view(request): if request.method == 'POST': students_form = StudentForm(request.POST) if students_form.is_valid(): students_form.save() print(Student.objects.all().values()) students_form = StudentForm() context = { 'form':students_form } return render(request, 'courses/courses.html', context) If I print print(Student.objects.all().values()) than I see student's ID, first_name and last_name. But I don't see in which groups they belong to. How to print that? -
(fields.E300) Field defines a relation with model 'Product', which is either not installed, or is abstract Django
I'm new in django, I faced with following error when I wanted to define two models which have foreignkey to each other . I searched about it and I find out this might happen when the models have been in two different apps, but my models are in one app . would you please help me about this . Thanks ERRORS: ?[31;1mstore.Collection.featured_product: (fields.E300) Field defines a relation with model 'Product', which is either not installed, or is abstract.?[0m class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null = True, related_name= '+') class Product(models.Model): title = models.CharField(max_length=255) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotion = models.ManyToManyField(Promotion) -
How to upload and deploy zip folder?
I want to upload and deploy the zip folder downloaded from repl.it to AWS eb, but it is difficult to find even if I google it.. -
Error10060 Time our when trying to send_mail with django
Here is my setting:(I'm pretty sure the password and user is correct, becauese if I intentionally input wrong password it will returen authenticationException but not time out) DEFAULT_FROM_EMAIL = 'xxxx' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'xxxx' EMAIL_HOST_PASSWORD = 'xxxxxxxx' I try this in python shell: send_mail('Test', 'This is a test', 'xxxx@gmail.com', ['xxxx@gmail.com'], fail_silently=False) It return timeout exception. plus:I'm using vpn, I think may be this is the culprit, but I don't know how to solve it, thanks for your help.