Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate or use docusign(api) using django?
I have done one small app using Django. Now, i'm trying to integrate docusign to my app.I have undergone through this url : https://github.com/peopledoc/django-docusign/tree/master/demo but it's not working .Any suggestions please? -
Unable to import a file and text filed from same HTML form
I need to import a file and text(field) from same html form. But I'm getting the error: Unable to upload file. MultiValueDictKeyError('name',) form.html <form action="{% url "upload2" %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="name"> <input type="file" name="xlfile"> <button type="submit">Upload</button> </form> veiw.py def upload2(request): if "GET" == request.method: return render(request, "homepage/new.html") try: myfile = request.FILES['xlfile'] cname = request.GET['name'] print(cname) return HttpResponse('ok') except Exception as e: logging.getLogger("error_logger").error("Unable to upload file. "+repr(e)) messages.error(request,"Unable to upload file. "+repr(e)) Error Unable to upload file. MultiValueDictKeyError('name',) Internal Server Error: /upload2 Traceback (most recent call last): File "/home/csdj/django/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/csdj/django/django/core/handlers/base.py", line 126, in _get_response "returned None instead." % (callback.module, view_name) ValueError: The view homepage.views.upload2 didn't return an HttpResponse object. It returned None instead. -
How to deal with zoom and api call errors
When I create jwt and call zoom api, I get the error {'code': 124, 'message': 'Invalid access token.'}. What does this mean? ApiKey = 'xxx' ApiSercret = 'xxx' mail = request.POST['mail'] print(mail) today = datetime.today() header = { 'alg':'HS256' } payload = { 'iss': ApiKey, 'exp': today + timedelta(hours=1), } #https://docs.authlib.org/en/latest/specs/rfc7519.html#authlib.jose.rfc7519.JWT.check_sensitive_data token = jwt.encode(header,payload,ApiSercret,check='true') print(token) options = { 'uri':'https://api.zoom.us/v2/users/'+mail+'/meetings', 'qs':{ 'status':'active' }, 'auth':{ 'bearer':token }, 'headers':{ 'User-Agent':'Zoom-api-Jwt-Request', 'content-type':'application/json' }, 'json':'true' } try: r=requests.get(options['uri'],params=options) print(r.json()) except: traceback.print_exc() print('API call failed, reason ') params = { mail:token } return render(request,'api/index.html',params) error contents {'code': 124, 'message': 'Invalid access token.'} Is this error an error on setting zoom api? I am trying to get the conference list in zoom api. I want to print the contents acquired by get with print. -
Compare year from DateTimeField/DateField Django ORM
I have a model configuration as below, class Foo(models.Model): start = models.DateTimeField() end = models.DateTimeField() How can I retrieve Foo instances with same Year? Unsuccessfull try: from django.db.models import F Foo.objects.filter(start__year=F('end__year')) returnd empty QuerySet -
how to fetch only content from table by avoiding unwanted codes
I was trying to fetch text content from table which works well but along with result it print unwanted codes my code is here searchitem = searchme.objects.filter(face = after) .values_list ("tale" , flat = True) the contents are text the result I receive is : searchitem but I only want o get result "Prabhakaran" -
form.cleaned_data return empty
I have a problem after choose a choice i get empty set. And the form return empty and cannot save the selected choice to the database. And this is my code : I have a form : class UserResponseForm(forms.Form): gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=1), widget=forms.CheckboxSelectMultiple, required=False) And my view def responsePenyakit(request): if request.user.is_authenticated: form = UserResponseForm(request.POST or None) if form.is_valid(): gejala1 = form.cleaned_data.get('gejala_id1') answer = UserAnswer.objects.all().filter(user_id = request.user.id).order_by('-number_diagnosis') user = UserAnswer() if(len(answer) > 0): user = answer[1] else: user.number_diagnosis = 0 if(len(gejala1)>0): for i in range(0, len(gejala1)): userAnswer = UserAnswer() userAnswer.gejala_answer = gejala1[i] userAnswer.user_id = request.user.id userAnswer.number_diagnosis = user.number_diagnosis+1 userAnswer.save() return redirect('diagnosis_penyakit:response_matching') else: raise Http404 And my form : <form method='POST' action='{% url "diagnosis_penyakit:response"%}' enctype="multipart/form-data"> {% csrf_token %} {{ form.errors }} <div class="row" style="margin-left:10rem;"> <div class="col-md-3"> <a onclick="myFunction1()" style="font-size:2rem; color:black;">Tubuh <i class="fas fa-angle-down"></i></a><br/> <div id="myDIV1" style="display:none; margin-left:-3rem;"> {{ form.gejala_id1 }} </div> </div> </div> And my model : class UserAnswer(models.Model): gejala_answer = models.CharField(max_length=250) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) number_diagnosis = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.gejala_answer class Gejala(models.Model): penyakit_id = models.IntegerField() gejala = models.CharField(max_length=150) id_organ = models.IntegerField(null=False) status = models.CharField(max_length=150, default='Tetap') def get_absolute_url(self): return reverse('gejala:gejala_detail', kwargs={'pk':self.pk}) def __str__(self): return self.gejala What's wrong and what should i do? Hope anyone can … -
Incompatible bootsrapp in normal browser
I have a web-application that works fine in private window. However, if i opened it in normal browser bootstrap files aren't loaded and gives issues in frontend display. -
How to save multiple uploaded files in Django?
I'm trying to upload multiple files in Django but keep getting an AttributeError: 'InMemoryUploadedFile' object has no attribute 'save'. Is there something I have to do before invoking the save() function within this class? This code comes from the Django docs but the docs say # Do something with each file. where I have f.save() My views.py class FileFieldView(FormView): form_class = FileFieldForm template_name = 'uploader/payroll.html' success_url = 'blog-home' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: f.save() # this is where the issue occurs return self.form_valid(form) else: return self.form_invalid(form) My forms.py class FileFieldForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) My .html file {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="col-md-14"> <div class="content-section"> <h6 class="application-heading">Payroll</h6> <div class="article-content">To begin please upload the files below. </div> </div> </div> <div class="col-md-14"> <div class="content-section"> <h6 class="article-title">Upload Spreadsheets</h6> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary" type="submit">Upload Spreadsheets</button> </form> </div> </div> {% endblock content %} The expected results are to upload multiple files to the server. -
Merge two different Django migrations
We have two developers working on Django. Due to some technical issues we have not started using version control yet. The two developers did some changes to the django models. Developer A has 1 migration and the developer B has 5 migrations. They both worked in two different tables. How do I go about merging the two migrations if they did not use version control. -
When I make website with django, How can I ipynb file import?
My project code was already ended by python(jupyter notebook). But, I don't know how to import python code to django. I want to make web application with django. thank you! windows 10 server -
Display Video from Database in Django
I am trying to make an application using Django, called Video uploader where a user should be able to upload a video and the video should be displayed on the same page as soon as the user clicks submit button. This is the code for HTML that I used for the videos.html page , models.py and views.py model.py class Video(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) views.py from .models import Video from .forms import VideoForm def showvideo(request): videofile= Video.objects.first() form= VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() context= {'videofile': videofile, 'form': form } return render(request, 'blog/videos.html', context) videos.html <head> <meta charset="UTF-8"> <title>Upload Videos</title> </head> <body> <h1>Video Uploader</h1> <form enctype="multipart/form-data" method="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Upload"/> </form> <br><br> <video width='400' controls> <source src='{{ MEDIA_URL }}{{ videofile }}' type='video/mp4'> Your browser does not support the video tag. </video> <br><br> </p> </body> </html> I think there is problem in retrieving the uploaded file from database as the error shows invalid URL. Is there an easier way to get it done. I want the file to be displayed on the same page instead of going through another link … -
The User ForiegnKey is now showing up as a field in django rest framework viewset
I am building a backend for a web app using django rest framework. I have a profile model that has a user forieingkey referencing a django user. Everything is loading correctly except for one issue which is that the User field is not showing up in the django rest framework backend urls so that I can assign a user to the profile object i want to create... does anyone know why this is happening... models.py: class Profile(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE ) synapse = models.CharField(max_length=25, null=True) bio = models.TextField(null=True) profile_pic = models.ImageField( upload_to='./profile_pics/', max_length=150 ) facebook = models.URLField(max_length=150) twitter = models.URLField(max_length=150) updated = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username + ' profile' viewset: from users.models import Profile from users.api.serializers.ProfileSerializer import ProfileSerializer from rest_framework import viewsets class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'user__username' url: from users.api.views.ProfileView import ProfileViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', ProfileViewSet, base_name='profile') urlpatterns = router.urls serializer: from rest_framework import serializers from users.models import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ( 'id', 'user', 'synapse', 'bio', 'profile_pic', 'facebook', 'twitter' ) depth=2 -
How can i save the output computed in view.py together with the rest of data in form.py
I have a form with defined data with some hidden field ie IP address as this will not need to be shown to users at the form page. After a user selects an address size, then view.py function will calculate and carve out a block of IPs. I want this IP to be saved along with the other information in form. Please see code below I thought passing the account = account_form.save(commit=False) then calling account.next_subnet (which is responsible for the IP cal) Then running a account.save() #models.py class Account(models.Model): id = models.AutoField(primary_key=True, editable=False) us = models.CharField(max_length=100, blank=False) account = models.CharField(max_length=100, blank=False) network_size = models.CharField(max_length=100, blank=False) network_range = models.CharField(max_length=100, blank=False) budget = models.CharField(max_length=100, blank=False) account_number = models.IntegerField(blank=True, null=True) class Meta: db_table = "xxxx" def __str__(self): return self.account #forms.py class AccountForm(ModelForm): class Meta: model = Account fields = (us', 'account', 'network_size', 'budget',) CHOICES = (('small', 'small'),('medium', 'medium'),('large','large'),) choices=[(x, x) for x in range(500,10000 )] widgets = { 'us': forms.TextInput(attrs={'placeholder': 'us', 'class': 'form-control'}), 'account': forms.TextInput(attrs={'placeholder': 'account', 'class': 'form-control'}) , 'network_size': forms.Select(choices=CHOICES,attrs={'class': 'form-control'}), 'budget': forms.Select(choices=choices,attrs={'class': 'form-control'}), 'account_number':forms.HiddenInput(), 'network_range':forms.HiddenInput(), } #views.py @login_required(login_url='/portal/sign-in/') def portal_create_account(request, *args, **kwargs): account_form = AccountForm(request.POST) if request.method == "POST": account_form = AccountForm(request.POST) if account_form.is_valid(): account = account_form.save(commit=False) account = account_form.cleaned_data['account'] network_size … -
choose a database type to create an web application where [on hold]
first of all i want to know which database type i should use for the following project. secondly, i want to create a website using python(django) where the website will be able to : *find a item among thousand of items *each item has 6, 10 or 13 other sub-item *each sub-item selected shall contain multiple values(also each value has its own price and number) NB: the sub-item sometimes may have the same value(but different number for each value according to the need) i have been using inheritance, but i'm getting lost and don't know a better way to solve it. thank you -
How to use Django reduce 4k video resolution to 720p during streaming
I have a Django site streaming videos. All videos are stored under /media/myvideo/, such as /media/myvideo/4kvideo.mp4 I want to limit the video received from client to be 720 resolution as 4k file is too large. Client browser screen is small, 720 resolution is good enough. I don't want to modify video file size on server. ---mail.html--- <video id="video" autoplay="" playsinline="" controls=""> <source src="/media/4kvideo.mp4" type="video/mp4"> Your browser does not support the video tag. </video> ---settings.py--- MOVIES_DIR = '/media/myvideo/' STATICFILES_DIRS = ( (os.path.join(SITE_ROOT, 'static/')), MOVIES_DIR, ) MEDIA_ROOT = MOVIES_DIR MEDIA_URL = '/media/' Question is how to use Django to reduce 4kvideo.mp4 resolution size during streaming, so that streaming speed will be faster. -
What is the best way to implement vue, vuetify for the frondend and Django for the back end
I am trying to implement Vue.js and Vuetify for the frontend and run Django for the backend. I found couple of tutorials and they all differ from each other. Is there a suggestion to follow? What are the pros and cons -
How can i make a certain template visible only to confirmed users in Django?
I'm creating a site and i successfully added an email confirmation system using django-allauth. Now i would like to have some parts of my site available only to users who confirmed their email. Suppose that part looks something like this: {% extends "main/header.html" %} {% if user.is_authenticated %} {% block content %} <body> <div> <p> Here are are a bunch of features etc... </p> </div> </body> {% endblock %} {% endif %} Now, i know how to do that in theory, but not practically. I figured that i need to add a statement that checks if the email is confirmed. What i'm not understanding is where should i add this statement and what that should look like. Should it be on the template? Or should i create a view for this? Any advice is appreciated? Thanks in advance! -
ingress-nginx problem with Django & query parameters
I'm using Django and I've deployed it using Kubernetes on Google Cloud platform with the help of ingress-nginx. Everything works fine so far, but I encountered a small issue with query parameters. I have a path like this which works on localhost http://localhost:8000/gopay-notify/?parent_id=&id=3083891252 However, when I try to access it using my domain it works if I access https://example.org/gopay-notify/ But it throws 404 if I access it like this https://example.org/gopay-notify/?parent_id=&id=3083891252 Can somebody please show me a direction here? I feel I tried everything. I played with nginx.ingress.kubernetes.io/rewrite-target quite a lot, but the point is I can only rewrite urls without query parameters. (which I actually don't need) Here's my config apiVersion: extensions/v1beta1 kind: Ingress metadata: name: exampleorg-admin-ingress annotations: kubernetes.io/ingress.class: nginx kubernetes.io/ingress.global-static-ip-name: exampleorg-admin-ip ingress.kubernetes.io/ssl-redirect: true nginx.ingress.kubernetes.io/proxy-body-size: 5m # ingress.kubernetes.io/force-ssl-redirect: true # ingress.kubernetes.io/from-to-www-redirect: true labels: app: exampleorg-admin spec: rules: - host: beta.example.com http: paths: - backend: serviceName: exampleorg-admin-service servicePort: 8080 path: / tls: - hosts: - beta.example.org secretName: exampleorg-tls -
Django SMTPSenderRefused at / (530, b'5.5.1 Authentication Required
I've been trying to let users send email to my personal account via a contact form. This is the error: SMTPSenderRefused at / (530, b'5.5.1 Authentication Required. I tried changing my password, using SSL instead of TLS, using only plain strings, different emails and turning on IMAP and POP in the gmail settings, but nothing seems to work. I keep getting the same error. views.py def mainview(request): all_projects = Projects.objects.all() if request.method == 'POST': messagecontainer = request.POST['name'] host_mail = settings.EMAIL_HOST_USER send_mail('Contact Form', host_mail, messagecontainer, ['paulaldabaghwork@gmail.com'], fail_silently=False) return render(request, 'portfolio/index.html', { 'all_items': all_projects }) settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'paulogameplays12@gmail.com' EMAIL_HOST_PASS = '*******' EMAIL_PORT = '587' EMAIL_USE_SSL = False EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -
How to store excel files properly while using Django
I am switching a Python application with a classic GUI on the local machine to a cloud-based application on my Django website and would like to know the proper way to store my users files while processing the application. Currently I am using the FileField class within the models module to upload the files. I have the upload_to= parameter set to a new folder anmed spreadsheets/. I am wondering if this is the correct way to be storing files that will be processed and then discarded shortly after. Or should I be storing the files in memory (somehow) to make the process quicker and the code more simple? Current models.py: class Spreadsheets(models.Model): title = models.CharField(max_length=100) xls = models.FileField(upload_to='spreadsheets/') def __str__(self): return self.title Current views.py function handling the upload: @login_required def upload_sheet(request): if request.method == 'POST': ss_form = SpreadsheetForm(request.POST, request.FILES) if ss_form.is_valid(): ss_form.save() return redirect('sheet_list') else: ss_form = SpreadsheetForm return render(request, 'uploader/upload_sheet.html', { 'ss_form': ss_form }) Is this the best way to be handling this process? -
Using Selenium with Pytest for a Django 2.2 project running in Docker
I'm trying to use Pytest with the Django plugin and Selenium to test a Django 2.2 project that is running in Docker but I'm unable to get Selenium to connect to the test server. Selenium keeps returning "Address not available" when I try to connect using the setup below. My Docker compose is: version: '3' volumes: local_postgres_data: {} services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: local_django depends_on: - postgres volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" links: - selenium command: /start postgres: build: context: . dockerfile: ./compose/local/postgres/Dockerfile image: local_postgres volumes: - local_postgres_data:/var/lib/postgresql/data env_file: - ./.envs/.local/.postgres selenium: image: selenium/standalone-firefox ports: - "4444:4444" I've defined DJANGO_LIVE_TEST_SERVER_ADDRESS=django in my .django env file, and setup a fixture in conftest.py for the Selenium remote webdriver: import environ import pytest from selenium.webdriver import Remote from selenium.webdriver.common.desired_capabilities import DesiredCapabilities env = environ.Env() @pytest.fixture(scope='session') def selenium() -> Remote: driver = Remote( command_executor=env('SELENIUM_HOST', default='http://selenium:4444/wd/hub'), desired_capabilities=DesiredCapabilities.FIREFOX ) yield driver My test case, using my selenium fixture and the live_server fixture provided by Django-PyTest: import pytest class TestDashboard: def test_loads(self, selenium, live_server): selenium.get(live_server.url) assert My Site' in selenium.title raises OSError: [Errno 99] Address not available in the live_server constructor. Amongst other things, I've also tried to … -
What does pop()' do in Django Rest FrameWork?
I want to understand why this function is used for class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username', 'email', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user -
relation "app_passwordobject" does not exist. Djnago
After implementing my application for production, I see the following error: Environment: Request Method: GET Request URL: http://testtesttest.online/accounts/profile/ Django Version: 2.2.1 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'bootstrap3', 'crispy_forms'] Installed 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'] Traceback: File "/home/app/lib/python3.5/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) The above exception (relation "app_passwordobject" does not exist LINE 1: ...ate_created", "app_passwordobject"."user_id" FROM "app_passw... ^ ) was the direct cause of the following exception: File "/home/app/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/app/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/app/app/app/views.py" in profile 41. for object in query: File "/home/app/lib/python3.5/site-packages/django/db/models/query.py" in __iter__ 274. self._fetch_all() File "/home/app/lib/python3.5/site-packages/django/db/models/query.py" in _fetch_all 1242. self._result_cache = list(self._iterable_class(self)) File "/home/app/lib/python3.5/site-packages/django/db/models/query.py" in __iter__ 55. results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/app/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql 1100. cursor.execute(sql, params) File "/home/app/lib/python3.5/site-packages/django/db/backends/utils.py" in execute 99. return super().execute(sql, params) File "/home/app/lib/python3.5/site-packages/django/db/backends/utils.py" in execute 67. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/app/lib/python3.5/site-packages/django/db/backends/utils.py" in _execute_with_wrappers 76. return executor(sql, params, many, context) File "/home/app/lib/python3.5/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) File "/home/app/lib/python3.5/site-packages/django/db/utils.py" in __exit__ 89. raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/app/lib/python3.5/site-packages/django/db/backends/utils.py" in … -
I want to attach my form with the current logged in user as the applicant
i'm new to Django and still learning and right now I'm making a LMS in Django and I have a form that applies for a leave with the current logged in user as the applicant. But I don't understand how can I do it by default. If i let the user do it then the desired result is achieved but I don't want the user to see the field. i tried excluding and passing the user through views, but I wasn't able to. forms.py from .models import Employee, Leave from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm class Leave_Form(forms.ModelForm): class Meta: model = Leave fields = ['leave_Type', 'employee_leaves'] # exclude = ['employee_leaves'] leave_type_choice = ( ("Annual leave", "Annual leave"), ("Sick leave", "Sick leave"), ("Casual leave", "Casual leave"), ("Emergency leave", "Emergency leave"),) widgets = { 'leave_Type': forms.Select(choices=leave_type_choice, attrs={'class': 'form-control'}), } class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ] def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user class userReg_Form(forms.ModelForm): class Meta: model = Employee exclude = ['employee_name'] fields = [ 'employee_designation', 'employee_department', … -
How can I filter a Django queryset by the latest of a related model?
Imagine I have the following 2 models in a contrived example: class User(models.Model): name = models.CharField() class Login(models.Model): user = models.ForeignKey(User, related_name='logins') success = models.BooleanField() datetime = models.DateTimeField() class Meta: get_latest_by = 'datetime' How can I get a queryset of Users, which only contains users whose last login was not successful. I know the following does not work, but it illustrates what I want to get: User.objects.filter(login__latest__success=False) I'm guessing I can do it with Q objects, and/or Case When, and/or some other form of annotation and filtering, but I can't suss it out.