Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass queryset data with multiple relationships to a template in Django
I am working on a project with models that have a multiple OneToOne and OneToMany relationship. The main model, Listing, has 4 other models referring to it with a OneToOne model depending on the type. The other model ListingImages model has a OneToMany relationship with the Listing model. So, I want to pass data from the Listing model and any other related data from the ListingImages and the other 4 models as may be necessary to the template. To make this clearly understood here is the code from attached: models.py from django.db import models from django.contrib.auth.models import User from location_field.models.plain import PlainLocationField from PIL import Image from slugify import slugify from django.utils.translation import gettext as _ from django.core.validators import MaxValueValidator, MinValueValidator from listing_admin_data.models import (Service, SubscriptionType, PropertySubCategory, PropertyFeatures, VehicleModel, VehicleBodyType, VehicleFuelType, VehicleColour, VehicleFeatures, BusinessAmenities, Currency ) def current_year(): return datetime.date.today().year def max_value_current_year(value): return MaxValueValidator(current_year())(value) class Listing(models.Model): listing_type_choices = [('P', 'Property'), ('V', 'Vehicle'), ('B', 'Business/Service'), ('E', 'Events')] listing_title = models.CharField(max_length=255) listing_type = models.CharField(choices=listing_type_choices, max_length=1, default='P') status = models.BooleanField(default=False) featured = models.BooleanField(default=False) city = models.CharField(max_length=255, blank=True) location = PlainLocationField(based_fields=['city'], zoom=7, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expires_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True ) listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, … -
How to get into details view from another details view and get all the queryset in template properly?
I need to get into details view from another details view..but i can't pass the queryset clearly... In models: class Match(models.Model): mega_league = models.ManyToManyField('MegaLeague', blank=True) class MegaPricePoolBreak(models.Model): pass class MegaLeague(models.Model): price_pool_break = models.ManyToManyField(MegaPricePoolBreak, blank=True) In views: def league(request): match = Match.objects.all() context = { 'match': match, } return render(request, 'main/league.html', context=context) def league_detail(request, pk): match = get_object_or_404(Match, pk=pk) context = { 'match': match, } return render(request, 'main/league_detail.html', context=context) def league_detail_more(request, pk): match = get_object_or_404(Match, pk=pk) context = { 'match': match, 'title': 'select matches', } return render(request, 'main/league_detail_more.html', context=context) In league template, i pass {% url 'league_detail' match.pk %} to get queryset from Match into league_detail template and in league_detail template i pass {% url 'league_detail_more' match.pk %}---here is the main problem..it pass all the pk of Match but i need to pass match.pk and match.mega_league.pk to get queryset from Match into league_detail_more template.. In all template i use for loop..it's working...but to get specific pk query is not working.. It is working for league_detail template but not for league_detail_more template..in league_detail_more template pk pass from league_detail is not working. How can i get the all the queryset clearly for both template using match = get_object_or_404(Match, pk=pk)?? -
Why do I get a userId duplicate key error even though my model does not have user as the primary key?
I have an Interactions model which inherits from the predefine django user model, but I have the messageId to be the primary key. models.py: class Interaction(models.Model): messageId = models.TextField(max_length=5000,primary_key=True, unique = True) user = models.OneToOneField(User, primary_key = False, on_delete=models.CASCADE) reciever = models.TextField(max_length=5000,blank=True,default='') sender = models.TextField(max_length=5000,blank=True,default='') date = models.TextField(max_length=5000,blank=True,default='') subject = models.TextField(max_length=5000,blank=True,default='') label = models.TextField(max_length=5000,blank=True,default='') I have a dictionary called data which stores the information required. In views.py entry, created = Interaction.objects.get_or_create(messageId=data['id']) entry.user = request.user entry.sender = data['from'] entry.reciever = data['to'] entry.date = data['date'] entry.subject = data['subject'] entry.label = data['label'] entry.save() So while running the code there are messages with the same user but obviously different message ids user is not my primary key yet I keep getting the error djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "mainapp_interaction" SET "user_id" = %(0)s, "reciever" = %(1)s, "sender" = %(2)s, "date" = %(3)s, "subject" = %(4)s, "label" = %(5)s WHERE "mainapp_interaction"."messageId" = %(6)s Pymongo error: {'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: 5d02255b9ccf640b8c608ee1_mysitev6.mainapp_interaction index: user_id_1 dup key: { : 16 }'} -
How to save and display previously entered values in the form fields?
I have 2 forms per page. Here is one of them. $('form').submit(function(e) { e.preventDefault(); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action="" method="post"> <div> <label for="sum">Sum</label> <input id="sum" type="number"> <label for="currency">Currency</label> <select id="currency"> <option value="KZT">KZT</option> <option value="USD">USD</option> </select> </div> <div> <label for="term">Term</label> <select id="term"> <option value="1">1 month</option> <option value="3">3 months</option> </select> </div> <input type="submit" value="Submit"> </form> forms.py class CreditFilterForm(forms.Form): sum = forms.CharField() currency = forms.ChoiceField(choices = CURRENCY_CHOICES, ...) term = forms.ChoiceField(choices = PERIOD_CHOICES, ...) views.py CreitsListView(ListView): ... def get(self): little_form = CreditFilterForm(self.request.GET or None, prefix="little") class LittleFormView(FormView): form_class = CreditFilterForm prefix = 'little' def form_valid(self, form): ... Now, when the user entered the data and reloaded the page (without a submit), or when he simply closed the page and opened it again after some time - the entered data disappears. How can I save and display them? It is necessary to use caching. Or store the entered values in the database, and then substitute them? -
AWS Lambda Couldn't load 'Argon2PasswordHasher' algorithm library
I am using Zappa to deploy my backend application. I can login to the /admin normally while I am running local on OSX 10.14.2. Then I try deploy on AWS Lambda. Endpoint works fine. But /admin/ returns to me Couldn't load 'Argon2PasswordHasher' algorithm library I had followed this, but does not work. I have both of the dependencies according to official docs django[argon2]==2.2.2 argon2-cffi==19.1.0 zappa==0.48.2 I also check with Django issue. It has been solved 4 years ago I have never not got this issue while I was working with EC2 or any VM except AWS Lambda serverless Where am I wrong? -
Django Rest shows TemplateDoesNotExist
I am trying to learn django rest on a existing blog project. My project has a model named "BlogPost". There I have created an endpoint to GET the blogpost object. I can create a blog successfully from django admin, but whenever I give the url "http://127.0.0.1:8000/api/postings/1/", it shows the error "TemplateDoesNotExist at /api/postings/1/", while there isn't any error in my terminal. it shows "GET /api/postings/1/ HTTP/1.1" 500 85630. Can anyone help me where am I doing wrong? from django.conf import settings from django.db import models from django.urls import reverse class BlogPost(models.Model): # pk aka id --> numbers user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=120, null=True, blank=True) content = models.TextField(max_length=120, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user.username) views.py: from rest_framework import generics from postapp.models import BlogPost from .serializers import BlogPostSerializer class BlogPostRudView(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'pk' serializer_class = BlogPostSerializer def get_queryset(self): return BlogPost.objects.all() Here is the serializer: from rest_framework import serializers from postapp.models import BlogPost class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = BlogPost fields = [ 'pk', 'user', 'title', 'content', 'timestamp', ] My urls.py inside the api from .views import BlogPostRudView from django.urls import path urlpatterns = [ path('<int:pk>/', BlogPostRudView.as_view(), name='post-rud') ] and my urls.py inside the project: from django.contrib import … -
ValueError The QuerySet value for an exact lookup must be limited to one result using slicing on django views
am Getting this error i cant figure a way to solve it here are the views.py class SellerTransactionListView(ListView): model = Transaction template_name = "sellers/transaction_list_view.html" def get_queryset(self): account = SellerAccount.objects.filter(user=self.request.user) if account.exists(): products = Product.objects.filter(seller=account) return Transaction.objects.filter(product__in=products) return [] template transaction_list_view.html {% extends "base.html" %} {% block content %} <h1>Transactions</h1> <ul> {% include "sellers/transaction_list.html" with transaction_list=object_list %} </ul> {% endblock %} and the transaction_list.html <table> <thead> <th>Product</th> <th>User</th> <th>order_id</th> <th>Sale Total</th> <th></th> </thead> <tbody> {% for trans in transaction_list %} <tr> <td>{{ trans.product }}</td> <td>{{ trans.profile }}</td> <td>{{ trans.order_id }}</td> <td>{{ trans.amount }}</td> <td>{{ trans.timestamp|timesince }} ago</td> </tr> {% endfor %} </tbody> </table> if i change the transaction_list_view.html the include part to {% include "sellers/transaction_list.html" with transaction_list=transactions %} the error disappears but the transactions are not showing. -
How can i update a django template in real time?
In this template i'm retrieving the price of Bitcoin from an API. At the actual moment, the price will be updated only when the page is refreshed, while i would like it to be updated without refreshing the whole page, dynamically. This is my view: def home(request): symbol = "BTCUSDT" tst = client.get_ticker(symbol=symbol) test = tst['lastPrice'] context={"test":test} return render(request, "main/home.html", context ) And the template's line looks something like this: <h3> var: {{test}} </h3> There are two problems here: 1) From the little i know, Django itself is not asynchronous, so i need to find a way to update that part of the template in real time, without having to refresh the whole page. 2) At the actual moment, the API is requested when the page is opened/refreshed, but to stream the price, it should be always running. I tried this (awful) solution: add a while true in the view, but of course it broke my code, executing only the part the while statement. Any advice is appreciated :) -
saving dynamic form elements in database
I have a dynamic form inputs in UI which users can add rows or remove but I do not have an idea how to store this elements in DB. I have looked at some answer which was done with function based views but I am using CBV. my code looks like this models.py class Item(models.Model): item_name = models.CharField(max_length=200) sku = models.CharField(max_length=200) barcode = models.CharField(max_length=200) category = models.CharField(max_length=200) views.py class ItemCreateView(CreateView): model = Item template_name = 'items/item_form.html' fields = ['item_name', 'sku', 'barcode', 'category'] def form_valid(self): #some code here here is the my code this input field can be dynamic according to number of item. Then how can I store them with CBV? and Which way is better to save in this condition? Thanks a lot in advance! -
Not able to access data using 'categories.products .all ' in template view. Django Models with foreign key
I have models that have relation using a foreign key. class Cat1(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length = 100) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50) productId = models.AutoField(max_length=50,primary_key=True) productType = models.CharField(max_length=50) matType = models.CharField(max_length=100,default='Use comma , to seperate multiple materials') seller = models.ForeignKey(User, related_name='sellers',on_delete=models.CASCADE,default='NA') cat_1 = models.ForeignKey(Cat1,related_name='catlevel1',on_delete=models.CASCADE,default='NA') Then i have my views of the page. where i need to display all the product from the category i have clicked on. My View is : def cat_products(request,pk): categories = get_object_or_404(Cat1, pk=pk) #here the categories get the category i clicked on homepage. products = Product.objects.all() return render(request, 'products.html', {'categories':categories,'products':products}) Then products.html is: <!--Full Code not shown for easy understanding--> {% for prod in categories.products.all %} {{categories.name}} <tr> <td>{{ prod.name }}</td> <td>{{ prod.matType }}</td> <td>0</td> <td>0</td> <td>0</td> </tr> {% endfor %} So basically categories is the the name that can be used to access current category.Products is the list of all products. I have tried this code above which yield no result. <!--Full Code not shown for easy understanding--> {% for prod in products %} {{categories.name}} <tr> <td>{{ prod.name }}</td> <td>{{ prod.matType }}</td> <td>0</td> <td>0</td> <td>0</td> </tr> {% endfor %} i have tried only printing all the products {% … -
How to pass multiple product ids while object creation?
I have a service master class in which the user can add multiple products. I'm unable to figure out how to do it? One possible idea for me was to use the Many2Many field but I wanted to know is there any other way? I also thought about creating separate relation table in which I will store the service id and the product id but my question is how do I pass that in the response after creating the service? -
How to set a callable function to AutoField default attribute?
I'm trying to overwrite the pk of my models to use a random generator. Here's the model field: pk = models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', default=genkey) and the keygenerator: def genkey(): return random.randrange(1,142857) So, I would like to make the autofield to execute the genkey function as much as possible until it gets a non-used key. Is there an attribute that I didn't find or do I need to code it in the generator (by getting all the used keys) ? My main goal is to make a generator as generic as possible, not define a custom generator for each model. -
How to change default web location from root user directory to another user directory in Nginx?
I'm new to Nginx I've created Django app and deployed in root user home directory due to some reasons I need to move it to some other user home directory; I've changed everything but when i access to the website it is still pointing to app from same root user directory. Previously /etc/uwsgi/sites/djangoproject.ini [uwsgi] project = djangoproject username = root base = /%(username) chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 uid = %(username) socket = /run/uwsgi/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true Currently: /etc/uwsgi/sites/djangoproject.ini [uwsgi] project = djangoproject username = jenkins base = /scratch/%(username) chdir = /home/%(username)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 uid = %(username) socket = /run/uwsgi/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true Currently: /etc/nginx/nginx.conf #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; server { listen 8001; listen svcpjanjana.nms.fnc.fujitsu.com:8001; server_name svcpjanjana.nms.fnc.fujitsu.com; location = favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/jenkins/djangoproject; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/djangoproject.sock; } } Previously: /etc/nginx/nginx.conf #user nobody; … -
how can i check whether a Stripe customer already has a specific card before adding a new one in django python
I want to store multiple card on stripe for customer.In this, customer try to add new card on stripe at that time check if this card store or not in django python I use below code to add customer card on stripe card = stripe.Customer.create_source( 'customer_stripe_id' source =request.POST['stripeToken'] ) -
How to chain filters / filtering two object lists in Django?
Need some help in writing a filter query. I have the following Models: class Product: pid name class WishList: user items = models.ManyToManyFields(Product) class Stock: storeid product = models.ForeignKey(Product) aisle segment I need to : Get the Current Logged in USER Get the Products in the User's WishList Search for those Products in the 'Stock' for a Particular StoreID passed as argument and display them along with their Aisle This is what I did: user = request.user wish_list = get_object_or_404(WishList, user=user) list_items = wish_list.items.all() store_stocks = Stock.objects.filter(storeid=(passed StoreID)) list_stocks store_stocks.filter(store_stocks.pid=list_items.pid) But it doesn't work and I need some help. I get the Error as: list_stocks = store_stocks.filter(store_stocks.pid=list_items.pid) | SyntaxError: keyword can't be an expression -
Django allauth social signup with custom user-model + form
I'm trying to use django-allauth package to handle my social login/signup with google oauth2 authentication. What I'm trying to do is after the google authentication pass the new user to a custom signup form with some custom fields to my user model and only after that to save the user model. Everything I try just ignore my custom form and save the user without passing my form. It would be awesome if you can list the necessary elements in the project to make this thing work. Thanks in advance, Itai -
How do I make <a href> link to open in a new tab but in an iFrame part of another template?
I have created a Django web app which throws document recommendation to users based on their search query; the next thing I am trying to achieve is to able to make users open these recommended documents in a new tab but in an iFrame which would part of another template. Also, I just want to use HTML and Python to achieve this result. Till now, I am just able to open the documents in a new tab which is not part of my Django framework <html> <body> {% for document in Documents %} <a href = "{link to the corresponding document on my system}" target = "_blank"> <p><font color = "blue"><b>{{ document }}</b></font></p> </a> {% endfor %} </body> </html> The above code loops through the list of recommended documents generated by model and prints their hyperlinked names on an HTML page. These links just open the document in a new tab but I want them to open in an iFrame on a new template which is part of my Django framework. -
Easiest and fastest way to migrate boto based django-photologue collections on S3 to the newer boto3?
There is a bug (https://github.com/boto/boto/issues/3837) in boto that prevents it from functioning properly with S3 in production (althought it does work in development). How would one go about installing a forked version of boto to the existing project or perhaps migrating the populated storages to boto3? Is it even possible without reuploadin/retaggint my entire collection? and even so, does django-photologue work with boto3? I'm linking to this code from my settings.py, as described in the tutorials for django-photologue s3 storage: # S3Boto storage settings for photologue example project. import os DEFAULT_FILE_STORAGE = 'example_storages.s3utils.MediaS3BotoStorage' STATICFILES_STORAGE = 'example_storages.s3utils.StaticS3BotoStorage' AWS_S3_HOST = 's3-us-west-2.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'CacheControl': 'max-age=94608000', } try: # If you want to test the example_project with S3, you'll have to configure the # environment variables as specified below. # (Secret keys are stored in environment variables for security - you don't want to # accidentally commit and push them to a public repository). AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME'] except KeyError: raise KeyError('Need to define AWS environment variables: ' 'AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_STORAGE_BUCKET_NAME') # Default Django Storage API behavior - don't overwrite files with same name AWS_S3_FILE_OVERWRITE = False MEDIA_ROOT = … -
Django + Python failed connecting to PostgreSQL server in a local machine in same network
I have a PostgreSQL running in a linux machine inside my local network. The IP address of this machine in my local network is 192.168.0.115. I am able to connect to this server using the Valentina Studio client on my Macbook Pro with username postgres and password postgres, and IP address 192.168.0.115 (address of the linux machine running the PostgreSQL server in my local network). Also in my Macbook Pro, I have a Django application setup to connect to the PostgreSQL server using the same IP address, username and password as the Valentina Studio, but when I run python3.7 manage.py migrate, I get an error message saying it could not connect to server: When I change my Django application database configuration to use SQLite, the migration runs well and everything works well. I disabled the firewall of the linux machine running the PostgreSQL server, just to make sure. (I don't think this is the problem though, because my Macbook Pro is able to connect to that server using the Valentina Studio client). If I run the same Django application INSIDE THE POSTGRESQL SERVER LINUX MACHINE, using 127.0.0.1 IP address, it works. If I change the IP address to 192.168.0.115 (IP … -
I can't submit the form even if it is valid
I have used CreateView for a form, but the form is not being submitted even when it is valid. It just redirects to the same page again.I am using the form_id for from fields, and it even submitted once or twice but now it is just not working. models.py class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) views.py class centre(CreateView): fields = ('name','address','contact','phone',) model = Centre success_url = reverse_lazy("NewApp:logindex") def form_valid(self, form): form.save() return super(centre, self).form_valid(form) template : <form method="POST"> {% csrf_token %} <div class="col col-md-12"> <div class="fieldWrapper" > {{ form.name.errors }} <div class="form-group col col-md-3"> <label for="{{form.name.id_for_label}">Centre Name</label> <input type="text" placeholder="Centre Name" name="name" maxlength="250" id="id_name" style="box-sizing: border-box; width:500px;"> </div> </div> <div class="form-group col col-md-3" style="float:right; margin-top=-80px;width=200%"> <label for="{{form.address.id_for_label}" style="margin-left:200px;width:200%;white-space:nowrap;">Centre&nbsp;Address</label> <input type="text" placeholder="Centre Address" name="address" maxlength="250" id="id_address" style="width:500px; margin-left:200px;"> </div> </div> <br> <br><br><br> <div class="col col-md-12"> <div class="form-group col col-md-3" style="float:right; margin-top=-80px;"> <label for="{{form.contact.id_for_label}" style="margin-left:200px;width:200px;white-space:nowrap;">Contact&nbsp;Person</label> <input type="text" placeholder="Contact Person" name="address" maxlength="250" id="id_contact" style="width:500px; margin-left:200px;"> </div> {{ user_form.non_field_errors }} <div class="fieldWrapper" > <div class="form-group col col-md-3" > <label for="{{form.phone.id_for_label}" style="white-space:nowrap;">Contact&nbsp;Number</label> <input type="text" name="phone" … -
django-zappa: Error loading psycopg2 module: libpq.so.5: cannot open shared object file: No such file or directory
When trying to deploy a Django project using django-zappa, I get the following error in the zappa tail output: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: libpq.so.5: cannot open shared object file: No such file or directory I've made sure to include the psycopg2 module in the requirements file: psycopg2==2.8.3 It's installed in the virtual environment that's active while running the zappa deploy command. I'm running on Linux and had to install libpq-dev via apt before even being able to pip install psycopg2 as I received an error before, saying that libpq was missing on the system (similar to the above error, I guess). How can I overcome this error? Thanks! -
"Is there any repository or documentation with instructions to run docker created by django oscar?"
I am working with Django oscar docker and in the meantime found that Django oscar sandbox not installing as expected. So I want to get rid of all hassles and want to run it in docker. When I went through Django oscar GitHub repository and their docker hub profile I found no instructions and guideline to run it. I have also created an issue to their GitHub profile and they suggested me to ask questions on StackOverflow or google group. For a faster response, I am asking help from this community. Hope you guys will come up. This is my github issue link https://github.com/django-oscar/django-oscar/issues/3051 -
How to automatically substitute a variable in the admin page at Django 1.11?
There is a City model. It has a name field. I need to somehow substitute this variable in the admin page in the text field at another models. Suppose need to write the phrase "Your location is Paris", but it is necessary that the name of the city was substituted by itself (since there are many cities, and prescribing for each is not an option at all). That is, there must be something like "Your location - {City.name}" - that is, a certain city is pulled out of the database and substituted into this line. Writing a prepared phrase in templates is not an option. I need to do this through the admin panel. Using selects is also not an option, since the number of variables, their location and phrases are not known in advance. For example, the phrase "The capital of France - Paris" (The capital of {Country.name} - {City.name}). I understand, need to create a shortcode_name field and somehow process it in the view? I'm use Django 1.11 -
Unknown interpreted text role "setting" with Django docstring and Sphinx
I'm documenting a Djagno 2.2 application. The Django documentation states linking to the settings as Add :mod:`django.contrib.auth` to your :setting:`INSTALLED_APPS`... In my documentation, The statement is The length is defined in the :setting:`URL_ID_LENGTH` When generating the documentation using Sphinx make html Gives WARNING :docstring of app.models.Class.function:4: WARNING: Unknown interpreted text role "setting". I have sphinx.ext.intersphinx added to the conf.py of Sphinx. -
How can I filter related field in django?
Say I have the model User which has a many-to-many relation with the model Company; and the model UserType, which is connected to both User and Company. Like this: class User(models.Model): name = models.TextField() class Company(models.Model): name = models.TextField() users = models.ManyToManyField(User, related_name="companies") class UserType(models.Model): name = models.TextField() company = models.ForeignKey(Company, related_name="user_types") users = models.ManyToManyField(User, related_name="user_types") I wanna find all Users in a Company, which is simple enough: User.objects.filter(companies=some_company). However, I also wanna filter the user_types field on the returned users objects, so that only UserType objects connected to the given Company is returned. To explain it with code, this should return true: def check_user_types(users, company): for user in users: for user_type in user.user_types: if user_type.company != company: return false return true How would I do this?