Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django login required message is not displayed
I was trying to flash some message when user tries to access user profile page without loging in. But it is not displaying on log in page. @login_required def profile(request): if request.user.is_authenticated: if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success( request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } else: # if not request.user.is_authenticated messages.info( request, f'Your account has been created! You are now able to log in.') return redirect('login') return render(request, 'users/profile.html', context) -
Groupby and Count doesn't include users that have no posts (OneToMany relationship between two models)
I have two models, User and Post, where each user can have many posts. class User(models.Model): first_name = models.CharField("First name", max_length=150) last_name = models.CharField("Last name", max_length=150) class Post(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") content = models.CharField(max_length=300) Now for a sample data like this: User id first_name last_name 1 Jon Skeet 2 Gordon Linoff 3 Another Soul Post user content 1 Jon #1 1 Jon #2 1 Jon #3 2 Gordon #1 2 Gordon #2 I'm trying to create an API that returns a response like this: [ { "first_name": "Jon", "last_name": "Skeet", "posts_count": "3", "recent_posts": [ { "content": "Jon #1", "created": "2022-07-22T07:48:12.299032Z" }, { "content": "Jon #2", "created": "2022-07-22T07:47:26.830772Z" }, { "content": "Jon #3", "created": "2022-07-22T07:02:31.654366Z" } ] }, { "first_name": "Gordon", "last_name": "Linoff", "posts_count": "2", "recent_posts": [ { "content": "Gordon #1", "created": "2022-07-22T09:59:36.965825Z" }, { "content": "Gordon #2", "created": "2022-07-22T09:59:18.544077Z" }, ] }, { "first_name": "Another", "last_name": "Soul", "posts_count": "0", "recent_posts": [] } ] So for each user, I want to include these info in the result: The count of their posts Their top three most recent posts Here's what I've done so far. I created two serializers, one for each model: class UserSerializer(serializers.ModelSerializer): posts_count = … -
Reverse for 'blogpost' with arguments '('',)' not found
Reverse for 'blogpost' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P[0-9]+)\Z'] I face this problem in every project. So please any devloper solve this problem my urls.py from django.urls import path from .import views urlpatterns = [ path('', views.index, name='Blog_home'), path('<int:pk>', views.blogpost, name='blogpost'), ] my views.py from django.shortcuts import render from blog.models import Post # Create your views here. def index(request): post = Post.objects.all() context = {'post':post} return render(request, 'blog/bloghome.html', context) def blogpost(request, pk): blog_post = Post.objects.get(id=pk) context = {'blog_post':blog_post} return render(request, 'blog/blogpost.html', context) my models.py from django.db import models # Create your models here. class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) content = models.TextField() author = models.CharField(max_length=50) date_and_time = models.DateTimeField(blank=True) def __str__(self): return self.title Template: bloghome.html {% extends 'basic.html' %} {% block title %} Blog {% endblock title %} {% block blogactive %} active {% endblock blogactive %} {% block style %} .overlay-image{ position: absolute; height: auto; width: 100%; background-position: center; background-size: cover; opacity: 0.5; } {% endblock style %} {% block body %} <div class="container"> {% for post in post %} <div class="row"> <div class="col-md-7 py-4"> <div class="row g-0 border rounded overflow-hidden flex-md-row shadow-sm h-md-250 position-relative"> <!-- <div class="col-auto m-auto img-fluid"> <img src="#"> </div> --> <div … -
How can I display movies and TVs side by side?
I want to display Movies and TV side by side with django_bootsrap. Movies left side TVs right side. But I don't know how display Movies left side TVs right side. I display Movies and TVs by django's for. Below html code. I'm not still CSS. <h1>TV Score_by</h1> <div class="row"> {% for m in movie %} <div class="card" style="width: 18rem;"> <img src="https://image.tmdb.org/t/p/w200{{ m.poster_path }}" class="card-img-top" alt="..."> <div class="card-body"> {% if not m.name %} <h5 class="card-title">{{ m.title }}</h5> {% else %} <h5 class="card-title">{{ m.name }}</h5> {% endif %} <p class="card-text">{{ m.overview }}</p> <a href="/movie/{{ m.id }}/" class="btn btn-primary">View Details</a> </div> </div> {% endfor %} </div> <h1>TV Score_by</h1> <div class="row"> {% for m in tv %} <div class="card" style="width: 18rem;"> <img src="https://image.tmdb.org/t/p/w200{{ m.poster_path }}" class="card-img-top" alt="..."> <div class="card-body"> {% if not m.name %} <h5 class="card-title">{{ m.title }}</h5> {% else %} <h5 class="card-title">{{ m.name }}</h5> {% endif %} <p class="card-text">{{ m.overview }}</p> <a href="/tv/{{ m.id }}/" class="btn btn-primary">View Details</a> </div> </div> {% endfor %} </div> -
django.core.exceptions.FieldError: Unknown field(s) (field_name) specified for ModelName
As stated in my title I am getting error: django.core.exceptions.FieldError: Unknown field(s) (total_price) specified for CERequest In admin panel everything works fine and it is displayed correctly but when I am trying to open html page with my form I get this error. Can you please let me know how to fix this error and how can I pass the total_price method to my form. models.py class CostRequest(models.Model): related_component = models.ForeignKey(CostCalculator, on_delete=models.CASCADE, default=1, blank=True) related_product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='related_product_ce_request') number_of_units = models.IntegerField(default=0) @property def total_price(self): return self.related_component.rate.hourly_rate * self.number_of_units forms.py class CalculatorForm(forms.ModelForm): number_of_units = forms.IntegerField(min_value=0) class Meta: model = CERequest fields = ('related_product', 'related_component', 'number_of_units', 'total_price') # 'total_price here causes issues -
Creating a detailed plan for task execution (Android App Development)
My mentor has asked me to first prepare a very well detailed plan for task execution. My assigned task/project is to develop an android app using DjangoREST and React. The app will pull data from an API and notify users of events. How detailed is detailed and what are some of the things he expects to see in the document before he can authorize me to write a single line of code. I like the idea, its interesting but I am anxious to impress from the plan before he sees my pathetic code. Please help -
Django reply of comment function issue, have to reply all html form
It works when you enter a comment, but when i write reply of comment, there is an error that requires me to enter the form in all areas. I'm sorry I can't upload the code, so I'm taking a screenshot -
Manage User Data on Django HTML with passing data
I'm doing small example project by Django. I'm making a Blog. in views.py I could render index.html with posts by passing posts dictionary onto third argument of render function as below. def home(request): posts = post.objects.all() return render(request, 'index.html', {'posts':posts}) By doing this, I could use posts data on HTML as below {% for post in posts %} <a href="{% url 'detail' post.id %}"> <h3>{{ post.title }}</h3> <h4>{{ post.id }}</h4> </a> <p>{{ post.date }}</p> However, when my instructor taught me how to implement login/logout function, I discovered he didn't pass the user data but he could manage 'user' data on HTML as below {% if user.is_authenticated %} {{ user.username }}님 <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} def login(request): if request.method=='POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) return redirect('home') else: return render(request, 'login.html') else: return render(request, 'login.html') How is if user_is_authenticated could be rendered successfully on HTML without passing 'user' data on views.py? -
what are depended package for install WeasyPrint in dockerfile?
I install WeasyPrint and config it for views.py ,urls.py,admin.py and my template. when i want convert html page to pdf , i have this error : (process:7): Pango-CRITICAL **: 13:27:29.635: pango_font_get_hb_font: assertion 'PANGO_IS_FONT (font)' failed base_shop_web_1 exited with code 245 my Dockerfile is : FROM python:alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code ADD requirements.txt /code/ WORKDIR /code RUN apk add --update --no-cache curl jq py3-configobj py3-pip py3-setuptools python3 python3-dev RUN apk add cairo-dev pango-dev gdk-pixbuf-dev py-lxml shared-mime-info openjpeg-dev freetype-dev libpng-dev gettext libxml2-dev libxslt-dev RUN apk add make automake libffi-dev gcc linux-headers g++ py3-brotli musl-dev postgresql-dev zlib-dev jpeg-dev RUN pip3 install -r requirements.txt EXPOSE 8000 COPY . /code/ what things i shoud to add dockerfile ? -
Django - Form not showing in template
I'm trying to make a login with a bootstrap dropdown. The problem is my form isn't showing up. I tried different things, I watched if my settings were correct and for me everything is good. I think the problem comes from my view. <!-- navbar.html --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a href="#" class="navbar-brand">Park<b>AUTO</b></a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div id="navbarCollapse" class="collapse navbar-collapse justify-content-start"> <div class="navbar-nav"> <a href="#" class="nav-item nav-link">Home</a> <a href="#" class="nav-item nav-link">About</a> <a href="#" class="nav-item nav-link">Contact</a> </div> <div class="navbar-nav action-buttons ml-auto"> <a href="#" data-toggle="dropdown" class="nav-item nav-link dropdown-toggle mr-3">Login</a> <div class="dropdown-menu login-form"> <form action= {% url 'account:login' %} method="post"> {{ form.as_p }}{% csrf_token %} <input type="submit" class="btn btn-primary btn-block" value="Login"> </form> </div> <a href="#" class="btn btn-primary">Get Started</a> </div> </div> </nav> #views.py from django.shortcuts import redirect, render from django.contrib.auth.forms import AuthenticationForm # Create your views here. def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect("home:home") else: form = AuthenticationForm() return render(request, 'pages/home.html', {"form": form}) #urls.py from django.urls import path from .views import login app_name = 'account' urlpatterns = [ path('', login, name='login'), ] If someone could help me on that, it would be pretty nice. -
In a Django template, is it possible to send the whole variable document to a template tag?
If I render a template using this document: { "a": 1, "b": 2 } In Django templates, I can render html using the value of "a" like this: {{ a }} But is it possible to send the whole document to a template tag? ie, all this? { "a": 1, "b": 2 } So that my tag can access arbitrary elements? -
Unhandled Exception: type 'Null' is not a subtype of type 'int' in type cast
factory Account.fromJson(Map<String, dynamic> json) { return Account( json["id"], json["email"], json["description"], json["first_name"], json["last_name"], json["phone"], json["username"], json["image"], json["email_confirmed"], json["reviews_media"] != null ? double.parse(json["reviews_media"]) : (json["reviews_media"] as int).toDouble(), json["holiday_mode"], json["identity_code"], json["residency_city"], json["birthday"] != null ? DateFormat("yyyy-MM-dd").parse(json["birthday"]) : null); } -
How do I sort the movies according to their star ratings and filter the movies with lower rating than the specified threshold
I want to sort the movies according to their star ratings and filter the movies with lower rating than the specified threshold. I want to sort movie and TV information in descending order by stars, search by each ID, and display data.json format and socre. However, I get a'module' object does not support item assignment error. context ["movie"] = in movie_list class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_tv.objects.filter(tv_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars def Score_by(request): movies = Movie.objects.order_by('-stars') movie_list= [] if movies.exists(): for obj in movies: data = requests.get(f"https://api.themoviedb.org/3/movie/{obj.id}?api_key={TMDB_API_KEY}&language=en-US") movie_list.append(data.json()) context["movie"] = movie_list tv = TV.objects.order_by('-stars') tv_list = [] if tv.exists(): for obj in tv: data = requests.get(f"https://api.themoviedb.org/3/tv/{obj.id}?api_key={TMDB_API_KEY}&language=en-US") tv_list.append(data.json()) context["tv"] = tv_list return render(request, 'Movie/score_by.html', context) <div class="row"> … -
I am working on a djnago project and I am using django_bootstrap_icons, I have installed it using pip and done everything but they aren't showing
settings.py INSTALLED_APPS = [ ... 'myapp', 'django_bootstrap_icons', ] ... STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'static,'media') STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root') STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static','static_files') ) home.html ... {load static} <link rel="stylesheet" href="{% static 'bootstrap_icons/css/bootstrap_icons.css' %}"> ... {% load bootstrap_icons %} {% bs_icons 'alarm' %} Is there something I've done wrong. I installed the django bootstrap icons using pip and I even did the py manage.py collectstatic And still it's saying Icon does not exist However the icons appear if I connect to the Internet but since I've installed the django bootstrap icons, I want the icons to appear even when I'm offline because I don't have Internet access everytime... -
How to send mail (like noreply) with Django sendgrid
I am newbie! I want to create a django application that sends mail. it worked well on localhost, but when I deployed it, it stopped working because the host doesn't support smtp. He suggested using sendgrid, and I'm stuck here... enter image description here sorry i dont have permission to put pic only link views.py enter image description here error: enter image description here -
How to get multiple values from a model field into a form choice field?
I have a model called Listing that has a field called categories that stores all the different categories. There is also a form with a field called categories that should show a choice field to the user, where the choices should be the values stored in the Listing.categories model field. So I tried to loop through it but that is not possible as the choice field values are stored in a dict format. So how do I get the values from the model field into the choice field? models.py class Category(models.Model): name = models.CharField(max_length=50) class Listing(models.Model): ... category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True) forms.py: from .models import Listing # example of what I was trying to do condition_choices = ( (1, 'New'), (2, 'Refurbished'), (3, 'Opened'), (4, 'Used'), ) ### for i in Listing.category: category_choices = ( (i, Listing.category) ) class NewListing(forms.Form): ... category = forms.ChoiceField(choices=category_choices) -
Django queryset annotation returning grouped counts
I am using Django 3.2 models.py class AwardCategory(models.Model) name = models.CharField(max_length=16) slug = models.SlugField(max_length=16, unique=True, db_index=True) class Award(models.Model): name = models.CharField(max_length=16) category = models.ForeignField(AwardCategory, on_delete=models.CASCADE) class CeremonyAward(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="awards", on_delete=models.CASCADE ) award = models.ForeignKey(Award, related_name="ceremonies", on_delete=models.CASCADE ) I want to write a query that returns for a specified user (or list of user_ids): award_category: name number_of_awards_in_category I know I have to use annotations, but I'm quite new to annotations. This is what I have so far: user_ids = (someuser.id,) CeremonyAward.objects.filter(user_id__in=user_ids).\ annotate(Count('award__category__slug', distinct=True)).\ prefetch_related('award','award_category') How do I create a query that groups by award__category and then counts the awards in each distinct category -
Django - Is there a difference between auth.models.User and .model.User (abstract)?
I have to import the User model in a file and I was wondering if there is any difference between the auth.models.User and an abstract user in .models.User: from django.contrib.auth.models import User or from .models import User -
POST http://127.0.0.1:8000/add-to-cart 500 (Internal Server Error)
Hi so I'm working on a ecommerce website using Django and my add to cart button keeps throwing this error. So when i click it before i've logged in it does its job and displays a "Log in to continue" message on the screen but after i login and click the "add to cart" button again it throws the error. I'm new to Django and i've been following https://www.youtube.com/watch?v=3YKXhdOGR-s&list=PL_99hMDlL4d2zsGU5nOgADmRc6A8msXyh&index=12&ab_channel=SharmaCoder this video for reference. this is my js file This the view.py file This is the html file urls.py AND ERROR -
ModelForm including ForeignKeys with multiple databases
Having two models in models.py such as: provider_name = models.TextField(primary_key=True, default=None) provider_address = models.TextField(null=False, blank=False, default=None) class PhoneNumber(models.Model): number = models.IntegerField(primary_key=True, default=None) provider = models.ForeignKey(PhoneProvider, on_delete=models.SET_NULL, default=None, null=False, blank=False) And then in forms.py I create two model forms: class Meta: model = PhoneProvider fields = "__all__" class FormPhoneNumber(forms.ModelForm): class Meta: model = PhoneNumber fields = "__all__" My question is, how to use the FormPhoneNumber (which has a ForeignKey) when using multiple databases with manual routing. Do I need to overwrite the field employing a query employing .using('database_name')? I am aware that Django does not support cross-referencing of Foreign keys along multiple databases, but I am talking about two tables placed in the same database. How can I let the ModelForm now the database from which it can extract the foreign key options? -
django oscar order app abstract models customization
I want to override django-oscar Order class which Inheritance from AbstractOrder class (in order apps and abstract_models.py file) but when i try to use migrate & makemigrations commands it says that model there is a problem in register_model function and i have no idea how i can solve it (i need to use basket_total_incl_tax property and currency field does anyone know where can i find these two in other classes?) if anyone knows what the problem is and what should i do to solve it please tell me. thank you. -
Render label names instead of integer fields in Django templates
As part of my models, I have an IntergerField "choices". These choices have been labelled. (Label 1 = Straw, Label 2 = Yellow...) However, the HTML renders the integer rather than the actual labels. What do I need to do return the labels and not the field's interger? Is it somethng I need to do in views? Or do I address it directly in the html file? Code below: Models CHOICE1=( ('',''), (1,'Straw'), (2,'Yellow'), ) class Model1(models.Model): user = models.ForeignKey(User,blank=True,on_delete=models.CASCADE) Choice_A = models.IntegerField(choices=Choice1,default=0) Views def account(request): review_list = Model1.objects.all return render(request,"main/account.html", {'review_list':review_list}) HTML <h6>Champagnes</h6> {% for Model1 in review_list%} <table class="table table-hover table-striped table-bordered "> {% if Model1.user == user%} <tr> <th>Text</th><th>{{Model1.Choice_A }}</th> </tr> {%endif%} </table> {% endfor %} -
Celery results not updating after dockerization
I'm currently putting my Django app on Docker. I successfully dockerized Django, gunicorn, nginx and Celery, however when I run a Celery task, even though it's executed (displayed in the logs), the results are not stored to my database. That worked before dockerizing everything so that probably comes from my docker configurations, but I didn't manage to find which part was incorrect/incomplete. Also, I'm using the default sqlite3 Django database as I don't need to store a huge amount of data. Here is my docker-compose.yml: version: '3.8' services: django_gunicorn: volumes: - db:/db.sqlite3 - static:/static - media:/media env_file: - env build: context: . ports: - "8000:8000" command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000" nginx: build: ./nginx volumes: - static:/static - media:/media ports: - "80:80" depends_on: - django_gunicorn rabbitmq3: image: rabbitmq:3-alpine ports: - 5672:5672 celery: restart: always build: context: . command: celery -A main worker -P eventlet -c 100 -l INFO env_file: - env depends_on: - rabbitmq3 - django_gunicorn volumes: - db:/db.sqlite3 volumes: db: static: media: Dockerfile FROM python:3.10.5-alpine ENV PYTHONUNBEFFERED = 1 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./src /app WORKDIR /app celery.py import … -
Is Django able to handle PostgreSQL's truncated table names?
I am creating a Django application with PostgreSQL and some of my model names have become a bit long. Now, PostgreSQL is truncating the table name for such models to 63 characters. Please throw some light as to whether Django is able to handle such truncated table lengths on its own.. For example, consider a sample model with: App Name: MosaicApp Model Name: BeethovenBandLovedRockPopHipHopMetalReggaeLatinMetalCountryElectronicMusic Table Name created: MosaicApp_BeethovenBandLovedRockPopHipHopMetalReggaeLatinMe2dcf (or, something of this sort) Should I overlook this table name truncation? I am able to successfully apply-unapply my migrations. But it would be great if the experienced guys could throw some light as to whether this phenomenon can be overlooked. -
APScheduler not creating the job in AWS deployed Django Application
I have deployed an application which consists of a job like the following: from apscheduler.triggers.combining import OrTrigger from apscheduler.triggers.cron import CronTrigger from reports.views import AutoMails def start(): print("reached") scheduler = BackgroundScheduler() mail = AutoMails() trigger = OrTrigger([CronTrigger(hour=17, minute=9)]) scheduler.add_job(mail.get,trigger, seconds=10, id="test_mails_001", replace_existing=True ) scheduler.start() I tested this on the local server and it is working but upon deployment I didn't receive any email Is AWS bocking this somehow?