Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to achieve deleting or updating model that doesn't effect previously created object
I have three models Product, Order, and OrderItem Once someone places an order I don't want the product object associated with the orderitem model on the receipt to change or get deleted if I were to delete or update the product model. How to achieve this? #model class Product(models.Model): price = models.DecimalField() class Order(models.Model): buyer = models.ForeignKey(Buyer, on_delete=models.SET_NULL) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL) order = models.ForeignKey(Order, on_delete=models.SET_NULL) #view @login_required def receipt(request): orderitems = OrderItem.objects.filter(order__buyer__user=request.user) -
Django, Should the attribute name of the model (or form) and the name of the input tag be exactly the same?
If the user at the front-end has an additional function on the form, how do I control it in views.py? And how can I send form to HTML from views.py? Ex <form> <input type="text" class=".." name='input_1'> <input type"button" onclick="add_input()"> </form> -
Email backend for django application not working
I tried to use the usual way of having my gmail account send user activation email to used but it keep failing. Please is there any new changes made to Django or Gmail that is preventing this and how do I work around it. Please see below for the error detail: raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials s2-20020a05620a29c200b006af0ce13499sm6006618qkp.115 - gsmtp') -
Django Field 'id' expected a number but got datetime.datetime error
I am working on a Django-Tenant (Multi-Tenant) application. I am writing the script to create the subdomain. I am getting this error Field 'id' expected a number but got datetime.datetime error and I am unable to tell where it is coming from. views.py class CreatePortal(View): def get(self, request): form = CreatePortalForm() return render(request, "registration/create_portal.html", {"form": form}) def post(self, request): form = CreatePortalForm(request.POST) if form.is_valid(): getDomain = form.cleaned_data.get('name') instance = form.save(commit=False) user_id = request.user.id user = User.objects.get(id=user_id) tenant = Client(schema_name=getDomain, name=getDomain, created_by=user) tenant.save() domain = Domain() domain.domain = (getDomain + ".example.com:8000") domain.tenant = tenant domain.is_primary domain.save() with schema_context(tenant.schema_name): instance.save() redirect = 'http://' + form.cleaned_data['name'] + '.example.com:8000' return HttpResponseRedirect(redirect) return render(request, "registraton/create_portal.html", {"form": form}) forms.py class CreatePortalForm(forms.ModelForm): class Meta: model = Client fields = ["name"] models.py This is the line that I am working with models.py created_by = models.ForeignKey(User, on_delete=models.CASCADE) I have verified that I am getting the correct user id, but now I get this error. -
Django channels allows only one connection
I've created web socket between django and react app. I can establish connection only with one client. When i try to connect from other tab it gives me an error [Errno 61] Connect call failed ('127.0.0.1', 6379) and whole channels/ redis crushes. What i'm trying to do is send to all users the same number. Consumers.py import json from random import randrange from channels.generic.websocket import WebsocketConsumer from datetime import * import time class DiceConsumer(WebsocketConsumer): def connect(self, immediately=True): self.accept() while True: if datetime.now().strftime('%S') != '00': self.send( json.dumps({'action': "nothing", 'time': datetime.now().strftime('%S')})) elif datetime.now().strftime('%S') == '00': self.send(json.dumps( {'action': "start dice", 'winning_value': randrange(1, 6)})) time.sleep(1) Asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter from channels.auth import AuthMiddlewareStack from channels.routing import URLRouter from Dice.routing import ws_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Core.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns)) }) -
DoesNotExist at / Profile matching query does not exist in Django project
I am working in a Django project. I created user model, and views but suddenly it started giving me this error: raise self.model.DoesNotExist( core.models.Profile.DoesNotExist: Profile matching query does not exist. [31/Jul/2022 00:57:01] "GET / HTTP/1.1" 500 72187 This is the error from local host page: DoesNotExist at / Profile matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.6 Exception Type: DoesNotExist Exception Value: Profile matching query does not exist. Exception Location: /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/query.py, line 496, in get Python Executable: /Library/Frameworks/Python.framework/Versions/3.10/bin/python3 Python Version: 3.10.5 Python Path: ['/Users/slau8405/Desktop/work_space/work_space/django-social-media-website', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages'] Server time: Sun, 31 Jul 2022 00:57:01 +0000 I couldn't get rid of this error. Can I get some help ? My code looks like this: models.py from django.db import models from django.contrib.auth import get_user_model import uuid from datetime import datetime User = get_user_model() # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blank-profile-picture.png') location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.http import HttpResponse from django.contrib.auth.decorators import login_required from .models import Profile, Post, LikePost, FollowersCount from itertools import … -
Django pass user id before form is submitted
I am working on a Django-Tenant (Multi-Tenant) application. I am writing the script to create the subdomain. I am trying to get it to where created_by is set to the current users id that is logged in. How can I get current user ID to populate the created_by field? views.py class CreatePortal(View): def get(self, request): form = CreatePortalForm() return render(request, "registration/create_portal.html", {"form": form}) def post(self, request): form = CreatePortalForm(request.POST) if form.is_valid(): getDomain = form.cleaned_data.get('name') instance = form.save(commit=False) tenant = Client(schema_name=getDomain, name=getDomain, created_by=**[NEED USER ID HERE]**) tenant.save() domain = Domain() domain.domain = (getDomain + ".example.com:8000") domain.tenant = tenant domain.is_primary domain.save() with schema_context(tenant.schema_name): instance.save() redirect = 'http://' + getDomain + '.example.com:8000' return HttpResponseRedirect(redirect) return render(request, "registraton/create_portal.html", {"form": form}) forms.py class CreatePortalForm(forms.ModelForm): class Meta: model = Client fields = ["name"] models.py This is the line that I am working with models.py created_by = models.ForeignKey(User, on_delete=models.CASCADE) I also get an error if it is not User type and if I do not pass an actual number for id, Field 'id' expected a number but got datetime.datetime I have tried this as well: user = request.user.id tenant = Client(schema_name=getDomain, name=getDomain, created_by=user) but then get this error: Cannot assign "1": "Client.created_by" must be a "User" instance. … -
Uploading a django project to a github repo
I am relatively new to github and I am still trying to take my django application into production using a github repository. The problem is that for some reason, github has refused to commit a certain folder to the main branch. When I try to commit the changes I get the following message: On branch main Untracked files: (use "git add ..." to include in what will be committed) blog/ nothing added to commit but untracked files present (use "git add" to track) So I assume its telling me that there are some untracked files within the blog folder but when I try to add the folder, I get the following error: warning: adding embedded git repository: blog hint: You've added another git repository inside your current repository. hint: Clones of the outer repository will not contain the contents of hint: the embedded repository and will not know how to obtain it. hint: If you meant to add a submodule, use: hint: hint: git submodule add blog hint: hint: If you added this path by mistake, you can remove it from the hint: index with: hint: hint: git rm --cached blog hint: hint: See "git help submodule" for more information. … -
How can i insert a serial number for the following query in Django?
Info: I want to a serial number to come along with all objects in queryset using Django rest framework instead of object ID. The example image is below. the serial start from first object in queryset list. serializers.py class LiveStreamSerializer(serializers.ModelSerializer): def get_serial(self, obj): return LiveStream.objects.count() serial = serializers.SerializerMethodField('get_serial') class Meta: model = LiveStream fields = ['id', 'channel', 'live_stream_id', 'serial', 'stream'] -
How can I Display Link in List when User is found in another Django Model
I have a search box with a list of users with a hyperlink for approving applications. I want to show Approved on the link on any user whose application is already approved and Approve link on not approved application. I have tried putting the hyperlink in a for loop with a conditional statement to do the check but the Approve button is displaying twice on those users whose application not Approved while on the those Approved Application, the Approve and Approved links are displayed. someone should gracefully help as I am Django beginner so I finding it difficult to go from here. Any better way of achieving the same thing would be much appreciated. Thanks Models code: class Fee(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) email = models.CharField(max_length=30, null=True) phone = models.CharField(max_length=20, null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Payments: {self.applicant}' class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) def __str__(self): return f'{self.applicant.username}-Profile' views code: def search_applicants(request): #Set an Empty Dict of Context context = {} #Search Applicant Form searchForm = SearchApplicantForm(request.GET or None) payments = Fee.objects.all() if searchForm.is_valid(): #Value of search form value = searchForm.cleaned_data['value'] … -
Why are my div and form elements being shoved outside my table?
Django Template Code: Chrome Inspect Element: -
Live Data Django
I am looking for help to make a Django application dynamic, that is, I would like that when I add articles via the Django admin panel, they must automatically exit on the frontend of the application, without reloading the page. Many sources I have found (both Ajax and Websocket) make me continually update the div I am going to work on. How can I solve if I don't want to adopt this solution? -
fetch a specific item in database into Django template if it's certain type
I've been trying to use if statement in Django template to check if the type is equals to something in my database I used this code for the if statement {% if product.type == 'tshirt'%} <strong>{{product.name}}</strong> <span>{{product.price}}IQD</span> {% endif %} but it doesn't seem to work also my back-end has no problem it can handle and load products from the database into the html template very well but the if statement is what i'm struggling with and it doesn't seem to work like that I just want to render the product into the template if it's a certain type. Thanks for helping! -
Django access array with forloop.counter in template
I have an array ['one', 'two', 'three'] In my django template i want to access to elements of the array like that: {% for a in array %} {{ array.loop.counter}} {% endif %} But array.loop.counter return nothing. There is a way to access the element of the array based on the loop counter of my for ? -
How to show the user the error when submitting a Django form?
I have created a Django form that creates a user through a custom user model, but if the form is invalid, the form disappears and leaves the button on the screen. I am trying to display the errors through field.errors. <form method="post"> {% csrf_token %} {% for field in registration_form %} <h5>{{ field.label_tag }} {{ field }} {% if field.help_text %} <span>{{ field.help_text }}</span> {% endif %} {% for error in field.errors %} <p>{{ error }}</p> {% endfor %} </h5> {% endfor %} <button type="submit">Join</button> </form> Does anyone know what is wrong with the error part? (The form works; it just does not show any errors if it is not vallid.) -
Django how to conditionally update a field value based on other field related by foreign key?
I have a Test model which has several skillareas in it (each test can have sevral skillarea: one to many) and each skillarea has several queastions in it (each skillarea can have several questions: many to many) I want to write an update serializer for test , but the field "type" in the Test model can be changed only if there is no question registered in skillarea of this test. how can i set this condithon for updating ? MODELS.PY : class Test(BaseModel): company = models.ForeignKey( 'company.Company', on_delete=models.PROTECT, related_name='tests', null=True, blank=True, ) types = models.ManyToManyField( TestType, related_name='tests', ) title = models.CharField(max_length=255) summary = models.TextField() def __str__(self): return self.title class SkillArea(BaseModel): title = models.CharField(max_length=255) test = models.ForeignKey('Test', on_delete=models.PROTECT, related_name='skill_areas') questions = models.ManyToManyField( 'assessment.Question', related_name='skill_areas', ) def __str__(self): return self.title class Question(BaseModel): question_text = models.TextField() def get_absolute_url(self): self.get_type_display() def __str__(self): return truncatewords(self.question_text, 7) class TestType(BaseModel): title = models.CharField(max_length=255) def __str__(self): return self.title the serializer i wrote is bellow, but i dont know how to make condition for updating the type field based on having no question registered in related skillarea serializer.py : class TestAPIViewSerializer(serializers.ModelSerializer): class Meta: model = Test fields = ( 'id', 'level', 'language', 'types', 'title', 'summary', 'relevant_for', 'expectations', 'status', 'duration', … -
is this is the right way to use prefetch_related?
i have these models class Theme(models.Model): name = models.charfield() class Category(models.Model): name = models.charfield() class Product(models.Model): name = models.charfield() ......... class MstProduct(Product): category = models.ForeignField(Category, related_name = 'category_products') themes = models.ManyToManyField(Theme, related_name='theme_products') ......... i want to fetch categories and there related products by Category.objects.prefetch_related('category_products').select_related('category_products__themes') is this is the right way to do this? -
Error on installing crispy python library with wheels in python:3.10.5-alpine docker image
Ahoi I tried to create an docker image from a Docker file of my djanog application. In the dockerfile i first use a builder to install the libraries from the requirements.txt file with wheel. When installing the crispy library it raises a ModuleNotFoundError: No module named 'silx'. The silx library is also in the requirements.txt file but is getting installed later. I also tried to put the silx entry in the requirements.txt before the crispy lib, but the error is getting raised anyway. Here is the error when i try to build the image: docker command to build the image: docker build . --progress=plain Collecting crispy==0.7.3 Downloading crispy-0.7.3.tar.gz (409 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 409.6/409.6 KB 106.5 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [12 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-wheel-9r0etvcg/crispy_5ce9bef2b34f47b19aabc37ccd7cfab8/setup.py", line 149, in <module> main() File "/tmp/pip-wheel-9r0etvcg/crispy_5ce9bef2b34f47b19aabc37ccd7cfab8/setup.py", line 77, in main version=get_version(), File "/tmp/pip-wheel-9r0etvcg/crispy_5ce9bef2b34f47b19aabc37ccd7cfab8/setup.py", line 53, in get_version from crispy import version File "/tmp/pip-wheel-9r0etvcg/crispy_5ce9bef2b34f47b19aabc37ccd7cfab8/crispy/__init__.py", line 3, in <module> from silx.resources import register_resource_directory ModuleNotFoundError: No … -
Django: Why is one template url working but the other isn't?
Essentially, my index.html postlist works great, and on the link to the post detail view it works correctly. However I copied the same code to my Profile view with only the posts of the request.user. It works without the {%url 'post_detail' post.slug %} as the rest of the paginated posts render as expected. However with this url, it throws this error: NoReverseMatch at /blog_app/profile/ Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/$'] The code in the views and templates are essentially identical, why does this not work? Views.py: (the working one) class PostList(generic.ListView): model = Post queryset = Post.objects.filter(status=1).order_by("-created_on") template_name = "index.html" paginate_by = 6 (the not working one) class Profile(generic.ListView): model = Post template_name = "profile.html" paginate_by = 6 def get_queryset(self): return Post.objects.filter(author=self.request.user) urls.py: urlpatterns = [ path('', views.PostList.as_view(), name="home"), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'), path('poll/<slug:slug>', views.PostPoll.as_view(), name='post_poll'), path('blog_app/create_post/', views.CreatePost.as_view(), name='create_post'), path('blog_app/profile/', views.Profile.as_view(), name='profile'), ] My two templates: (working one) {% for post in post_list %} <div class="col-md-4"> <div class="card mb-4"> <div class="card-body"> <div class="image-container"> {% if "placeholder" in post.featured_image.url %} <img class="card-img-top" src="https://codeinstitute.s3.amazonaws.com/fullstack/blog/default.jpg"> {% else %} <img class="card-img-top" src=" {{ post.featured_image.url }}"> {% endif %} <div class="image-flash"> <p class="author">Author: {{ post.author }}</p> </div> … -
Django: order elements of a form field
I have two models named Quiz and Course class Quiz(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='quizzes',) and class Course(models.Model): name = models.CharField(max_length=30) I'm using quiz model in a createview. class newQuiz(CreateView): model = Quiz template_name = 'teacher/new_quiz.html' fields = ['name', 'course', ] course field is shown as an choice field in the form how can i order the course choices in ascending order while showing in the form -
Using placeholder tags in non-django CMS pages
In the Django CMS there's the {% placeholder 'content' %}. I tried to use it on a non-django-cms page, i.e., a detail-view page that comes from an apphook. However, when I switch to the structure view in the detail-view page and the placeholder does not seem to reflect. Is that's how it's supposed to work or is there a problem with my code? If it's how it's supposed to work is there a way to make placeholder appear in the page? -
Django templateview not recognizing my template_name
Currently I have in settings set my main directory to the templates folder so that I have a project level templates. Within that folder I have a home.html file. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is my views.py file from django.views.generic import TemplateView class HomePageView(TemplateView): template_name: "home.html" Whenever I runserver I receive this error: ImproperlyConfigured at / TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()' I'm following a book to the T (Django for Beginners) and i'm unsure why this error could be happening. Has the syntax for template_name changed? I've checked all the documentations and my name seems to be okay. I've also tried to input the pathname to the file instead. Any help would be wonderful. Thank you -
How to get local-memory cache in Django Templates?
I set local-memory cache, then I tried to get it to display in the Django Template "index.html" as shown below: # "index.html" {{ cache.get.success }} But, it displayed nothing so are there any ways to get local-memory cache in Django Templates? -
Django: cleaned_data for special characters and punctuation marks
I want to validate the Name field in my form. Now I have in my forms: def clean_name(self): name = self.cleaned_data['name'] if re.search(r'\d', name): raise ValidationError('The name must not have numbers') if re.search(r'\s', name): raise ValidationError('The name must not have spaces') return name But I also want to create validation for special characters and punctuation marks. I have tried some ways with [[:punct:]], but this returns an error to me, and I guess that this doesn't work with Python or another way of using it is needed. Is there any way to do this, I need help. -
How to save all data collected from a multi step form in the database with Django
I'm attempting to construct a multi-step form, but I'm having trouble saving all the form's data. When I click submit, I can only save the Investment ID which is the input field on the first step. The remaining ones don't save to the database. Any ideas as to what I'm not understanding? I don't want to use Django form tools. views from django.shortcuts import render, reverse from django.http import HttpResponseRedirect from .models import Withdraw def create_withdraw(request): if request.method != 'POST': return HttpResponseRedirect(reverse('investment:withdraw')) else: investment_id = request.POST.get('investment_id') front_id = request.FILES.get('front_id') back_id = request.FILES.get('back_id') id_no = request.POST.get('id_no') proof_of_address = request.FILES.get('proof_of_address') user_pic = request.FILES.get('user_pic') try: withdraw = Withdraw.objects.create( investment_id=investment_id, front_id=front_id, back_id=back_id, id_no=id_no, proof_of_address=proof_of_address, user_pic=user_pic ) withdraw.save() messages.success(request, 'withdrawal request submitted successfully') return HttpResponseRedirect(reverse('investment:withdraw')) except: messages.success(request, 'request failed! Try again') return HttpResponseRedirect(reverse('investment:withdraw')) model from django.db import models class Withdraw(models.Model): investment_id = models.CharField(max_length=20, null=True) front_id = models.ImageField(upload_to="user_doc", null=True, blank=True) back_id = models.ImageField(upload_to="user_doc", null=True, blank=True) id_no = models.CharField(max_length=20, null=True, blank=True) proof_of_address = models.FileField(upload_to="users_doc", null=True, blank=True) user_pic = models.ImageField(upload_to="user_doc", null=True, blank=True) created_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.investment_id template {% extends 'base2.html' %} {% load static %} {% block content %} <!-- MultiStep Form --> <div class="flex justify-center md:w-1/2 mx-auto"> <form id="msform" action="{% url 'investment:create-withdraw' …