Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot integrate image in vue.js using django
Models has been shown and absolute url has been sent from here -
Django get request does not pass the tz_zone param
I have a client having an issue that the Django get request does not contain the tz_zone param. It seems to occur on some specific browsers. I guess it relates to the browser settings but have no way to reproduce it on my local. Is there anyone got the same issue and knows how to fix it? Thanks, Thanh Tran -
DRF: How to access "context" inside custom DecimalField class?
I am subclassing the DecimalField class from Django RestFramework and need to access context. Formatting for decimal fields includes settings that are user-selectable, so I need to access the user object (which, I assume, should be inside context) inside the to_representation() method. Via debug, I've looked at all properties of self inside my CustomDecimalField class, but, of course, I can't see class methods, so I don't know if there's an appropriate "get" method to get context. I've tried self.context (as a property), self.get_context(), and self.getcontext(), but none worked. I found this announcement re: require_context: https://www.django-rest-framework.org/community/3.11-announcement/ ...but it seems to be valid only for validation and default value methods. This seems like such a simple thing; hard to believe it is so difficult. -
Why would 15-20 minute website scrapes work at first but after a couple scrapes stop working?
By "stop working" I mean it has errors which stop the scrape. I'm thinking it's a sysadmin problem but I don't know what it is. The site is run at digital ocean on a python/django stack. I'm using selenium to scrape, python-rq for the task queue. I'm using nginx and gunicorn to run django. the rq worker has it's on .service as does the django app itself. Can anyone help? this is for a client so it's important -
submit form with multiple images
User are able to create posts via a model form. I am attempting to add a feature so once the post is created they can go on the post an and upload multiple images, but I am having some issues implementing it properly. forms.py class PostImagesForm(ModelForm): class Meta: model = PostImages fields = ('images',) widgets = { 'images': forms.ClearableFileInput(attrs={'multiple': True}), } When the user uploads an image I would receive the error 'PostImages' object is not iterable and only one image would get uploaded to the database views.py def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) formImages = PostImagesForm if request.method == 'POST': formImages = PostImagesForm(request.POST, request.FILES) if formImages.is_valid(): formImages = formImages.save(commit=False) formImages.post = Post.objects.get(pk=pk) formImages.save() else: print(formImages.errors) context = { 'post':post, 'formImages':formImages, } return render(request, 'blog/post_detail.html', context) html <div class="content-section"> <form method="post" enctype="multipart/form-data" novalidate> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Testing image upload</legend> {{ formImages|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> I figured the issue was because I was only having the form submit once and it needs to submit once for each image (I could be completely wrong) Where I am currently stuck is attempting to setup a loop. I figured the … -
Django Rest Framework - How to create a custom serializer for GoogleSheets
I have some data on a Google Sheet that I'd like to serialize. I've been working on using a Django server to create a REST API that makes it easy for other apps to use. My use case is that we have several different Google Sheet Documents with data about devices we want to serialize. Python has a lot of neat libraries, like SheetFu, that basically do what we want, so I'd like to integrate that functionality with a REST API to do things like search, filter, etc. I did find a Django app, django-gsheets that combined with the Django-Rest-Framework does almost what I want, but it looks like models are fixed to a single Google Sheet Document - I need to be able to work with, and add multiple documents. I can use SheetFu to write a serializer, but I'm not sure how to integrate that with Django, and it's REST framework - can anyone point me in the right direction for this? Thanks! -
Django after login failed page is not redirecting to next
If user do successfull login then it is redirecting to next but if user can not do login then I wants to change template and wants to redirect to next page but it is not working. Views.py if request.method == 'POST': if request.META['HTTP_REFERER'].split('/')[-1] == 'bs5': template_path = 'theme/bs5_theme.html' response = LoginView.as_view( template_name=template_path, redirect_field_name='next', form_class=EmailAuthenticationForm, )(request) login.html {% if form.non_field_errors %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> Login failed. Email and password case-sensitive. </div> {% endif %} <form id="formLogin" action="{% url 'login' %}" method="post" role="form"> <input type="hidden" name="csrfmiddlewaretoken"> <input type="hidden" name="next" value="/bs5" /> <label for="id_username" class="form-label">Email address</label> <input type="username" class="form-control" id="id_username" name="username" value="{{ form.username.value }}"> <label for="id_password" class="form-label">Password</label> <input type="password" class="form-control" id="id_password" name="password"> <button class="btn btn-primary btn-lg" type="submit">Log In</button> </form> I have also try with return HttpResponseRedirect('/bs5') But then it is not showing login error. Any help would be appreciated. -
TypeError: conversion from DecimalField to Decimal is not supported
I am building a bidding website using Django. I found a problem in the models.py. I cannot execute the shell command migrate and don't know why. Could anyone help on it? Thanks in advance. models.py is as below: class User(AbstractUser): pass def __str__(self): return f"{self.username}" class AuctionItem(models.Model): ''' Description of Auction Item ''' category_choices = [ ("Fa", "Fashion"), ("To", "Toys"), ("Fo", "Food"), ("El", "Electronics"), ("Ho", "Home") ] title = models.CharField(max_length=16) description = models.CharField(max_length=128) image = models.URLField() category = models.CharField(max_length=16, choices=category_choices) create_time = models.DateTimeField(auto_now_add=True) seller = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="owned") initial_price = models.DecimalField(max_digits=10, decimal_places=2, null=True) current_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, default=0) class BiddingPrice(models.Model): ''' Bidding price of each item ''' bid_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) bidder = models.ForeignKey(User, on_delete=models.CASCADE, null=True) auction_item = models.ForeignKey(AuctionItem, on_delete=models.CASCADE, null=True, related_name="bidding_price") class Comments(models.Model): ''' Comments made by different users ''' comments = models.CharField(max_length=200) commentor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="comments_given") connected_item = models.ManyToManyField(AuctionItem) The error message is: TypeError: conversion from DecimalField to Decimal is not supported -
Using fixtures in django.test.TestCase
I try to use fixtures in django.test.TestCase. It works correctly, but I do it for the first time. What is the best practice in this case? from django.test import Client, TestCase class SomeTestClass(TestCase): fixtures = ['fixtures.json',] @classmethod def setUpClass(cls): super().setUpClass() cls.user = User.objects.get(id=1) # from fixtures cls.authorized_client = Client() cls.authorized_client.force_login(cls.user) cls.someobject = Someclass.objects.get(id=1) # from fixtures cls.anotherobject = Anotherclass.objects.get(id=1) # from fixtures def test(self): ... -
Python Django Page loading issue
Why my Python Django WebApp always loads the same page but with different URLs ? I have templates for the requested url too . But Django loads only my home page . Why ? -
CSRF cookies not set - React, JWT, Django
I'm rather confused regarding the following error: "Forbidden (CSRF cookie not set.)". This error is received during attempting to logout, login, signup. The problem is similar to this post which was never answered: Django (DRF) & React - Forbidden (CSRF cookie not set) I used axios and JWT for handling authentication. I have two git branches to track this error. On the master branch I have the original authentication setup. It works just fine, no errors. On a second branch (we'll call it branch2), I get the error specified above. The only difference between the two branches is that I ran the cmd django-admin startapp books. I then proceeded to setup the model, serialization, views, and urls for the books app on branch2. I also added it to the settings.py installed apps. Other than that, nothing has changed. Therefore the authentication process should remain the same. React handles the looks of the website but the default django ip is used for development: http://127.0.0.1:8000/ I run npm run build in order to update react's current build. Book View (branch2) # Book Imports from .serializers import BookSerializer from .models import BookModel ##### Book API ##### # A Complete List of ALL Projects … -
Django image css
I can't get django to use my css file. I've done a lot of sifting through various sites and tutorials but with no luck. Most of them say to change your STATICFILES_DIRS while some don't mention it at all. I've tried changing it to about every variant that could match my style.css location as well as copying and pasting the css file into a bunch of locations which might match '/static' but nothing works! for STATICFILES_DIRS I have tried: os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'static/store'), os.path.join(BASE_DIR, 'staticfiles'), os.path.join(BASE_DIR, 'staticfiles/store'), I also found the file manually and copied the location into a string like so: '...Desktop/project/staticfiles/store', I have also tried similarly playing around with the STATIC_URL and STATIC_ROOT to no avail. My tree looks like this: project static store style.css staticfiles store style.css store static store style.css staticfiles store style.css and my template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> {% block head %} <link rel='stylesheet' type='text/css' href='{% static "store/style.css" %}'> {% endblock %} </head> <body> {% block body %} {% endblock %} </body> </html> I also tried changing static in the template to staticfiles I already wasted hours on this problem and am tired and frustrated, please help! -
Avoid repeating queries in several SerializeMethodFields using Django REST Framework
I'm trying to optimize database queries in my DRF app. To do that I'm trying to avoid repeating queries in my serializers. Supose I have a ModelSerializer like this: class BookSerializer(serializers.ModelSerializer): genres = serializers.SerializerMethodField(read_only=True) out_of_stock = serializers.SerializerMethodField(read_only=True) price = serializers.SerializerMethodField(read_only=True) class Meta: model = Recipe fields = ['id', 'title', 'genres', 'out_of_stock', 'price'] def get_genres(self, obj): # Complex query here ... location_id = self.context['request'].query_params.get('location', None qs = Book.objects.annotate(min_price=Min('price')).filter( (Q(supplier__location_id=location_id) | Q(supplier_id__isnull=True)) & Q(name__in=collection_names), min_price__lte=F('price')).order_by() genres_ids = qs.filter(is_out_of_stock=False).values_list('genres__id', flat=True) genres = Genre.objects.filter(id__in=genres_ids) return GenreSerializer(genres, many=True).data def get_is_out_of_stock(self, obj): # Same complex query here ... location_id = self.context['request'].query_params.get('location', None qs = Book.objects.annotate(min_price=Min('price')).filter( (Q(supplier__location_id=location_id) | Q(supplier_id__isnull=True)) & Q(out_of_stock=False) & Q(name__in=collection_names), min_price__lte=F('price')).order_by() return qs.filter(is_out_of_stock=True).exists() def get_price(self, obj): # Another same complex query here ... location_id = self.context['request'].query_params.get('location', None qs = Book.objects.annotate(min_price=Min('price')).filter( (Q(supplier__location_id=location_id) | Q(supplier_id__isnull=True)) & Q(out_of_stock=False) & Q(name__in=collection_names), min_price__lte=F('price')).order_by() ........ ........ return ...... As you can see I need to pass some query_params to filter the queryset. Do you know what could I do to avoid repeating each query to retrieve all the serializer fields? Thank you in advance. -
Creating simple like button
Hi im developping a blog app and i am creating a simple like button for the post idintified by it's pk where the link is located in a form but it ran into an error. NoReverseMatch at /single_post/8/ Reverse for 'like_post' not found. 'like_post' is not a valid view function or pattern name. my views.py for the detail view and the like button view def post_detail(request, pk): post = Post.objects.get(id=pk) context = { 'post': post, } return render(request, 'news/post_detail.html', context) def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return(HttpResponseRedirect(reverse('single_post', args=[str(pk)] ))) models.py class Post(models.Model): title = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to='img/', default='img/default.jpg') author = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) credit = models.URLField(blank=True, null=True) likes = models.ManyToManyField(User, related_name='daily_posts') def __str__(self): return self.title in the detail views the form and the link <form action="**{% url 'like_post' post.pk %}**" method="POST"> {% csrf_token %} <button class="btn btn-primary btn-sm" type="submit", name="post_id", value="{{ post.id }}">Like</button> </form> and the error i run to everytime i hit like. NoReverseMatch at /single_post/8/ Reverse for 'like_post' not found. 'like_post' is not a valid view function or pattern name. i cannot identify what seems to be the issue here anyone can help please? -
How to get the username of the current user and assign it to a certain field in a form in django?
This is my models.py file from django.db import models from django.contrib.auth.models import User # Create your models here. class Book(models.Model): category_choices =( #("Undefined","Undefined"), ("Action", "Action"), ("Romance", "Romance"), ("Horror", "Horror"), ("Comedy", "Comedy"), ("Adventure", "Adventure"), ("Dramatic", "Dramatic"), ("Crime","Crime"), ("Fantasy","Fantasy"), ) name = models.CharField(max_length=100) author = models.CharField(max_length=100, null=True) content = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) image = models.ImageField(upload_to= 'photos/%y/%m/%d', blank = True) category = models.CharField( max_length = 20, choices = category_choices, #default = 'Undefined' ) publication_year = models.CharField(max_length=4, null=True) ISBN = models.CharField(max_length=13, null=True, unique=True) active = models.BooleanField(default= True) def __str__(self): return self.name class Borrow(models.Model): name = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) book = models.OneToOneField(Book, null=True, on_delete= models.SET_NULL) period = models.PositiveIntegerField(default=0) id = models.IntegerField(primary_key=True) def __str__(self): return str(self.book) and this is my forms.py file from django import forms from .models import Borrow class BorrowForm(forms.ModelForm): class Meta: model = Borrow fields = ('name', 'book', 'period') and this is the function in my views.py file that renders the form @login_required def borrowing(request): momo = BorrowForm() if request.method == 'POST': momo = BorrowForm(request.POST) if momo.is_valid(): instacne = momo.save(commit=False) instacne.user = request.user.username instacne.save() return redirect('profile') return render(request, 'books/book.html', {'momo': momo}) The role of this function is to render that form and to save the data that user will enter and … -
User created from a custom serializer built for django default user model can't log in to django admin site
I have a serializer, which was built for Django's default model as defined below. However, users created cannot login to the admin site, even when I make the user a staff using the superuser. The error says "incorrect username and password". Is there anything I'm not doing right. I have the serializer,viewset and the url defined below. Any help will be much appreciated. # serializer.py class CreateUserSerializer(serializers.ModelSerializer): password1 = serializers.CharField( style={'input_type': 'password'}, write_only=True ) password2 = serializers.CharField( style={'input_type': 'password'}, write_only=True ) def validate(self, data): """Check if password1 and password2 are the same""" if data['password1'] != data['password2']: raise ValidationError('passwords do not match') try: """Check if valid password was provided""" validators.validate_password(data['password1']) except ValidationError as e: errors = list(e.messages) raise ValidationError(errors) return data class Meta: model = User fields = ( 'username', 'email', 'first_name', 'last_name', 'password1', 'password2', ) def save(self): """Create user and sets password""" password = self.validated_data['password1'] self.validated_data.pop('password1') self.validated_data.pop('password2') user = User.objects.create_user(**self.validated_data) user.is_active = False user.set_password(password) user.save() return user class UserViewSet(viewsets.ModelViewSet): queryset = Users.objects.all() def get_serializer_class(self): if self.action == 'create': return serializers.CreateUserSerializer return serializers.UserSerializer router = routers.DefaultRouter() router.register( 'users', views.UserViewSet, basename='user' ) urlpatterns = router.urls -
Displaying data from a specific page in django
I am creating a donation application that allows donors to donate stuff. I have a screen, called available supplies.html which renders out all of the donations from the database using a for loop. Each donation is displayed in a user-friendly way, and contains a button that allows them to see details about that specific donation. When the button is clicked, the user is redirected to a page, and on this page I want to render out detail about the donation they clicked on. For example if the user clicked on the donation titled Apple, it would bring up data from my model with details about that particular apple. Can someone please help me accomplish this? My code is down bellow. Donation Model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) HTML (this is where I want to render out the model data): {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="/availablesupplies/">&#x2190; Back</a> <br> <br> <table class="table"> <tr> <th><h5>Date Posted: <strong>Date</strong></h5></th> <th><h5>Donor:<strong> User</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="">Accept</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div class="cart-row"> <div style="flex:2"></div> … -
module parse failed: Unexpected token (10:11)
I'm new to programming and i'm following a tutorial (https://www.youtube.com/watch?v=YEmjBEDyVSY&t=589s) However, i keep getting the following error: ERROR in ./src/components/app.js 10:11 Module parse failed: Unexpected token (10:11) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | | render() { > return <h1>{this.props.name}</h1>; | } | } @ ./src/index.js 1:0-38 webpack 5.45.1 compiled with 1 error in 103 ms When i run: npm run dev App.JS import React, { Component } from "react"; import { render } from "react-dom"; export default class App extends Component { constructor(props) { super(props); } render() { return <h1>{this.props.name}</h1>; } } const appDiv = document.getElementById("app"); render(<App name='matt' />, appDiv); -
How to set max length on integerfield Django Rest
Okay so I need to have my field have a maximum of 10 integers allowed to be entered. I tried MaxValueValidator but i figured out that this just needs a value thats lower than the set value. I want to be able to enter a maximum of 10 numbers, so it should work if i enter just one number, but also if I enter 10. Code ex: class Random(models.Model): code=models.IntegerField -
Annotate + Distinct Not Implemented, Count a Distinct Subquery
I have two models, RetailLocation and Transaction, which share a one-to-many relationship respectively. I trying to annotate the total number of days (Count) a RetailLocation has any number of Transactions for. In doing so, I am filtering the Transaction.date field to just Date instead of Datetime, and trying to SELECT DISTINCT dates, but am running into an error "NotImplementedError: annotate() + distinct(fields) is not implemented." Models class RetailLocation(models.Model): name = models.CharField(max_length=200, null=True) class Transaction(models.Model): date = models.DateTimeField(null=True) r_loc = models.ForeignKey(RetailLocation, null=True, on_delete=models.SET_NULL) Attempted Code test = RetailLocation.objects.annotate( days_operating=Subquery( Transaction.objects.filter(r_loc=OuterRef("pk")) .distinct('date__date') .annotate(count=Count('pk')) .values('count') ) ) I tried to reference this solution in combination with an earlier post solved by Willem, but using distinct seems to cause the NotImplementedError referenced above. I believe there also might be a solution using Count( , distinct=True), but it wouldn't help unless I could distinct on date__date, as I am only trying to find days that any number of Transactions occurred on. Thank you very much for your time. -
Stop Celery caching Django template
I have Django 3.24, celery 4.4.7 and celerybeat 2.2.0 setup via the RabbitMQ broker. I have have a celery task that renders a Django template and then sends it to a number of email recipients. The Django template is dynamic in as much as changes can be made to it's content at any time, which in turn rewrites the template. The trouble is that on occasions, I have to restart celery to get it to re-read the template. My question is, is there any way of forcing celery to reread the template file, without requiring a full celery restart? celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backoffice.settings') app = Celery('backoffice') default_config = 'backoffice.celery_config' app.config_from_object(default_config) app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) celery_config.py from django.conf import settings broker_url = "amqp://someusername:somepassword@webserver:5672/backoffice" worker_send_task_event = False task_ignore_result = True task_time_limit = 60 task_soft_time_limit = 50 task_acks_late = True worker_prefetch_multiplier = 10 worker_cancel_long_running_tasks_on_connection_loss = True -
How to Improve IFrame Loading Speed?
I am working on a project for a client who is using Square booking and would like that embedded into their website. I have added an IFrame on the site which points to their booking page on Square's website, however this IFrame loads painfully slow. I am using Django templates for the front end of the website. Is there any way to make this IFrame load faster? Is there a way to load it in the background of the homepage so that it is cached when the user goes to the booking page? -
Issue with Django blog tutorial on youtube, class view and GET method not clear
Was following a youtube tut regarding a django blog but ran into an issue. Link to video: https://www.youtube.com/watch?v=CnaB4Nb0-R8&t=607s The tut says to use the following code in the blog app's view.py file: from django.views.generic. import ListView, DetailView from .models import Post from django.views import View class Blogview(ListView): model = Post template_name = 'blog.html' When I tried to implement the code this way, I was given an error referencing something to do with GET. Looking into it, I modified my code to look like the following: from django.shortcuts import render from .models import Post from django.views import View class Blogview(View): model = Post template_name = 'blog.html' def get(self, request): return render(request,'blog.html') The above version of code works now for me. I find it frustrating why I couldn't figure out why the youtube tutorial code seemed to be much simlified and worked just as expected, whereas when I tried it word for word it failed and had to include a reference to the get method. I'll let you know I did simplify my version of the template file 'blog.html' to be something as simple as a single line of text whereas the tutorial had a template file which took all the posts … -
(index):217 Uncaught TypeError: Cannot read property 'innerHTML' of null
receving error message. Ive tried everything i can think of and being a novice im at a loss. please help DisplayCart(cart); function DisplayCart(cart){ var cartString = ""; cartString += "<h5>This is your cart</h5>"; var cartIndex = 1; for(var x in cart){ cartString += cartIndex; cartString += document.getElementById("nm"+x).innerHTML + "QTY:" + cart[x]; cartIndex += 1; } -
Rendering django model data in html
I am creating a donation application that allows donors to donate stuff. I have a screen, called available supplies.html which renders out all of the donations from the database using a for loop. If someone wants the stuff in the donation, they can click on a view button and are redirected to a page that contains details about the donation. I am struggling with rendering these details out, because I need specific data. Is there any way I can do this? Basically, I want to display data for the donation the user clicked on. My code is down bellow. Donation Model: class Donation(models.Model): title = models.CharField(max_length=30) phonenumber = models.CharField(max_length=12) category = models.CharField(max_length=20) quantity = models.IntegerField(blank=True, null=True,) HTML (I want the donation data that the user clicked on to render here) {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="box-element"> <a class="btn btn-outline-dark" href="/availablesupplies/">&#x2190; Back</a> <br> <br> <table class="table"> <tr> <th><h5>Date Posted: <strong>Date</strong></h5></th> <th><h5>Donor:<strong> User</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="">Accept</a> </th> </tr> </table> </div> <br> <div class="box-element"> <div class="cart-row"> <div style="flex:2"></div> <div style="flex:2"><strong>Item</strong></div> <div style="flex:1"><strong>Category</strong></div> <div style="flex:1"><strong>Quantity</strong></div> </div> <div class="cart-row"> <div style="flex:2"><img class="row-image" src=""></div> <div style="flex:2"><p>Title</p></div> <div style="flex:1"><p>$20</p></div> <div style="flex:1"> …