Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django upload multiple files to dynamic subfolder
Is there any way to upload multiple files to a dynamic subfollder? I need to create the file system like this: _uploads _incident _folder1 _file1.docx _file2.xlsx _folder2 _file1.docx _file2.xlsx _file3.xlsx Where the name of the folder is defined in when upload files. I manage to upload multiple files but each time they are saved in incident folder and only 1 file is saved in subfolder folder1/folder2. These are some of my code. Models.py from django.db import models #Create your models here. def form_directory_path(instance,filename): # file will be uploaded to MEDIA_ROOT/<folder_name>/<filename> return 'incidents/{0}/{1}'.format(instance.folder_name, filename) class UploadFiles(models.Model): folder_name = models.CharField(max_length=40,unique=True) files = models.FileField(upload_to=form_directory_path) date = models.DateField(auto_now_add=True, blank=True, null=True) def __str__(self): return f'{self.folder_name} ({self.date})' Forms.py from django import forms from .models import UploadFiles # class FileFieldForm(forms.Form): # file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class FileFieldForm(forms.ModelForm): class Meta: model = UploadFiles fields = '__all__' widgets = { 'files': forms.ClearableFileInput(attrs={'multiple': True}), } Views from django.shortcuts import render from django.views.generic.edit import FormView from .forms import FileFieldForm from .models import UploadFiles class FileFieldFormView(FormView): form_class = FileFieldForm template_name = 'upload_files_app/upload.html' # Replace with your template. success_url = 'thankYou/' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('files') if … -
Django authenticate user does not work after logging in
I'm trying to create a custom session-based login in Django using a custom user model and a custom login template. For some reasons it worked at first but now the authenticate method from django.contrib.auth is not authenticating user. When it did work, the login and signup button were hidden. users/urls.py app_name = 'users' urlpatterns = [ path('login/', login_user, name='login_user'), path('logout/', logout_user, name='logout_user'), ] users/views.py app_name = 'users' def login_user(request): django_logout(request) message = '' if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: django_login(request, user) return redirect('homepage') else: message = "Log in failed!" messages.error(request, message) return redirect('users:login_user') else: return render(request, 'users/login.html') @login_required(login_url='users/login/') def logout_user(request): django_logout(request) templates/users/login.html <form class="bg-white rounded-5 shadow-5-strong p-5" method="post" action="/"> {% csrf_token %} <!-- Email input --> <div class="form-outline mb-4"> <label class="form-label" for="form1Example1">Email address</label> <input type="email" name="email" id="form1Example1" class="form-control" /> </div> <!-- Password input --> <div class="form-outline mb-4"> <label class="form-label" for="form1Example2">Password</label> <input type="password" type="password" id="form1Example2" class="form-control" /> </div> <!-- Submit button --> <button type="submit" class="btn btn-primary btn-block">Sign in</button> </form> users/models.py class CustomUserManager(BaseUserManager): def create_superuser(self, email, password): if email is None: raise TypeError('Users should have an Email') if password is None: raise TypeError('Password should not be none') user … -
How can i edit file field in Django?
how can I change the input file in Django?I have 3 input fields. But I want to change 2 of them another one has to store old file from database. How can I restore it -
Django with Conda DJANGO_SETTINGS_MODULE error
I am using Django installed under conda-forge conda install -c conda-forge. Right after installation, when I call django-admin, I receive the following error Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). I found the documentation recommend pointing it to mysite.settings, but this is before I start a project. Mind have anyone tell me how should I deal with it? Best, HS -
Dialogflow webhook not working with django
My Dialogflow webhook was working completely fine till yesterday but it is suddenly not connecting to the webhook today. Although I've made no changes in the code. I'm getting the following fulfillment status: Webhook call failed. Error: NOT_FOUND, State: URL_ERROR, Reason: ERROR_NOT_FOUND, HTTP status code: 404. Please note the following points: Fulfillment URL is written in the correct format (with HTTPS protocol). My Django server is running fine and it is also receiving requests when instigated from the browser. (Just not receiving requests from Dialogflow) Suddenly, none of my Dialogflow agents (previously built and working fine) are sending requests to Django/Flask server. I've checked multiple things like trying from different Dialogflow accounts and different browsers but I can conclude that the issue is with the Dialogflow webhook/Fulfillment. Please, help me with the solution. Thank you in advance. -
How to post data in django-cms using cms.api?
I am using django-cms. I want use react as front end and post data in django-cms by using cms.api. I am not able to get proper solution. -
How to save django form without displaying it
I have a page (se_balance.html) that displays a parent form and a child formset. The contents of the parent form is set by the link selected by the user on the previous page. I would like to only display the formset and the parent form to be saved without being displayed, however, if I do not have the parent form in the html I receive an error related to the fact that the parent form is invalid. This is the view used to generate the page in question class CaseView(TemplateView): model = Case template_name = "../templates/se_balance.html" def get(self, *args, **kwargs): # here the parent form is created based on user selected link from previous page p = self.request.GET.get("p", None) case_form = CaseForm(initial={'pharm_class_name': p}) #i sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none()) return self.render_to_response( { "case_form": case_form, "sideeffect_formset": sideeffect_formset, "sideeffect_formsethelper": SideEffectFormSetSetHelper, } ) def post(self, *args, **kwargs): form = CaseForm(data=self.request.POST) sideeffect_formset = SideeffectFormSet(data=self.request.POST) if form.is_valid(): case_instance = form.save(commit=False) if self.request.user.is_authenticated: case_instance.user = self.request.user case_instance.save() if sideeffect_formset.is_valid(): sideeffect_name = sideeffect_formset.save(commit=False) for sideeffect in sideeffect_name: sideeffect.case = case_instance sideeffect.save() return redirect( reverse( "results", kwargs={"case_id": case_instance.case_id}, ) ) How should I amend it so that I don't ned to display the parent form to the user -
How to built ola in django
I want to crate ola like service app using django that provide cooking and other services so i want to integrate map just like ola in this django project. What technologies packages and APIs i should use if someone could help that would be very helpful. -
How to fix AttributeError in django?
I am unable to find out the issues. Please let me How to fix this one and which website is good for this types of issues. -
Django Martor image upload only working on Mobile
The Image Upload button works fine on my cell phone, but when trying to use chrome desktop, the upload button is dead and does nothing. The part of the toolbar that is responsible for it is this: {% if 'image-upload' in toolbar_buttons %} <span class="btn btn-light markdown-selector markdown-image-upload" title="{% trans 'Upload an Image' %}"> <i class="fas fa-image"></i> <input name="markdown-image-upload" class="button" type="file" accept="image/*" title="{% trans 'Upload an Image' %}"> </span> {% endif %} Is there something about the mobile browser that makes this usable but not on the desktop? -
TemplateDoesNotExist-Already added the templates dir in settings and created inside project
I have created a project "ProTwo" and app as "appTwo" added the templates dir in the project settings and created templates folder in the project.When I render the views index.html its showing error app/views.py ''' from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): help_dict={'help_me':"HELP PAGE"} return render(request,'appTwo/help.html',context=help_dict) ''' app/urls.py ''' from django.urls import path from appTwo import views urlpatterns = [ path('',views.index,name="index"), ] ''' Project/settings.py """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR=os.path.join(BASE_DIR,"templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-0m6xzby50vk61zdun2g%oq^nkr2v0=_7il#z#qnx)=7=6q_e^p' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appTwo', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ProTwo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ProTwo.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
Django: Saved data is not outputting to html .(I am real beginner.)
Thank you for reading. Even though data is stored in the Product, it is not output to the store.html screen. What might be the problem? I checked Product is saved with admin page. I'm so new I have no idea what I'm doing wrong. Thank you very much. views.py def store(request): global products, context data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'maps/store.html', context) models.py class Product(models.Model): poiid = models.DecimalField(max_digits=7, decimal_places=2) name = models.CharField(max_length=200, null=True) price = models.CharField(max_length=7, null=True) address = models.CharField(max_length=7, null=True) digital = models.BooleanField(default=False, null=True, blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) # Call the "real" save() method. def __str__(self): return self.name # url = '' # return url store.html {% extends 'maps/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-md"> <div class="card card-body"> <table class="table table-sm"> <tr> <th>poiid</th> <th>name</th> <th>category</th> <th>address</th> <th>save</th> </tr> {% for product in products %} <tr> <td>{{product.poiid}}</td> <td>{{product.name}}</td> <td>{{product.price}}</td> <td>{{product.address}}</td> <td><button data-product={{product.id}} data-action='add' class="btn btn-outline-secondary add-btn update-cart">save</button></td> </tr> {% endfor %} </table> </div> </div> </div> {% endblock content %} -
Why is my data not rendering from this.state?
I've been trying to get an array to come over into react and then display it on the browser. The data is coming over, but for some reason I cannot display it. ReactJs: import React, { Component } from "react"; export default class RegisterPage extends Component { constructor(props){ super(props); this.state = { }; this.getPlayers(); } getPlayers() { fetch('/draft/get-players') .then((response) => response.json()) .then((data) => { this.setState({ players: data, }); }); } render(){ return (<h1>{this.state.players[0].name}</h1>) } } I initially was trying to .map this into multiple lines of HTML, but through troubleshooting learned that I'm not even able to get a single element out of the array. JSON from /draft/get-players: [ { "id": 1, "name": "Aidan Hutchinson", "position": "EDGE", "EstimatedRound": 1, "college": "Michigan", "age": "SR", "TakenRound": null, "TakenPick": null }, { "id": 2, "name": "Aidan Hutchinson", "position": "EDGE", "EstimatedRound": 1, "college": "Michigan", "age": "SR", "TakenRound": null, "TakenPick": null }, { "id": 3, "name": "Kayvon Thidobeaux", "position": "EDGE", "EstimatedRound": 1, "college": "Oregon", "age": "SOPH", "TakenRound": null, "TakenPick": null }, { "id": 4, "name": "Kyle Hamilton", "position": "S", "EstimatedRound": 1, "college": "Notre Dame", "age": "JR", "TakenRound": null, "TakenPick": null }, { "id": 5, "name": "Ikem Ekwonu", "position": "OL", "EstimatedRound": 1, "college": "NC State", "age": … -
Does This Hierarchy work with ListView? Getting NoReverseMatch Error
I'm running into an issue debugging the following error: Reverse for 'tasks' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P[-a-zA-Z0-9_]+)/tasks/$'] However, I'm pretty certain that my url parameters are correct and without typos. The url and page worked fine with a function based view, the problem started when I changed to a ListView. Template: <a href="{% url 'customerportal:tasks' object.slug %}" class="nav-link"> I also tried: <a href="{% url 'customerportal:tasks' slug=object.slug %}" class="nav-link"> <a href="{% url 'customerportal:tasks' slug=object.slug|slugify %}" class="nav-link"> My ListView: class TaskListView(ListView): model = Task template_name = 'customerportal/tasks.html' def get_queryset(self): self.project = get_object_or_404(Project, slug=self.kwargs['slug']) return Task.objects.filter(project=self.project.id) URLs: path('<slug:slug>/', ProjectDetailView.as_view(), name='customer-portal'), path('<slug:slug>/tasks/', TaskListView.as_view(), name='tasks'), I've confirmed that I'm passing the right slug by printing it. The slug parameter is from a parent directory as seen in the urls.py above. I'm guessing ListView doesn't work this way? If not is there a way I could maintain this structure, or do I have to switch back to a function based view in order to get this to work? Thanks. -
RelatedManager object is not iterable
Whenever I run my code, I get a "RelatedManager" object is not iterable error. Here is my models.py: from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse class Post(models.Model): contents = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) replies = list() def __str__(self): return f'{self.author} - {self.pk} - {self.date_posted}' def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Reply(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='replies') contents = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.author} - {self.date_posted}' def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Meta: ordering = ['-date_posted'] Here is my views.py: from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from .forms import ReplyForm class PostListView(ListView): model = Post template_name = 'app/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 15 def PostDetailView(request, **kwargs): template_name = 'app/post_detail.html' post = get_object_or_404(Post, pk=kwargs['pk']) replies = post.replies new_reply = None # Reply added if request.method == 'POST': reply_form = ReplyForm(data=request.POST) if reply_form.is_valid(): # Create reply object but don't save to db yet new_reply = reply_form.save(commit=False) # Assign the current post the the reply new_reply.post = post … -
Django: How do I put data from a csv file into a datatype I created in "models.py"?
I'm learning django for the first time, I'm stuck on even the simplest screen output. I even created a data format to display in the listview in models.py, how do I add data to this now? (I've tried to save the data in admin page, but there is no output.) I want to output the data in csv, so does anyone know how to put the data in the name directly in the python file and pop it up on the screen? class Product(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name url = '' return url thank you so much! -
How To Get Google User Profile Info Using Access Token From OAuth?
I am using ReactJS on the frontend: I successfully retrieved the access token from Google's Oauth service, but it doesn't give me any profile information for the 'current user'. I tried using the /userInfo endpoint, ?access_token={my_access_token} query str, and some other solutions but I keep getting weird errors. Currently I have: const { access_token, refresh_token } = res.data; // now I have valid access_token let userInfo = await axios.get("https://www.googleapis.com/oauth2/v3/userinfo", { headers: { Authorization: `Bearer ${access_token}` } }); // ERROR WHEN MAKING THIS CALL. My specific 401 error is as follows: error message -
heroku host successfully but application error
I successfully deploy the to Heroku. but when I run Heroku open it throws Application error occurred "An error occurred in application and your page could not be served. if you are the application owner, check your logs for details my logs is here 2022-01-23T02:24:56.663017+00:00 app[api]: Initial release by user victchubxy@gmail.com 2022-01-23T02:24:56.663017+00:00 app[api]: Release v1 created by user victchubxy@gmail.com 2022-01-23T02:24:56.822006+00:00 app[api]: Release v2 created by user victchubxy@gmail.com 2022-01-23T02:24:56.822006+00:00 app[api]: Enable Logplex by user victchubxy@gmail.com 2022-01-24T02:06:26.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T02:06:27.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/b6179e58-ffa5-4189-964c-63cbc70d8d08 2022-01-24T02:26:50.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T02:26:51.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/8c889fa0-73c2-4257-b19d-ca893a595436 2022-01-24T03:22:22.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T03:22:23.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/634953f5-1324-4dd4-afbc-35bc9296c1b8 2022-01-24T03:23:35.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T03:23:36.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/9da67c75-fb7c-4178-98c9-8e05551efb06 2022-01-24T03:38:33.000000+00:00 app[api]: Build started by user victchubxy@gmail.com 2022-01-24T03:38:34.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/af9da633-ce1d-4e6b-bd49-51c06b87f315/activity/builds/b84dff51-b132-417a-aca9-cba9f79e549c 2022-01-31T02:21:07.844606+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=hidden-hollows-48192.herokuapp.com request_id=ef621c27-e056-43fb-af5d-feecc2a18e7f fwd="197.210.79.99" dyno= connect= service= status=502 bytes= protocol=https 2022-01-31T02:39:40.874045+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=hidden-hollows-48192.herokuapp.com request_id=4e6586b7-4de1-491a-a4fb-dfcfdb3820cd fwd="197.210.79.240" dyno= connect= service= status=502 bytes= protocol=http 2022-01-31T02:39:42.062534+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET … -
Django Admin Model - Foreign key is showing email, not id
I have two models - An Article Model. A Reporter Model. Just like the Django Documentation from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return str(self.email) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return str(self.headline) I also have registered this in my admin.py file @admin.register(Reporter) class ReporterAdmin(admin.ModelAdmin): pass @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): pass When I go to add an article in admin, the field for reporter shows me the reporters email, I want it to show me the reporters id (the id field that is created by default). -
Django custom ordering causes error for related model?
I have two models as follows: class A(models.Model): # more fields here finished_at = models.DateTimeField(db_index=True, null=True, blank=True) class Meta: ordering = [ models.F("finished_at").desc(nulls_first=True), "other_field", ] class B(models.Model): related = models.ForeignKey(A, on_delete=models.CASCADE) class Meta: # custom ordering here too And then when I try to delete A instances through the admin site, or when accessing B instances either through admin or command line it gives error: Cannot resolve keyword into field finished_at. But if I remove the ordering on model A it works fine. -
Query in Django template
I am trying to query inside a django template, but i am just not sure how to correctly phrase the query, i have two models 1-category 2-items and i am trying to get all the items of a specific category from it's ID {% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%} here is the complete template: <div class="inventory-content"> <div class='category'> <div>Categories</div> <div class='category-checkbox'> {%for category in items%} <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}"> <label for="{{category.name}}"> {{category.name}}</label><br> {%endfor%} </div> </div> <div class='items'></div> </div> <script> $('.category-checkbox input[type="checkbox"]').on('click', function() { if ($(this).is(':checked')) { // Add the element to the div with an id identifier $('.items').append(`<div id="item_${this.id}">{% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}</div>`); } else { // Remove the element from the div targeted by the id identifier $(`#item_${this.id}`).remove(); } }); </script> models.py: class Category(models.Model): name = models.CharField(max_length=150) vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE,related_name='category') def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=255) part_number = models.IntegerField(blank=True) ROB = models.IntegerField(default=0) category=models.ForeignKey(Category,related_name='items',on_delete=models.CASCADE) def __str__(self): return self.name also i have been told it's bad practice to write query inside the template, so if you can guide me what better way could i have achieved this ?which is querying for all items in a specific category when checked -
Do I need to create a model for a table I'm inserting through sqlalchemy in django?
I have a Command class that runs an api call to a coin market cap api and writes it into the database that I have rigged up to my django project called cryptographicdatascience. The table that the data is written to is called apis_cmc and is not defined in my models.py. My question is if I am writing straight to a table using sqlalchemy do I need to go in and create a model for the same table in my models.py file? It seems to me that the answer is no but I'm sure there is something I'm overlooking. Thanks, Justin -
The command 'pip freeze' on the linux bash shell is not showing any of the installed packages in the output
I'm using the Linux Bash shell on Windows to activate django virtual environment and I want to see if the packages I'm using in this certain project are showing up using pip freeze (just like in the tutorial I am watching, since I'm very new to Linux in general) but once I put in the command, it doesn't give me any errors it's just that it won't output any packages at all. This might be a very simple question to some of you guys but I was doing some research and I can't find anyone in the exact same circumstances I'm in, so I decided to come to SO for help. As you can see in the image, it only shows the + pip freeze. Please, any help would be appreciated. -
Single object from queryset
I need help with a little issue I am having with my project. I have a model where I have a foreign key with many entries and I would like to take just one item of these entries. In fact, my problem is something like that: I need to obtain the single mission id, in order to have other functions. The code is working fine, my problem is that I don't know the righe order to obtain the mission item from this queryset: models.py from django.db import models from flight.models import LogEntry from user.models import Instructor, Student # Create your models here. TRAINING_COURSE_CHOICES = ( ('PPL', 'PPL'), ('CPL', 'CPL'), ('IR', 'IR'), ('ATPL', 'ATPL'), ) class TrainingCourse(models.Model): name = models.CharField(max_length=20, choices=TRAINING_COURSE_CHOICES) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class StudentTrainingCourse(models.Model): training_course = models.ForeignKey( TrainingCourse, on_delete=models.PROTECT) student = models.ForeignKey(Student, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.student.first_name + ' ' + self.student.last_name + ' ' + self.training_course.name class Mission(models.Model): name = models.CharField(max_length=200) training_course = models.ForeignKey( TrainingCourse, on_delete=models.CASCADE) note = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.training_course.name + ' ' + self.name class StudentMission(models.Model): mission = models.ForeignKey(Mission, on_delete=models.PROTECT) student_training_course = models.ForeignKey( StudentTrainingCourse, … -
Django queryset - Add HAVING constraint after annotate(F())
I had a seemingly normal situation with adding HAVING to the query. I read here and here, but it did not help me I need add HAVING to my query MODELS : class Package(models.Model): status = models.IntegerField() class Product(models.Model): title = models.CharField(max_length=10) packages = models.ManyToManyField(Package) Products: |id|title| | - | - | | 1 | A | | 2 | B | | 3 | C | | 4 | D | Packages: |id|status| | - | - | | 1 | 1 | | 2 | 2 | | 3 | 1 | | 4 | 2 | Product_Packages: |product_id|package_id| | - | - | | 1 | 1 | | 2 | 1 | | 2 | 2 | | 3 | 2 | | 2 | 3 | | 4 | 3 | | 4 | 4 | visual pack_1 (A, B) status OK pack_2 (B, C) status not ok pack_3 (B, D) status OK pack_4 (D) status not ok My task is to select those products that have the latest package in status = 1 Expected result is : A, B my query is like this SELECT prod.title, max(tp.id) FROM "product" as prod INNER JOIN "product_packages" …