Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files are not served but accessible directly. Django, docker, nginx
I am trying to dockerize a django project with postgres, gunicorn and nginx. My problem is that static files are not served. However in browser console I see all static files being loaded properly (code 200). Also I can easily access any static file directly i.e. 127.0.0.1:8080/static/admin/.../base.css. Nginx doesn't show any errors in console either. What makes it even more strange for me, my redoc.yaml is loaded properly. Here is part of my settings.py with static: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Here is my main Dockerfile: FROM python:latest RUN mkdir /code COPY requirements.txt /code RUN pip install -r /code/requirements.txt COPY . /code WORKDIR /code CMD gunicorn api_yamdb.wsgi:application --bind 0.0.0.0:8000 Here is the Dockerfile for nginx: FROM nginx:latest COPY nginx/nginx.conf /etc/nginx/nginx.conf Here is the nginx.conf file: events {} http { server { location /static/ { root /etc/nginx/html/; } location / { proxy_pass http://web:8000; } } } And finally here is my docker-compose: version: '3.8' volumes: postgres_data: static: services: db: image: postgres:latest volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: build: . restart: always command: gunicorn api_yamdb.wsgi:application --bind 0.0.0.0:8000 volumes: - static:/static ports: - "8000:8000" depends_on: - db env_file: - ./.env nginx: build: context: . dockerfile: nginx/Dockerfile ports: - "8080:80" volumes: … -
Django Rest Framework serialized image returns absolute system url, and not amazon s3 url
I'm currently using django-storages with my application for hosting static and media files. I'm also using imagekit on image uploads to create multiple versions of an image needed across the application. The problem arises when trying to serialize the images urls. DRF returns a url such as http://127.0.0.1:8000/media/CACHE/images/categories/tilbeh%C3%B8r/tilbehor/2fbf015bd21dba581f5d306ed4248b47.jpg, and when opening this, its returns a completely blank page. What i really need is for it to return the "real" storage url, e.g. https://domain.s3.amazonaws.com/static/media/CACHE/images/categories/tilbeh%C3%B8r/tilbehor/2fbf015bd21dba581f5d306ed4248b47.jpg. S3 settings: # aws settings AWS_ACCESS_KEY_ID = 'secret' AWS_SECRET_ACCESS_KEY = 'secret' AWS_STORAGE_BUCKET_NAME = 'domain' AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), # os.path.join(BASE_DIR, 'frontend/dist'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_ROOT = 'static/media' MEDIA_URL = '/media/' models.py class Category(models.Model): def upload_content_file_name(instance, filename): """ Return the location of which to upload the file """ return os.path.join('categories/%s/' % instance.name.lower(), filename) name = models.CharField( _('category name'), max_length=255, unique=False ) ... image = models.ImageField( _('image'), upload_to=upload_content_file_name, help_text=_( 'Category image, should only be used on top level parents!' ), blank=True, null=True, ) image_default = ImageSpecField(source='image', processors=[ResizeToFill(375, 375)], format='JPEG', options={'quality': 90}) image_sm = ImageSpecField(source='image', processors=[ResizeToFill(640, 300)], format='JPEG', options={'quality': 90}) image_md = ImageSpecField(source='image', processors=[ResizeToFill(768, 366)], format='JPEG', options={'quality': … -
Django and ReactJS show how many visitor online now
I am trying to show how many visitors are on my website at this moment. i mean, I want to show many visitors are online at this moment, not how many users, Can anyone please suggest me what is the best way to do this? do i need to use WebSocket or there are any better option to do this? Can you please advise me regarding this? -
Searching query
I am searching for a query using python in Django, the terminal shows it is a success but the query does not show on the search result. I don't understand what to do please help. views.py functions we are to use to retrieve query templates page view -
How to run commands from docker-compose.yml to start couchdb
I have a webapp written in django which i need to connect with couchdb both are running on docker container. But i'm unable to figure out how to achieve this as there is no good material available for reference. I have tried the below codes but it is throwing the following error. docker-compose.yml version: '3' services: web: build: . command: python ./webapp/server.py volumes: - .:/code - ./webapp/static:/static networks: - couchserver_network depends_on: - couchserver couchserver: image: couchdb ports: - "5984:5984" command: curl -u rob:123456 -X PUT localhost:5984/_users environment: - COUCHDB_USER=rob - COUCHDB_PASSWORD=123456 volumes: - ./dbdata:/opt/couchdb/data networks: - couchserver_network networks: couchserver_network: driver: bridge Error thrown : 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0curl: (7) Failed to connect to localhost port 5984: Connection refused If i remove the line "command: curl -u rob:123456 -X PUT localhost:5984/_users" below error is thrown : couchserver_1 | {database_does_not_exist,[{mem3_shards,load_shards_from_db,"_users",[{file,"src/mem3_shards.erl"},{line,399}]},.... This is my Dockerfile : FROM python:3.6-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ Any sort of help is really appreciated One more query : what does the below lines do. I'm novice into docker and this is my first hands on … -
Django Weasyprint: Timeout error loading css while site is hosted on PythonAnywhere
I'm struggling to use Django WeasyPrint correctly while exporting a template to PDF. This issue only occurs on the PythonAnywhere version; using the view on localhost works as intended. Using any other view with the same stylesheets on PythonAnywhere also works fine. The errors occur when loading these two resources: <link rel="stylesheet" href="{% static 'css/boostrap4.5.2.css' %}"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> (note: I originally used a cdn for the bootstrap css but was finding a 403 forbidden error when WeasyPrint tried to get it instead, gave up on that one) Here's the error log when weasyprint tries to use it: Failed to load stylesheet at http://kirkmania.pythonanywhere.com/static/css/boostrap4.5.2.css : timeout: timed out Failed to load stylesheet at http://kirkmania.pythonanywhere.com/static/css/blog.css : timeout: timed out And here's the server log: SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /cv/export (ip 10.0.0.52) !!! uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during GET /cv/export (10.0.0.52) SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /static/css/boostrap4.5.2.css (ip 10.0.0.52) !!! uwsgi_response_write_headers_do(): Broken pipe [core/writer.c line 248] during GET /static/css/boostrap4.5.2.css (10.0.0.52) SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /static/css/blog.css (ip 10.0.0.52) !!! uwsgi_response_write_headers_do(): Broken pipe [core/writer.c line 248] … -
Django : Iphone picture localisation
I hope you're well. I'm creating a Picture model and I was wondering if there is any way store automatically in DB the picture localisation when an Iphone user upload it? class Picture(models.Model): catego = models.ForeignKey(Catego,on_delete=models.CASCADE,related_name="catego_pictures") user = models.ForeignKey(User, blank=True, null=True,on_delete=models.CASCADE,related_name='user_pictures') image = models.ImageField(null=True,blank=True, upload_to='nutri/') localisation = models.CharField(null=True,blank=True,max_length=300) publishing_date = models.DateField(auto_now_add=True) def __str__(self): return self.catego.title Have a good day, -
Add custom users with a specific attribute to the 'friends' list
I have implemented the logic of adding users to the 'friend list' from the whole list of users. models.py class VendorList(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='owner', on_delete=models.SET_NULL, null=True) @classmethod def add_vendor(cls, current_user, new_vendor): vendor, created = cls.objects.get_or_create( current_user=current_user ) vendor.users.add(new_vendor) @classmethod def remove_vendor(cls, current_user, new_vendor): vendor, created = cls.objects.get_or_create( current_user=current_user ) vendor.users.remove(new_vendor) views.py class VendorListView(TemplateView): template_name = 'event/vendor_list.html' def get(self, request): #form = EventItemModelForm() users = User.objects.exclude(id=request.user.id) vendor = VendorList.objects.get(current_user=request.user) vendors = vendor.users.all() args = { #'form': form, 'users': users, 'vendors': vendors } return render(request, self.template_name, args) def change_vendor_list(request, operation, pk): vendor = User.objects.get(pk=pk) if operation == 'add': VendorList.add_vendor(request.user, vendor) elif operation == 'remove': VendorList.remove_vendor(request.user, vendor) return redirect('/vendors/') It works and provides the list of all users whom I can add to the list. However, I need to filter this 'whole' list and display only users who have is_vendor attribute (similar to is_staff). Where should I filter users, in models or views? I have tried vendors = vendor.users.filter(is_vendor=True) which doesn't work. -
How to install Pip on a new Ubuntu upgrade
At the suggestion of others working on what was a functional Django project, I upgraded to a more recent version of Ubuntu (18). However, when I first try to run it it blows up at line 3 of the initial script module when asked to import django as a package. I tried pip -r requirements.txt, but the system said pip was an unknown package. I dropped down and used apt to load pip onto my machine (sudo apt-get pip), then tried using pip itself (pip update pip) which failed.: I also tried "pip install django", and got this: I would have thought an OS upgrade would not require re-installing all currently installed packages (seems like a no-brainer to do the work of installing everything that had been installed). But right now I am terribly stuck...obviously, having 'pip' let's you (at least) have a basic CLI tool. Any advice? -
modelformset_factory alter data after form submit
I have a modelformset_factory with some fields, and I combine it with other data from the PartRelation in a CreateView (like name, price, color ...). forms.py: class PartRelationForm: form = modelformset_factory(PartRelation, fields=("part", "qty", ), widgets={'part': forms.Select(), 'qty': forms.NumberInput()}) views.py: class PartsMixin(object): def post(self, request, *args, **kwargs): inquiry_form = InquiryModelForm(request.POST) parts_form = PartRelationForm().form(request.POST, prefix='part2inq') if inquiry_form.is_valid() and parts_form.is_valid(): i = inquiry_form.save() for form in parts_form: p = form.save(commit=False) p.inquiry = i p.save() return redirect ... return render ... class PartCreateView(PartsMixin, CreateView): model = Part the corresponding model (relation): class Part2InqRelation(CommonFunctionalities, models.Model): part = models.ForeignKey(PartBase, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") inquiry = models.ForeignKey(Inquiry, related_name='inq_part', on_delete=models.CASCADE) As soon as I have no qty or no part in my form, the is_valid() method always fails. How can I alter or delete the data in the PartRelationForm before the validation? I tried iterating through them and setting them None or an other approach with cleaned_data without success already. -
Django heroku connect read-write primary key issue
i am using djagno-heroku-connect library,salesforce and heroku connect link below for library https://github.com/Thermondo/django-heroku-connect So the problem that i am facing is i have one model that is marked as read-write, so which field should i make as primary key, I can't make sf_id as pk, because when i create one object it won't be there, as this is provided by salesforce As suggested in docs create external_id, but this won't be present if data from salesforce is synced back to my database let's say postgres There is one id field in postgres which is used by heroku connect and its suggested in docs on not to use that and i am not willing to user salesforce API for this, is there any approach to do this? Thanks in advance -
Form error message overrides model error message
I have a model: from django.contrib.postgres.fields import ArrayField class Profile(models.Model): phone = ArrayField(PhoneField(max_length=20, blank=True), verbose_name="Phone number", blank=True, error_messages={'item_invalid': 'Phone %(nth)s is invalid:'}) PhoneField is simple: class PhoneField(models.CharField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.validators.append(validators.PhoneValidator()) And the PhoneValidator: class PhoneValidator(): def __call__(self, value): phone = self.clean(value) if not (10 <= len(phone) <= 15): raise ValidationError('The phone number must contain from 10 to 15 digits.') def clean(self, value): return ''.join([d for d in value if d.isdigit()]) Then I created a simple form: class ProfileForm(forms.ModelForm): class Meta: model = Profile And when I fill something like 111,222 to the Phone field I expect to get the following error: Phone 1 is invalid: The phone number must contain from 10 to 15 digits.. But instead I get a generic error Item 1 in the array did not validate: without any details. I found out why does this happen. BaseModelForm overrides model error messages with form error messages: # django.forms.models def _update_errors(self, errors): # Override any validation error messages defined at the model level # with those defined at the form level. opts = self._meta ... for field, messages in error_dict.items(): if (field == NON_FIELD_ERRORS and opts.error_messages and NON_FIELD_ERRORS in opts.error_messages): error_messages = opts.error_messages[NON_FIELD_ERRORS] elif … -
Django: 404 when requesting static files in CSS but not in HTML
Static files are quite frustrating. Here is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_PATH, 'content'), ] # content/img/bg-mathead.jpg exists Now in my HTML, calling /static/ this way works: <div class="col-lg-6 order-lg-2" style="background-image: url('static/img/bg-masthead.jpg');"></div> [27/Aug/2020 18:39:24] "GET /static/img/bg-masthead.jpg HTTP/1.1" 200 693185 But the same call does not work in CSS: /* masterhead image bakgound */ header.masthead { position: relative; /*background-color: #343a40;*/ background: url("static/img/bg-masthead.jpg") no-repeat center center; background-size: cover; padding-top: 8rem; padding-bottom: 8rem; } [27/Aug/2020 18:42:23] "GET /static/css/static/img/bg-masthead.jpg HTTP/1.1" 404 1817 The same thing happens with relative paths, STATIC_ROOT, etc.. -
How to show select field with pre-selected data using django forms?
I've a django Form with 2 choices (yes and no), on my "create page" i can render the select field to save the data and it works just fine, when i try to use on the "edit page" the value is not pre-selected with the current value, how can i make the current value selected on the select input field? The form: class Form(forms.ModelForm): choose = forms.BooleanField( required=False, widget=forms.Select( choices=[(1, 'Yes'), (0, 'No')], attrs={'class': 'form-control'} ) ) class Meta: model = MyModel When i call the view to edit: class MyUpdateView( LoginRequiredMixin, SuccessMessageMixin, UpdateView, ): model = MyModel form_class = BenefitForm template_name = "my/template.html" success_url = reverse_lazy('my-url') success_message = 'Updated!' def get_object(self, queryset=None): data = super(MyUpdateView, self).get_object() if not data.user == self.request.user: raise Http404 # data.choose is False return data The HTML input will be always "1" (Yes) even tough the current value is "0" (No) The HTML: {{ form.choose }} -
I need to display paintings based on genre in a HTML template
Im doing a project thats a fine art gallery and have different pages based on each painting genre eg. Impressionism, Surrealism etc i duplicated the all paintings template and want to modify it so it only displays a chosen genre. Here is my all_paintings view def all_products(request): """a view to show all products including search""" products = Painting.objects.all() products = Painting.objects.filter(genre__name='genre') for p in products: print(p) context = { 'products': products, } return render(request, 'products/paintings.html', context) Id like to know if can add a filter like above to an existing class or make an entirely new class? and also what do i add to the HTML template so the specific genre paintings will be shown -
Creating a custom function in model to compare two foreign key max timestamps
In my Django project, I am attempting to create a custom model field that relies on comparing the values of two reverse foreign key timestamps. In this toy example, I operate some car dealerships. Cars are hired out to folks but need to be 'serviced' every time before they are hired out again. I am trying to add a 'currently_serviced' field into my Car model. A car is considered currently serviced if it has had an associated 'ServiceEvent' after the latest 'HireEvent'. I have been following the documentation on custom model fields but this doesn't help me navigate the trickiness of the reverse foreign keys and identifying the latest (before current time as I want to ignore future hires) timestamps. I have tried writing model manager classes and writing the logic into my views with F() comparisons, although would prefer as a DRY approach to declare the 'currently_serviced' attribute on the model itself as it would dynamically update as and when cars are hired and serviced and I would then be able to utilise this field in my views, such as by outputting the '% of serviced cars by dealership'. I am currently getting an attribute error, although I suspect … -
How to display content in grid format in django template when receiving dynamic data in terms of list from database?
In django model I have created a multiselectfield for suppose wishlist where user can select multiple wishes from the available choices. I am storing this data in comma separated format when it comes to displaying this on template things are pretty easy. But, I want this data to be displayed dynamically as one row with two columns and as soon as two columns are filled and there is more data left to be displayed logic should should have the capability to create a new row and display the remaining content on the django-template. For reference: # models.py class Wishlist(models.Model): wishlist = ( ('W1',"Buy a big masion"), ('W2',"Buy worlds fastest car"), ('W3',"Visit Europe"), ('W4',"Travel on bike to mountains") ) your_wishlist = MultiSelectField(choices=wishlist) # views.py def index(request): wishlist = Wishlist.objects.all() context = { "wishlist":wishlist } return render(request,'demolistingapp/index.html',context) # index.html {% load app_filters %} {% block content %} <h1>INDEX LISTING APP</h1> {% if wishlist %} {% for each_wish in wishlist %} {% with each_wish.your_wishlist|split:"," as wish %} {% for mywish in wish %} <p>{{mywish}}</p><br> {% endfor %} {% endwith %} {% endfor %} {% endif %} {% endblock %} I have registered the custom filter split which returns a list. I want the … -
How to check if the a query returns something or does not in django?
I am having this :items=order.orderitem_set.all() in my views.py that gives the items in a order. Currently this is under my cart view. The problem I am facing is that even if a persons cart is empty that is there are no items still the user can go to billing page. So is there any way in my views.py so that I can check whether there are item in items and return alert if not. -
How to fetch user profile from google after login
In my django project i create a function which redirect to user on google and ask for login by google account and user can login but it didn't know to fetch user profile from google and save in my database.So any can tell me what should i have to written in if part. def login(self,request): if (data): pass else: client_id = settings.GP_CLIENT_ID scope = "profile&response_type=code&state=jJzexptNPLLF&flowName=GeneralOAuthFlow" url = "https://accounts.google.com/o/oauth2/auth/identifier?client_id="+client_id+"&redirect_uri=http://localhost:8000/index/&scope="+scope return redirect(url) -
How to get objects which are related one to one to the user model
I'm creating an ecommerce website, currently loading the objects created by the customer to the cart template. My doubt is that how to get the customer which is related to the user by a one to one relationship? the error is Attribute error at /cart/ 'User' has no object 'customer' models.py : class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True) def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) views: def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] context = {'items': items} return render(request, 'store/cart.html', context) all i want to do is get the customer of the user. Thank you! … -
Django default image does not seem to load
Looked at a bunch of answers and tried to fix them, but my default image for profile.html does not seem to load. What I'm I doing wrong and how can I solve, in case it happens again? Thanks. This is my default image. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' profile.html {% extends "blog/base.html" %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{user.username}}</h2> <p class="text-secondary">{{user.email}}</p> </div> </div> <!-- FORM HERE --> </div> {% endblock content %} Relevant settings.py MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = '/media/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to Enforce Consecutive Numbering in "Through" Model Field
I'm using Python 3.7 with Django 3.1. I have two models: Text and Edition. There are a fixed number of texts, and users will be able to create editions in which they place these texts in whatever order they want. This is accomplished by means of a "through" model, EditionTextThrough, which keeps track of the position of a given text in a given edition: class EditionTextThrough(models.Model): text = models.ForeignKey(Text, on_delete=models.CASCADE) edition = models.ForeignKey(Edition, on_delete=models.CASCADE) position = models.PositiveSmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(372)]) class Meta: ordering = ['edition', 'position'] unique_together = ['edition', 'position'] This works fine. However, I want to enforce consecutive numbering for the "position" attribute, relative to the Edition it is paired with. Django's auto-generated IDs won't do this, because they are simply assigned to each row in the table, and don't start over with each Edition that is contained in it. Django's IDs can't do what I want for another reason as well: I want the "position" numbers to remain consecutive, even when some of them are deleted: position | edition_id | text_id 1 | uuid | 4 2 | uuid | 22 3 | uuid | 128 4 | uuid | 16 5 | uuid | 3 Now, if the … -
How to get clean pagination URL in Django?
https://docs.djangoproject.com/en/3.0/topics/pagination/ I'm referring this URL to add pagination to my app but I'm unable to get a clean URL. URL I get: localhost:8000/?page=2 URL I want: localhost:8000/page/2 urls.py urlpatterns = [ path('page/<int:pageno>', views.methodname, name='methodname') ] views.py def meth0dname(request, pageno=1): '''logic goes here''' By doing this I can access clean URL but pagination is not working. It keeps showing me the same landing page on page 2 and doesn't paginate further. -
How to get jsdoc to work with django template tags?
I have js files with {% %} template tags in them, which causes jsdoc to fail with ERROR: Unable to parse <path>: Unexpected token Is there any way to get django template tags to work with jsdoc or any other javascript doc generator? -
Django-Filter - Removing filter options that will return empty
I feel as if I am missing something pretty obvious here. I'm using Django-Filter to filter a ListView and it's working perfectly apart from the fact the options you get in the dropdown menus also include options that will return an empty search query. I've pre-populated my database with a bunch of data I'm going to need down the line yet isn't currently in use, the "Nations" and "Region" model's specifically. Models.py: class Nation(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=100, unique=False) class Region(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=100, unique=False) nation = models.ForeignKey(Nation, on_delete=models.PROTECT) class Business(models.Model): name = models.CharField(max_length=200) nation = models.ManyToManyField(Nation, blank=True,) region = models.ManyToManyField(Region, blank=True,) Filters.py: from business.models import Business, BusinessCategory from locations.models import Nation, Region import django_filters class BusinessFilter(django_filters.FilterSet): nation = django_filters.ModelChoiceFilter( field_name='nation', lookup_expr='isnull', queryset=Nation.objects.all().order_by('name') ) class Meta: model = Business fields = ['business_category', 'nation', 'region'] View.Py: class BusinessIndexView(ListView): paginate_by = 6 template_name = "business/index.html" context_object_name = 'all_business' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter']= BusinessFilter(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self): return Business.objects.filter(live=True).order_by('-id') Filter.html: {% load crispy_forms_tags %} <div class="mb-2"> <form method="get"> {{filter.form|crispy}} <button type="submit" class="btn btn-outline-success my-2 my-sm-0">Search</button> <a class="btn btn-outline-warning my-2 my-sm-0" href="{% url 'business:index' %}">Reset</a> </form> </div> Filters.py is where I know it is …