Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template rendering error after website deploy
my website is about eccommerce activity. As I have deployed the site I am getting several errors. For example I can enter to log in or register user , I got errors like customuser does not exist. But I clearly have a models like below and it was working fine before deploying. class CustomUser(AbstractUser): is_customer = models.BooleanField(default=False) is_merchant = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) Another significant error I got in my customer home file template which says: relation "projectapp_product" does not exist The error occuring in store.html: {% extends 'customertemplates/main.html' %} {% load static %} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.product_name}}</strong></h6> <h4 style="display: inline-block;"><strong>${{product.discount_price}}</strong></h4> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart"><i class='fa fa-shopping-cart yellow-color'></i> Add to Cart</button> {% if user.is_authenticated and user.is_customer %} <button style="width:110px" class="btn btn-outline-secondary add-btn add-wishlist" data-product="{{product.id}}" data-action="add"><i class="fa fa-heart"></i> Wishlist</button> {% endif %} <a class="btn btn-outline-success" href="{% url 'product_details' product.pk %}"><i class="fa fa-eye"></i> View</a> </div> </div> {% endfor %} </div> {% endblock content %} store.views.py: def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products':products, … -
Bad Request 400 Django Heroku
I have made everything to upload my application on heroku I fade yp Collectstatic fine Allowed Host OK installed gunicorn ,whitenoise The project is uploaded on github Kind Regards -
TypeError at /email/ getaddrinfo() argument 1 must be string or None
i was trying to send message to candidate using Gmail as smtp, when i click send button im seeing the above error............................................................................................................................................................................................ views.py def email(request): if request.method == 'POST': # save message to DB to_db = Email( status = request.POST.get('status'), name = request.POST.get('name'), email = request.POST.get('email'), message = request.POST.get('message'), subject = request.POST.get('subject'), ) to_db.save() #Send email form = EmailForm(request.POST) company = "TT Software Solutions" if form.is_valid(): email = form.cleaned_data["email"] subject = form.cleaned_data["subject"] message = form.cleaned_data["message"] mail = EmailMessage(subject, message, company, [email]) mail.send() messages.success(request, 'Email sent successfully') return redirect('candidates') else: form = EmailForm() return render(request, {'form':form}) models.py class Email(models.Model): # Hidden name = models.CharField(max_length=50) email = models.EmailField(max_length=50) status = models.CharField(max_length=50) # Non Hidden subject = models.CharField(max_length=50) message = models.TextField() def __str__(self): return self.name template <form class="was-validated" action="{% url 'email' %}" method="post"> {% csrf_token %} <div class="modal-body"> <strong>To: <span class="text-primary">{{ candidate.first_name }} {{ candidate.last_name }}</span></strong> <hr> <!-- Hiden Inputs --> <input type="hidden" name="name" value="{{ candidate.first_name }} {{ candidate.last_name }}"> <input type="hidden" name="email" value="{{ candidate.email }}"> <input type="hidden" name="status" value="{{ candidate.Situation }}"> <!-- Non Hiden Input --> <input type="text" name="subject" class="form-control mb-2" placeholder="Subject" required> <textarea name="message" class="form-control" rows="8" placeholder="Message to candidate..." required></textarea> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary w-100"> <i class="fas fa-paper-plane"></i>&nbsp;&nbsp; … -
In pycharm previous django project`s server still runs after opening and running another project
I found the answer here PyCharm Django previous project`s server still runs after opening and running another project which works for me but I want to find a permanent solution. Can anyone suggest a solution? -
Django making an efficient way to loop transactions and categories to reduce datebase calls
response.json potentially contains thousands and thousands of items. I have would like to limit the number of times the database is queried. I'm aware a QuerySet can be constructed, filtered, sliced, and generally passed around without hitting the database. No database activity occurs until you do something to evaluate the queryset. In the code below, I rarely have to create a new category if one does not already exist, but the code "appears' to query the database on every item in the response.json loop due to categories.objects.getorcreate line: categories = Category.objects.all() __new_transactions = [] for item in response.json: category = categories.objects.getorcreate(code=item['category_code']) transaction = Transaction( category=category ) __new_transactions.append(transaction) # Save the transactions to the database in bulk. Transaction.objects.bulk_create(__new_transactions) Can I make the above more efficient? My initial idea was to check if the transaction category is in the categories list. However, that is a large list (5000 items) on this line item['category'] in categories categories = Category.objects.all() __new_transactions = [] for item in response.json: # check if the transaction category is in the categories list if item['category'] in categories: category=categories.get(code=item['category']) else: Category.objects.create(code=item['category'], name=item['category']) category = categories.objects.getorcreate(code=item['category_code']) transaction = Transaction( category=category ) __new_transactions.append(transaction) # Save the transactions to the database in bulk. … -
Best method to authenticate users in Django and React
I am building an application in Django for the backend and React for the frontend. Both are hosted in different domains so my way to authenticate users was to use a token which will then be saved on localStorage. However, upon reading more about it, storing the token this way is not so secure. Many recommend cookies but from what I understand they need to be on the same domain for this to work. What is the best thing to do in this case and the most secure? -
Django comment(s) on users in database
I'm currently building a Django website where staff has control over users, and, within those powers, I'd like to add one where the staff members can add private comments on users so that they can be read by whoever has the power to do so. So I started building the user models.py here what I did: class user(models.Model): name = models.CharField(max_length=30) comments = models.TextField() date = models.DateField(default=datetime.now()) def __str__(self): return self.name My question: how can I add a comment field every time a staff member wants to? Like, with the above code, I can only have one comment per user. Everything is appreciated. Thanks! -
Link form in Vue component to Django model
I have a template/html form inside one of my Vue components. How do I link this to my django model? I know how to do this in the case of linking a form made using django's built in forms, but I am not after that, I wish to link my vue form to my django backend. -
Django uvicorn root-path analogue
I work on some project, which uses microservice architecture. I have one Django monolith and several FastAPI microservices, which comunicate with main monolith app (splitting main app to microservices in progress, but now I still need to all this architecture works). I use traefik to route my services, so main app has /core prefix. I have a problem with in-django routing: my custom urls works okey, but built-in django admin urls work not good, because they try to redirect me not on /core/admin/some-url, but on /admin/some-url - they know nothing about my traefik prefix. In my FastAPI apps there are no problems with prefixes. I use uvicorn and they use --root-path /my-prefix-for-this-app setting in uvicorn run command, and I have no redirects inside these apps (probably, in future there will be a problem with redirection, but now I have no). So, my question is the following: "Do Django has any settings or logic to change base prefix to all redirections or maybe gunicorn has (I did not find any) setting to make it change base root url on django start via wsgi or maybe there is some other method to make my django app redirect urls right way? ". If … -
Forbidden: / 403 error while sending image from react to django using axios
I have a reactjs project that makes requests using API to django-rest-framework. I am trying to create an image field in reactJS that sends image to django server on submitting. Maybe the error is with csrf token or maybe not. I am a newbie. Please help. If possible please help me with the correct code. Thankyou veru much Image.js import React, { useState} from 'react'; axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'; axios.defaults.xsrfCookieName = 'csrftoken'; export default function Image() { const[images,setImages]=useState(null); function handleImages(e){ setImages(e.target.files[0]) } function handleSubmit(evemt){ const formData= new FormData(); formData.append('images',images) axios.post('http://127.0.0.1:8000/',formData,{ headers:{ "Content-Type": "multipart/form-data" }} ).then((res)=>{ console.log(res) } ) } return ( <div> <input type="file" name="images" accept="image/*" onChange={handleImages}/> <button onClick={handleSubmit}>Upload</button> </div> ) } views.py from rest_framework.parsers import FileUploadParser from rest_framework import viewsets from .serializers import RentDetailsSerializer from firstapp.models import RentDetails from rest_framework.parsers import MultiPartParser, FormParser class RentDetailsViewSet(viewsets.ModelViewSet): serializer_class=RentDetailsSerializer queryset=RentDetails.objects.all(); parser_classes = [MultiPartParser, FormParser] serializers.py from rest_framework import serializers from firstapp.models import RentDetails class RentDetailsSerializer(serializers.ModelSerializer): images=serializers.ImageField(required=False) class Meta: model = RentDetails fields = ['floor_no','distance','location','area','no_of_rooms','price','property_type','images'] settings.py REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser' ] } # REST_FRAMEWORK = { # 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.TokenAuthentication', # ) # } # CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] … -
Django table - Displaying floats
I am currently configuring a better readable FlaotColumn class NumberColumn(tables.Column): def render(self, value): if isinstance(value, float) and abs(value) != 0: dec = decimal.Decimal(value) rounded_val = round(dec, 6) return rounded_val else: return value So this is the current state. As you can see, when the value comes in I am checking if the value is not 0 and has the correct dtype. Now lets say one value is: -0.0977443609022557169385692077412386424839496612548828125 and the other one is: 0.00000000012312312312312321232356787686 How can I gurantee that both values are displayed in a verbose way without saying that values with f.ex. 6 decimal places are returned? Thanks for any suggestions here! -
Django's Admin list_display won't show correct Boolean Icon when using pre_save signal or in a model's custom save() unless saving the model twice
I have a Product model, and in the models.py I use a pre_save signal to update the product's all_variations_active field. For some unknown reasons, this all_variations_active field won't be updated with the correct Boolean value in list_display for admin unless the product gets saved twice. Below is the example code that I have issues with: pre_save signal part in models.py: @receiver(models.signals.pre_save, sender=Product, dispatch_uid='product_pre_save_unique_id') def product_pre_save(sender, instance, **kwargs): res = Variation.objects.filter(product=instance) active_list = [] for i in res: active_list.append(i.is_active) if sum(active_list) < 1 or False in active_list: instance.all_variations_active = False else: instance.all_variations_active = True In admin.py: class VariationInline(admin.TabularInline): model = Variation extra = 3 class ProductAdmin(admin.ModelAdmin): list_display = ( 'thumbnail', 'product_name', 'product_description', 'on_sale', 'price', 'stock', 'is_available', 'category', 'created_date', 'sku', 'all_variations_active') inlines = [VariationInline, ] Additional info: The model Variation(models.Model) has product model as a Foreignkey. Which looks like this: product = models.ForeignKey(Product, on_delete=models.CASCADE) So the gist is that when I go to the inline tabular tab for the variations of a product and change the select boxes - when saving the tabular tab does get saved correctly but in the admin's list_display it won't show the correct boolean status of the variations - because according to my code above if one … -
Django - Wagtail - Heroku: How to troubleshoot intermittent, seemingly random, HTTP 404s?
I'm serving Wagtail pages in a very well tested web app. No errors show up in development. When in Production (using Heroku and a hobby-tier Postgres db), those pages occasionally return an HTTP 404. If I refresh the browser a couple times, it goes back to serving the Page perfectly again. Some details: This happens with multiple pages; I get emails with the 404 error when this happens, so Django's BrokenLinkEmailsMiddleware is kicking in; Heroku web Dyno looks healthy based on its metrics; Heroku Postgres has no logs for the Hobby tier, so I don't know what's going on on the db side; Server is running behind a Cloudflare proxy server, but I can see the request hitting the origin and returning a 404. I'm obviously not expecting a solution here since the above info is insufficent for that. But I'm looking for troubleshooting pointers, for example: If the db has become under-dimensioned (too little RAM, too many simultaneous connections, etc.) - could that result in a Wagtail db query wrongly returning PageNotFound? Or would that return a 500 Server Error? How can I test DB error-handling locally with Django? How can I add a full Traceback for the Django … -
how to authenticate Angular and Django Rest Framework
I need to build an application where only logged in users can access a type of information using Angular in Front and Django Rest Framework in back. I just can't do this authentication, I tried and researched in every way, even using simple-jwt, I can't succeed. If anyone has been working on this, could you please help me or suggest me a site with a complete example. Here is my code bellow: settings.py # ALLOWED_HOSTS=['*'] # CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS=['localhost', '127.0.0.1'] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:4200', ) # JWT settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_HEADER_TYPES': ('Bearer',), } accounts/views.py class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = MyUser.objects.all() serializer_class = UserSerializer # renderer_classes = (UserJSONRenderer,) permission_classes = [permissions.IsAuthenticated] account/urls.py # app_name = 'accounts' router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] And from my Angular auth.service.ts import { HttpClient, HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { … -
why are only some css classes being generated in tailwind and others aren't?
I have a project where I'm using Django as backend and tailwind for the css. tailwind is not giving me any errors and is finding classes in my files but not generating the css. the only class that its working for is bg-blue-500 and nothing else. if anyone could think of why this may be happening or how to fix is I would really appreciate it. html page <ul class="nav"> <li class= "bg-red-500"> <a class="" href="{% url 'activeListings' %}">Active Listings</a> </li> {% if user.is_authenticated %} <li class=" bg-blue-500"> <a class="" href="{% url 'logout' %}">Log Out</a> </li> {% else %} <li class=""> <a class="" href="{% url 'login' %}">Log In</a> </li> <li class=""> <a class="" href="{% url 'register' %}">Register</a> </li> tailwind.css @tailwind base; @tailwind components; @tailwind utilities; @layer base { h1 { @apply text-4xl; } h2 { @apply text-3xl; } h3 { @apply text-2xl; } h4 { @apply text-xl; } } package.json { "name": "jstools", "version": "1.0.0", "description": "", "main": "tailwind.config.js", "scripts": { "build": "tailwind build -i ../auctions/tailwind.css -o ../auctions/output.css && cleancss -o ../auctions/output.min.css ../auctions/output.css" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "autoprefixer": "^10.4.12", "clean-css-cli": "^5.6.1", "tailwindcss": "^3.1.8" } } tailwind.config /** @type {import('tailwindcss').Config} */ module.exports = { future: { … -
django class view access response
in function view: def view(request): # do something with request response = render(request, 'view.html') # do something with response return response but now I have a View class: class ArticleDeleteView(View): pass # or even something more complicated class ArticleDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): pass which function shall I overwrite to access to the response? -
How i can cache SerializerMethodField result
I have a serializer: class OrderItemResponseSerializer(serializers.ModelSerializer): prepack_qty = serializers.SerializerMethodField() product_description = serializers.SerializerMethodField() class Meta: model = OrderItem fields = ( "product", "qty_ordered", "qty_approved", "status", "prepack_qty", "product_description" ) def get_prepack_qty(self, obj): return obj.product.prepack_quantity def get_product_description(self, obj): return obj.product.product_description When I make a get request to /orders, I make a lot of sql queries to the database because different orders may contain the same product. How i can cache result of get_prepack_qty and get_product_description methods? I tried to use @cached_property this way: class OrderItem(models.Model): ... @cached_property def item_product_description(self): return self.product.product_description but the number of requests to the database remained the same. -
Submitting a form from Vue component to POST data into django backend database
Where is the relationship between a form (found in a vue component) and a django backend meant to be defined? For my frontend, I am using VueJS, my main component is able to fetch data from json file using an api defined in my django view and url file. I do not understand how after filling in my Vue form, I may directly submit data to my django database. Tutorials online utlise django's built-in form related features; this, I am not after. -
Reverse for 'people' not found. 'people' is not a valid view function or pattern name
I got the error in my title when I tried to add a URL link so I can get to the person when I click on the URL. Beginner here so sorry if I am making silly mistakes. I am not sure where in my view function I messed up so any help is really appreciated views.py from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import People # Create your views here. class pplList(ListView): model = People context_object_name = 'people' class pplDetail(DetailView): model = People context_object_name ='cnd' template_name = 'base/people.html' people_list.html <h1>Interviewee Dashboard</h1> <table> <tr> <th> Item</th> <th> </th> </tr> {% for cnd in people %} <tr> <td>{{cnd.name}}</td> <td><a href="{% url 'people' cnd.id %}">View</a></td> </tr> {% empty %} <h3>No items in list</h3> {% endfor %} </table> models.py from unittest.util import _MAX_LENGTH from django.db import models from django.contrib.auth.models import User # Create your models here. status_choices = ( ("Choose", "Choose"), ("Resume Submitted","Resume Submitted"), ("Resume Reviewed", "Resume Reviewed"), ("Interview Scheduled","Interview Scheduled" ), ("Interview Completed","Interview Completed" ), ) wl = ( ("Choose", "Choose"), ("Accepted", "Accepted"), ("Rejected", "Rejected"), ) class People(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200) age = models.IntegerField(null=True, blank=True) address = models.TextField(null=True, … -
Reporting data entries in the project
In the project I use Django and PostgreSql, there is data entry every day. I want to receive the data of that day at the time I set myself, convert it into pdf and send it as an e-mail. Is there something automatic to do this all the time or what kind of script or query should I write? In other words, I want to do a reporting process on a daily basis, but I want to ensure that it is done automatically. -
How to host a django project on a hostinger vps?
I have a django project. I want to host it on a vps. I saw a few vps services and liked the hostinger vps.I want to host it to that vps. But the problem is, I am using django celery.I am also using django channels(WebSocket). It means,you know, I'm using asgi. And I want to use apache server with it. Can I know how to deploy this project on a vps? -
Django REST: Authentication credentials were not provided
There are similar questions like this on StackOverflow which didn't solve my problem. I'm using Postman to test my APIs. For some reason, my token authorization is not working and it's showing the following message, "detail": "Authentication credentials were not provided." My settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } These are my installed apps: ... 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'dj_rest_auth', 'dj_rest_auth.registration', ... I spent some hours to find the problem but failed. Can anyone please help me with where might the problem be? -
Context data not passing to Django templates
My cart view. I have passed context on return but it doesn't appear on the templates. If i print the def cart(request): total = 0 quantity = 0 cart_items = None tax = None grand_total = None try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, is_active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quality) quantity = cart_item.quality tax = (total / 100) * 2 grand_total = total + tax except: pass context = { 'total': total, 'quantity': quantity, 'cart_items': cart_items, 'tax': tax, 'grand_total': grand_total, } return render(request, 'c.html', context) Html Template. Here I created a for loop to get items from the array. But It doesn't show any objects from the array. But always print "Item" string for each object. {% extends 'base.html' %} {% load static %} {% block content %} {% extends 'base.html' %} {% load static %} {% block content %} {% for item in cart_items %} item.product.product_name {% endfor %} {% endblock %} {% endblock %} -
Symmetric django model
I want to create a model, which is symmetric on two fields. Let's call the model Balance: class Balance (models.Model): payer = models.ForeignKey(auth.User, ...) payee = models.ForeignKey(auth.User, ...) amount = models.DecimalField(...) It should have the following property: balance_forward = Balance.objects.get(payer=USER_1, payee=USER_2) balance_backward = Balance.objects.get(payer=USER_2, payee=USER_1) balance_forward.amount == -1 * balance_backward.amount What is the best way to implement this? -
How to Filter out Django Models
How do I create a lesson in a course without it showing in another course. I have a foreign key which is the course and it is under the models Lesson. I want to only view the lesson that is created under the certain course. But my problem is when I create a lesson in course 1, the lesson also shows in course 2. (sorry for bad english) views.py from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView from courses.forms import AddCourseForm, AddSectionForm, AddLessonForm from courses.models import Course, Section, Lesson def coursepage(request): courses = Course.objects.all() if request.user.is_authenticated: return render(request, "courses/courses.html", {'courses': courses}) else: return redirect('loginpage') def addcourse(request): if request.method == "POST": form = AddCourseForm(request.POST) if form.is_valid(): form.save() return render(request, "courses/successcourse.html", {'form1': form}) form = AddCourseForm() return render(request, "courses/addcourse.html", {'form': form}) def updatecourse(request, id): course = Course.objects.get(id=id) context = { 'course': course } return render(request, 'courses/editcoursehtml', context) def updatecourserecord(request, id): course = Course.objects.get(id=id) form = AddCourseForm(request.POST, instance=course) if form.is_valid(): form.save() return redirect("coursepage") return render(request, 'courses/editcourse.html', {'course':course}) def deletecourse(request, id): course = Course.objects.get(id=id) course.delete() return redirect("coursepage") class CourseDetailView(DetailView): queryset = Course.objects.all() template_name = "courses/detail.html" def sectionspage(request): section = Section.objects.all() if request.user.is_authenticated: return render(request, "sections/sections.html", {'sections': section}) else: return redirect('loginpage') def addsections(request): …