Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
with custom user i have not the group form in admin django
I created a custom user, it works well, but I notice that in the django admin, if I create a new user, I don't have access to the form that manages the groups. If I use a standard user system, when you create a user, in the admin, you have access to the management of groups and permissions. On the other hand in my project group and user are not linked my models.py from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password): if not email: raise ValueError('Vous devez entrer une adresse email.') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email=email, password=password) user.is_staff = True user.is_admin = True user.save() return user class CustomUser(AbstractBaseUser): email = models.EmailField( max_length=255, unique=True, blank=False ) nom = models.CharField(max_length=50, blank=False, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = "email" def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def __str__(self): return self.email in the views.py from django.contrib.auth import authenticate from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login as log_user from django.contrib.auth import logout as logout_user from accounts.forms import … -
Django Allauth not included in URL Conf through template links but URL is functional
I am new to using AllAuth and somewhat new to Django. I am developing a site and wanted to overhaul the custom user authentication that I was using before. I have implemented AllAuth into an existing solution. Everything seems to be connecting, but the template links are not working and I get returned a 404 error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/url%20'account_login' Using the URLconf defined in QuoteTool.urls, Django tried these URL patterns, in this order: admin/ [name='home'] accounts/ form/ [name='entryForm'] form/success [name='success'] quotes/ [name='quotes'] The current path, url 'account_login', didn’t match any of these. For example in my Navbar ... {% if user.is_authenticated %} <div class="m-2"> <h6>Hello, {{ request.user.firstName }}!</h6> </div> <a class="btn btn-outline-secondary" href=" url 'account_logout' ">Logout</a> {% else %} <a class="btn btn-outline-secondary" href=" url 'account_login' ">Login</a> <a class="btn btn-primary ml-2 mr-2" href=" url 'account_signup' ">Sign Up</a> {% endif %} ... These links do not work! I am not understanding why not. Especially since if I manually type the URL "http://127.0.0.1:8000/accounts/login/" it returns and renders the proper page with my custom template. My url.py file is as follows from django.contrib import admin from django.urls import path, include from QuoteTool import views from accounts import … -
Django Project Permissions for Production
I’m struggling on how to properly set up my directory and file permissions for my Django apps on my Linux Server. I set the permissions on my Development Test machine to 755 for Directories and 644 for Files. However, I was unable to run pip from the Terminal in PyCharm until I increased the permissions for pip file. Are these the correct permissions for all folders/files in the Virtual Environment as well, especially the files in the Bin directory? Also, I have ownership of files set to a specific user I elevate privileges to perform certain ops. I am reading some people use root as owner of Django directory and files. Which is preferred in production environment? Any help would be greatly appreciated. -
Proper way to manage a list of form in Django
What is the best way to handle an array of forms in django? I am trying to create a custom permissions system and I have to do the form to create a role. The models involved are listed below: class CategoryPermissions(models.Model): upload = models.BooleanField(default=False) download = models.BooleanField(default=False) history = models.BooleanField(default=False) class Category(models.Model): name = models.CharField(max_length=250, unique=True) label = models.CharField(max_length=250) directory = models.CharField(max_length=250) class GroupPermissions(models.Model): role = models.ForeignKey('repository.Role',on_delete=models.RESTRICT) category = models.ForeignKey('repository.Category',on_delete=models.RESTRICT) category_permissions = models.OneToOneField("repository.CategoryPermissions",on_delete=models.RESTRICT) class Role(models.Model): name = models.CharField(max_length=250) For each Category (which are already created) I define a CategoryPermissions that contains the permissions and I link it to the Role with GroupPermissions. How do I create a multiple form that allows me to create GroupPermissions with related CategoryPermissions, maintaining the relationship between GroupPermissions, Category and Role? I tried with a CategoryPermissions formset, but when I extract it from request.POST I don't know which one I understand that it may be unclear so do not hesitate to ask for more explanations, I will try to do my best. -
a python script that binds a google table and postgresql
How to write a python script that can: Get data from the document using Google API made in [Google Sheets]. The data should be added to the database, in the same form as in the -source file, with the addition of the column "column_name." a. Need to create DB independently, DBMS based on PostgreSQL. The script runs constantly to ensure that the data is updated online (it is necessary to take into account that the rows in the Google Sheets table can be deleted, added and changed). And this script is wrapped in Django application I have made all the necessary API's and settings -
Unable to return user data properly in Django
I am following a tutorial and I got myself stuck. I've built the login page of the website and now I was just trying to display a dropdown in the Navbar, that displayed the user's name. Here is the code that is responsible for that to happen: {userInfo ? ( <NavDropdown title={userInfo.name} id="username"> <LinkContainer to="/profile"> <NavDropdown.Item>Profile</NavDropdown.Item> </LinkContainer> <NavDropdown.Item onClick={logoutHandler}> Logout </NavDropdown.Item> </NavDropdown> ) : ( <LinkContainer to="/login"> <Nav.Link> <i className="fas fa-user"></i>Login </Nav.Link> </LinkContainer> )} Trying to debug the issue I realized that 'userInfo' is just returning me the refresh and access token of the user, and basically userInfo.name does not exist. Here's the User action: import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, USER_LOGOUT, } from "../constants/userConstants"; import axios from "axios"; export const login = (email, password) => async (dispatch) => { try { dispatch({ type: USER_LOGIN_REQUEST, }); const config = { headers: { "Content-type": "application/json", }, }; const { data } = await axios.post( "/api/users/login/", { username: email, password: password }, config ); dispatch({ type: USER_LOGIN_SUCCESS, payload: data, }); localStorage.setItem("userInfo", JSON.stringify(data)); } catch (error) { dispatch({ type: USER_LOGIN_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }); } }; And the user views: from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes … -
How to display data from Django manager's method in Django templates?
I'm implementing an app where a manager can control the products and their batches where he can activate or deactivate batches by selecting the,, so I'm trying to display a dropdown list to show all the available batches with their 'expiration status' and 'quantity availability status' and 'activation status'. What I did so far is that i have created a QuerySet and Manager classes in my Django model class, and I want to retrieve these classes and display them in my template. But the problem is that it didn't work, in my templates it displays nothing, and the select field doesn't show any choices. Here's what I did in models.py: class ExpirationStatus(models.TextChoices): VALID='VALID',_('Valid') ONE_MONTH= 'ONE_MONTH',_('One month or Less') THREE_MONTHS='THREE_MONTHS',_('Three Months Or Less') EXPIRED='EXPIRED',_('Expired') class BatchQuerySet(models.QuerySet): def annotate_expiration_status(self): one_month=date.today() - timedelta(days=30) three_months=date.today() - timedelta(days=90) today=date.today() return self.annotate(expiration_status= Case( When(expiry_date__lt=today,then=Value(ExpirationStatus.EXPIRED)), When(expiry_date__lte=one_month,then=Value(ExpirationStatus.ONE_MONTH)), When(expiry_date__lte=three_months, then=Value(ExpirationStatus.THREE_MONTHS)), When(expiry_date__gt=three_months, then=Value(ExpirationStatus.VALID)), )).order_by('arrival_date') class BatchManager(models.Manager): use_for_related_fields = True def annotate_expiration_status(self): return self.get_queryset().annotate_expiration_status() def get_queryset(self): return BatchQuerySet(model=self.model, using=self._db) class Batch(models.Model): class Status(models.TextChoices): ACTIVE = 'active', _('Active') INACTIVE = 'inactive', _('Inactive') product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='product_batch') expiry_date = models.DateField() quantity_bought = models.PositiveIntegerField() status=models.CharField(max_length=32, null=True, choices=Status.choices) arrival_date = models.DateField(auto_now_add=False) objects=BatchManager() def available_quantity(self): return self.quantity_bought-(self.issued_batches.aggregate(total_issued_quantity=Sum('issued_quantity')).get('total_issued_quantity') or 0) def __str__(self): return self.product.name + ' … -
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