Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there anyway to delete object from queryset that already chosen in django?
Example: query = Test.objects.all() I want to delete the specific one. But before deletion I want to do some function like so. for q in query: if q.name == something: newq = q.relate_set.all() query.remove(q) # this remove not work -
Export User model into different app
I have a project with one app, where user, their posts and other models are located. Now I want to separate User model and put it into different app, called users. How should I do this correctly? User model looks like this: class ExternalUser(AbstractUser): class Meta: permissions = ( ('can_do_this', 'Permission1'), ('can_do_that', 'Permission2'), ..., ) I've done django-admin startapp users and copy-pasted user's model code into created app models.py. Then I tried makemigrations and it failed, showing: SystemCheckError: System check identified some issues: ERRORS: photogal.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'ExternalUser.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'ExternalUser.groups'. photogal.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'ExternalUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'ExternalUser.user_permissions'. users.ExternalUser.groups: (fields.E304) Reverse accessor for 'ExternalUser.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'ExternalUser.groups' or 'User.groups'. users.ExternalUser.user_permissions: (fields.E304) Reverse accessor for 'ExternalUser.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'ExternalUser.user_permissions' or 'User.user_permissions'. Adding related_name='+' to the old user model resulterd in: ERRORS: <class 'django.contrib.auth.admin.UserAdmin'>: … -
Django - app in subfolder
I've created new django app in a subdirectory using the command: python manage.py startapp appName subFolder/appName but if I try to add this app to INSTALLED_APPS at the end of the list I see the following error: ImportError: No module named appName Does anyone know what I am doing wrong ? -
Django - delete record view based on the same method as django admin?
id like a are you sure page like the one in django admin that enables users to delete records if they have perms. currently my view and templates are per the below (the template is modified from the admin template in the Django install) the view I think ive got half right, I just need to send the model_count and deleted_objects, but im not sure how to obtain them in my view? {% extends "home/sbadmin_base.html" %} {% load extras %} {% load static %} {% block content %} {% if perms_lacking %} <p>{% blocktrans with escaped_object=object %}Deleting the {{ object_name }} '{{ escaped_object }}' would result in deleting related objects, but your account doesn't have permission to delete the following types of objects:{% endblocktrans %}</p> <ul> {% for obj in perms_lacking %} <li>{{ obj }}</li> {% endfor %} </ul> {% elif protected %} <p>{% blocktrans with escaped_object=object %}Deleting the {{ object_name }} '{{ escaped_object }}' would require deleting the following protected related objects:{% endblocktrans %}</p> <ul> {% for obj in protected %} <li>{{ obj }}</li> {% endfor %} </ul> {% else %} <p>{% blocktrans with escaped_object=object %}Are you sure you want to delete the {{ object_name }} "{{ escaped_object }}"? … -
Django makemigrations permission denied for relation django_migrations
I have Python 2.7.14, Django 1.11 and PostgreSQL 9.4.15, and cannot run python manage.py makemigrations with it. It says: django.db.utils.ProgrammingError: permission denied for relation django_migrations But python manage.py migrate works just fine. Sudo's mode is not what I need. With sudo it has another mistakes -- it cannot import settings, but everything is fine with settings, because other developers don't meet this problem. What could be the issue? -
Django: make model field and foreign key unique together
I have the following model: class Locale (models.Model): """ Locale model """ locale_id = models.AutoField(primary_key=True) locale_name = models.CharField(max_length=800) magister = models.ForeignKey(Magister, on_delete=models.CASCADE) def get_name(self): return self.locale_name In the database, there must be exactly one locale-magister pair. To create each locale item, an administrator has to upload the locales. This is done via a bulk upload: try: lcl=Locale(locale_name = data_dict["locale_name"], magister = data_dict["magister "]) # lcl.full_clean() locales_list.append(lcl) rows+=1 if rows==INSERTNUMBER: try: Locale.objects.bulk_create(locales_list) locales_uploaded+=rows except IntegrityError as e: print("Error: locale bulk_create "+repr(e)) locales_list=[] rows=0 I tried using lcl.full_clean() in my bulk upload but I get a UNIQUE constraint failed: zones_locale.locale_name error and only about 1/2 of all locales upload successfully. I also tried using: def validate_unique(self, exclude=None): lcl = Locale.objects.filter(locale_id=self.locale_id) if lcl.filter(magister=self.magister).exists(): raise ValidationError("item already exists") But the same error occurs. I also tried using: class Meta: unique_together = (("locale_name", "magister"),) This did not work either. From what I can tell, the problem is that there exist locales with the same name that belong to different magisters. How can I allow locales with the same name to be uploaded while also enforcing the uniqueness of any given locale-magister pair? -
Why does this URL work in Django? It is not in urls.py
I've never worked with Django before. I'm taking over a Django project that was started by another programmer, who is now long gone. There is some magic happening in the code that I do not understand. For instance, in this file: urls.py I see this: from django.conf.urls import url, include from django.contrib import admin from django.core.urlresolvers import reverse_lazy from django.views.generic.base import RedirectView from django.conf import settings from core import views as core_views from sugarlab.search.views import validate_collections, create_document, delete_interest, rename_interest, add_url, my_interests from sugarlab.search.views import content, score, terms from django.contrib.auth.views import logout as django_logout from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ url(r'^admin/logout/$', django_logout, {'next_page': '/'}), url(r'^admin/', admin.site.urls), url(r'^accounts/logout/$', django_logout, {'next_page': '/'}), url(r'^accounts/', include('allauth.urls')), url(r'^unsecured/$', core_views.home), The confusing part is these two lines: from django.conf import settings url(r'^accounts/', include('allauth.urls')), "allauths" is some configuration set inside of this file: settings/common.py The data looks like this: 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.auth', 'django.contrib.sites', # Social/3rd party Authentication apps 'allauth.socialaccount.providers.linkedin_oauth2', 'captcha' Somehow this is a URL that actually works: /accounts/signup/ This file is completely blank: settings/__init__.py So I've two questions: how does "import settings" manage to magically import allauths? how does /accounts/signup/ map to an actual view? I don't see anything in urls.py, nor in settings, … -
DJANGO - Add field to default auth.User model - simpliest way
Looking for a simpliest way to add one field to Django's User model. I have two types of users with different fields - Company and Customer so I decided to create two types of UserProfiles. CompanyProfile and CustomerProfile. Every user has either CompanyProfile or CustomerProfile. To be able to filter and deciding which type is it, I want to add type field to User model. What would you suggest? Now I have UserProfile in the middle which seems to be overkill and it makes filtering, lookups and many other things less straightforward. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile') type = models.CharField(max_length=100, choices=settings.OBSTARAJME_USERPROFILE_TYPE_CHOICES) company_profile = models.OneToOneField('CompanyProfile', null=True, blank=True, on_delete=models.CASCADE, related_name='userprofile') customer_profile = models.OneToOneField('CustomerProfile', null=True, blank=True, on_delete=models.CASCADE, related_name='userprofile') I'm considering to create my custom User model. class User(AbstractBaseUser): type = models.CharField(max_length=100, choices=settings.OBSTARAJME_USER_TYPE_CHOICES) USERNAME_FIELD = 'username' but Django say's that there is no such field like username and I would like to avoid writing whole User model and all it's fields manually. EDIT I know that I could filter based on customerprofile__isnull=False so practically, I don't need type field at all but it doesn't look to be the best way. -
Django ModelForm: Display readonly boolean field as ModelAdmin().readonly_fields does
When in the admin class, a boolean field becomes read-only: class MyAdmin(admin.ModelAdmin): readonly_fields = ('a_boolean_field', ) it gets a great appearance using icons as described in this answer. If this boolean field is defined in a forms.ModelForm: class MyForm(forms.ModelForm): a_boolean_field = forms.BooleanField(disabled=True) How can I present it in the admin interface as if I had set it in the readonly_fields of the admin.ModelAdmin()? -
Django raw query "Schema does not exists"
I'm using django 1.7, and I wish to make us a Count with a conditional. This is possible in django 1.8 onwards, but I'm unable to upgrade. As such, I'm trying to write a raw query as detailed in this question.. Regretfully, I haven't yet managed. My query: a = Photo.objects.raw( 'select "photos_photo"."id" , ' 'COUNT(' 'DISTINCT ' 'CASE ' 'WHEN "point_substanceexistslabel"."substance"."name" = "fabric" then 1 else null end) as c ' 'FROM "photos_photo" ' 'LEFT OUTER JOIN "points_substanceexistslabel" ' 'on ("photos_photo"."id" = "points_substanceexistslabel"."photo_id")' ' GROUP BY "photos_photo"."id"' ) Running the query and trying to print a result raised the following error: ProgrammingError: schema "point_substanceexistslabel" does not exist -
How to get a list of many to many relation to the same model
I want to move the list of related messages with a given model to the variable in the view - this is the "related" field. At the moment I'm getting all the objects that are badly displayed on the site. Please any hint, thanks a lot. Model: class News(models.Model): title = models.CharField(max_length=500) subtitle = models.CharField(max_length=1000, blank=True) text = models.TextField() link_title = models.CharField(max_length=500) date = models.DateField(null=True) related = models.ManyToManyField('self', symmetrical=False, blank=True) class Meta: verbose_name_plural = 'news' ordering = ['-date'] View: class NewsDetailView(DetailView): model = models.News context_object_name = 'news_item' def get_context_data(self, **kwargs): context = super(NewsDetailView, self).get_context_data(**kwargs) context['related_news'] = models.News.objects.values_list('related', flat=True) return context -
Django sorl thumbnail not creating thumbnail but returning results
This worked locally and also on a prior digitalocean VM I made (I believe I also found a solution prior but I'm now putting the same site from a repo on Google Cloud). This is the code from the Image model as a function class Image(models.Model): grey_image = ImageField(upload_to="black", null=True, blank=True) ... def left_half_full(self, img_type='black'): if self.grey_image: image = self.grey_image im = PIL_Image.open(image.path) image = im.convert('RGB') else: image = self.image im = PIL_Image.open(image.path) image = im.convert('RGB') if img_type == 'black': image = get_thumbnail(image, '{0}x{1}'.format(image.width/2, image.height), crop='left') return image it uses get_thumbnail and PIL as shown from the imports here from PIL import Image as PIL_Image from sorl.thumbnail import get_thumbnail This is trying to see if it creates a file successfully In [1]: from gallery.models import Image In [2]: image = Image.objects.get(id=171) In [3]: image.left_half_full() Out[3]: <sorl.thumbnail.images.ImageFile at 0x7ff4dc348e50> In [4]: image.left_half_full().url Out[4]: '/media/cache/a1/6a/a16a3cc553a1a9390713b812004c02ee.jpg' In [5]: exit() (djangoenv) muiruri_samuel@pluscolor:~/webapp/revamp$ cd revamp/media (djangoenv) muiruri_samuel@pluscolor:~/webapp/revamp/revamp/media$ cd a1 -bash: cd: a1: No such file or directory (djangoenv) muiruri_samuel@pluscolor:~/webapp/revamp/revamp/media$ ls add_color background both colored_images crop full_both original timeline all black cache colorfest full_all images profile_pic uploads there's a problem where it seems to create a file but actually doesn't. Same goes for on the site … -
Import Django QuerySet to python list
I am trying to export my Django QuerySet to a python list but I couldn't achieve it. My data structure: [{'time_stamp': datetime.datetime(2017, 9, 30, 22, 0, 37, tzinfo=<UTC>), 'num': 1}, {'time_stamp': datetime.datetime(2017, 9, 31, 22, 0, 37, tzinfo=<UTC>), 'num': 2}] My attempt is: my_query=MyModell.objects.all().filter(time_stamp__range=('2017-10-01', '2017-10-02')).values('time_stamp').annotate(num_avg=Avg('number')).order_by('time_stamp') data=[i.num_avg for i in my_query] Unfortunately I got this error message when I tried to retrieve the num. AttributeError: 'dict' object has no attribute 'num_avg' My aim is to get a list like this a=[1,2] Thank you in advance! -
Disqus universal code for Django
I try to install disqus in my site, but nothing is displayed on the page. Site url - djaway.net This is my code: views.py def detail(request, slug): url = (reverse('content:detail', args=[slug])) content_info = Post.objects.get(slug = slug) return render(request, 'detail.html', {'content_info':content_info, 'url':url}) template.html <script> var disqus_config = function () { this.page.url = 'djaway.net{{ url }}'; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = '{{ url }}'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'djaway.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> Tag {{ url }} return right links, for example - /content/slug/ -
How can I randomize csrf token for django admin
I've just got vulnerability report that came from pentesters for my Django project. The report says my Django app is vulnerable to the BREACH ATTACK. SSL is active, cookies are flagged as a secure, session cookies are set as a secure. HTTP Compressions closed by the sysadmin it is controlled from the Nginx that I have no access. So gzip is close. Now I want to randomize csrf token for per client-side request for the django admin, especially for the login page. Is there a way to do this in settings.py in a simple way or do I have to write custom admin view? What is the best practice for this issue? -
How to add mouse click event in python nvd3?
I'm beginner to Data visualization in python, I'm trying to plot barchart (multibarchart) using python-nvd3 and django, It's working fine but my requirement is need to add click event to Barchart to get the data if user click the chart.I searched quite a lot but i couldn't found any reference or solution due to lack of documentation.Below i mentioned my code.Thanks in advance! In view.py: from django.shortcuts import render_to_response import random import datetime import time def demo_multibarchart(request): nb_element = 10 xdata = range(nb_element) ydata = [random.randint(1, 10) for i in range(nb_element)] ydata2 = map(lambda x: x * 2, ydata) ydata3 = map(lambda x: x * 3, ydata) ydata4 = map(lambda x: x * 4, ydata) extra_serie = {"tooltip": {"y_start": "There are ", "y_end": " calls"}} chartdata = { 'x': xdata, 'name1': 'series 1', 'y1': ydata, 'extra1': extra_serie, 'name2': 'series 2', 'y2': ydata2, 'extra2': extra_serie, 'name3': 'series 3', 'y3': ydata3, 'extra3': extra_serie, 'name4': 'series 4', 'y4': ydata4, 'extra4': extra_serie } charttype = "multiBarChart" data = { 'charttype': charttype, 'chartdata': chartdata } return render_to_response('multibarchart.html', data) in template page: {% load static %} {% load nvd3_tags %} <head> {% load_chart charttype chartdata "multibarchart_container" %} </head> <body> {% include_container "multibarchart_container" 400 600 %} </body> -
Django: using ConTeXT mkiv to output PDF
i have a small Django app to manage my patients data, and use LaTeX to output reports. It consists un a parent model called Patients and child models Consultation , StressEcho and so on. With LaTex this works without problems def courrier_pdf(request, pk2, pk1): entry = Courrier.objects.get(pk=pk2) source = Patient.objects.get(pk=pk1) context = dict({'courrier': entry, 'patient': source}) #buffer = BytesIO() template = get_template('courrier/courrier.tex') rendered_tpl = template.render(context, request).encode('utf-8') #Python3 only. For python2 check out the docs! with tempfile.TemporaryDirectory() as tempdir: # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['xelatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r i tried with this view in order to use ConTeXT but without success def courrier_mkiv(request, pk2, pk1): entry = Courrier.objects.get(pk=pk2) cource = Patient.objects.get(pk=pk1) context = dict({'courrier': entry, 'patient': cource}) # buffer = BytesIO() template = get_template('courrier/courrier.mkiv') rendered_tpl = template.render(context, request).encode('utf-8') with tempfile.TemporaryDirectory() as tempdir: process = Popen(['context', '--result', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'textput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r My feeling … -
django pagination can not direct to next page
I want to use pagination to list data from database,but when I click next page button,it shows “local variable 'context' referenced before assignment” I use filter to searching data from database first ,and use "REQUSET.POST" to get the data back。then send the data to another html。I think when I click next page,it will do all these again ,but I don't know how to code it。 Please help me to find out the problem,thank you! Below is my code: view.py from django.template.loader import get_template from django.template import RequestContext from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render,render_to_response from datetime import datetime from .form import DateRangeForm from .models import Post import tkinter.messagebox from tkinter import * from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger # Create your views here. def answer(): showerror("Answer", "Sorry, no answer available") def homepage(request): posts = Post.objects.all() now = datetime.now() context = {'posts':posts,'now':now} return render(request,'jishi.html',context) def showpost(request,times): template=get_template('post.html') ##posts=Post.objects.all().values('customer') posts=Post.objects.filter(pub_date__year=2018) now = datetime.now() html = template.render(locals()) return HttpResponse(html) def foobar(request): date_sel1 = request.POST.get('datetime1',None) date_sel2 = request.POST.get('datetime2',None) if date_sel1!=None: posts = Post.objects.filter(pub_date__range=(date_sel1,date_sel2)).order_by("pub_date","time") paginator = Paginator(posts,6,1) page = request.GET.get('page') try: customer = paginator.page(page) except PageNotAnInteger: customer = paginator.page(1) except EmptyPage: customer = paginator.page(paginator.num_pages) context={'posts':customer} return render(request,'sheet.html',context) html: {% extends 'balance.html' %} … -
django-filter for Boolean
I am a beginner to Django and doing a learning project which is a booking system. Can anyone recommend me an open source django project where I can check the source code for best practices. Thanks in advance When I use the code below, get method gets "on" or "off". How can it be "True"/"False"? Model.py class Mymodel(models.Model): ... is_xxx_approved = models.BooleanField(default=False,blank=False,null=False) is_contracted_by_yy= models.BooleanField(default=False,blank=False,null=False) is_zz_approved = models.BooleanField(default=False,blank=False,null=False) Filter.py class MymodelFilter(django_filters.FilterSet): class Meta: model = Mymodel fields = ['is_xxx_approved', 'is_contracted_by_yy', 'is_zz_approved'] exclude = [ 'name', 'address', 'phone', 'email',] filter_overrides = { models.BooleanField: { 'filter_class': django_filters.BooleanFilter, 'extra': lambda f: { 'widget': forms.CheckboxInput, }, }, } Template <div class="filter_index"> {% with field=filter.form.is_xxx_approved %} {{ field.label_tag }} {{ field }} {% endwith %} </div> <div class="filter_index"> {% with field=filter.form.is_contracted_by_yy %} {{ field.label_tag }} {{ field }} {% endwith %} </div> <div class="filter_index"> {% with field=filter.form.is_zz_approved %} {{ field.label_tag }} {{ field }} {% endwith %} </div> -
Django ORM: List of Foreign Key values
I have a table which has a column which stores a list of values. These values are basically Foreign key values of another table. This is the query I had written in SQL: SELECT COUNT(g.*) AS match_count, TEXT(g.created_at::DATE) AS created_at FROM groups g JOIN users u ON u.username = ANY (g.winner) WHERE g.created_at::DATE >= '2018-01-01' AND g.created_at::DATE <= '2018-01-20' AND g.winnings = 0 AND g.group_type = 'random' AND u.type = 'u' AND g.winner IS NOT NULL GROUP BY g.created_at::DATE I need to migrate this query into Django's ORM. How can I do a join with this array field (winner)? -
string Validation with xlsxwriter python
I am trying to put validations on excel file. I field should only accept characters or character with '_' symbol. The following code is only redistricting user to enter values more than length 10. import xlsxwriter wb = xlsxwriter.Workbook('staff.xlsx') ws = workbook.add_worksheet() ws.data_validation(1, 1, 10, 0, {'validate': 'length', 'input_title': 'Enter value', 'criteria': '<', 'value': firstname_max_length, 'error_message': 'Max Length is {0}'.format(10)}) Help me to validate values that should only except characters. Thanks. -
Custom django user registration
I am doing a user registration function this is viewsenter image description here this is formsenter image description here this is htmlenter image description here I found that if I change the name of the clean_password2 method in the views file to clean_password, I can not get the value of password2 in the form This is the wrong messageenter image description here My English is not very good I hope someone can help me Thank Thank Thank -
ValueError - Invalid literal for int() with base 10: 'add' Error Python 3.6
Here is my urls.py code, from django.contrib import admin from django.urls import path from . import views app_name = 'stories' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<pk>', views.DetailView.as_view(), name='detail'), # path('<story_id>/ratings', views.rating, name='rating'), path('add', views.CreateStory.as_view(), name='add-story'), ] I get above error when click the link, <li><a href="{% url 'stories:add-story' %}">Click me</a></li> I have no idea about this issue. Please help. -
celery + rabbitMQ - Cannot connect to broker
after successfully testing celery with the message broker (rabbitmq) installed locally (BROKER_URL = 'amqp://localhost') in a django app, i'm experiencing issues while connecting to broker: (projenv_py36) ➜ proj_pop_app (dev) celery -A proj worker --app=config.celery:app -l info [config] .> app: celeryProj:0x1068e7cc0 .> transport: amqp://rabbit:**@mq0.stg.eu-west-1.internal.my-company.eu:5672/vhost_proj_pop .> results: rpc:// .> concurrency: 8 (prefork) .> task events: OFF (enable -E to monitor tasks in this worker) [queues] .> celery exchange=celery(direct) key=celery [tasks] . config.celery.debug_task . process_session_task . sum_two_nrs [2018-01-24 11:30:08,197: ERROR/MainProcess] consumer: Cannot connect to amqp://rabbit:**@mq0.stg.eu-west-1.internal.my-company.eu:5672/vhost_proj_pop: [Errno 8] nodename nor servname provided, or not known. Trying again in 2.00 seconds... [2018-01-24 11:30:10,215: ERROR/MainProcess] consumer: Cannot connect to amqp://rabbit:**@mq0.stg.eu-west-1.internal.my-company.eu:5672/vhost_proj_pop: [Errno 8] nodename nor servname provided, or not known. Trying again in 4.00 seconds... note: the BROKER_URL value has been provided to me by my company devops team. I'm new to celery. Is there something that I can check to determine if is a celery configuration issue or if it's the broker not working properly? Thanks -
Django: Deleting query filters with button in template
I have a listview that displays a list of objects ('Speakers') that has a simple filter on top. In the template I've put the following code <form class="col-md-5" method="get"> <div class="input-group"> <select name="type" class="selectpicker" multiple> {% for type in types %} <option><a href="#">{{ type.name }}</a></option> {% endfor %} </select> <span class="input-group-btn"><button class="btn btn-gray" type="submit">Search</button></span> </div> </form> The types are supplied by the 'get_context_data' method from the listview, like so def get_context_data(self, **kwargs): data = super(SpeakerList, self).get_context_data(**kwargs) typelist = [x for x in Type.objects.all()] data['types'] = typelist return data The filters are handles in the 'get_queryset' method like so def get_queryset(self, **kwargs): qs = super(SpeakerList,self).get_queryset().filter(status=STATE_ACTIVE) types = self.request.GET.getlist('type', None) categories = self.request.GET.getlist('category', None) if types: qs = qs.filter(type__in=types) if categories: qs = categories.filter(categories__in=categories) return qs So far, so good. However, I want to display all of the selected filters in the template, with a 'remove' button behind them so users can remove specific filters. The template would then look something like this [ Type select dropdown ] . [ Day-speaker 'X'] . [Weekend-speaker 'X'] Object list Supplying the filters that are used is easy, I've added the following code to the get_context_data types_query = self.request.GET.getlist('type', None) data['types_query'] and used the following …