Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Upload and process excel file in inline forms
I have a django form and an inline formset attached to it as given below: class Sales_form(forms.ModelForm): class Meta: model = Sales fields = ('User','Company','date','Address','billname','GSTIN','PAN','State','Contact','DeliveryNote','Supplierref','Mode', 'ref_no', 'Party_ac', 'sales', 'Total_Amount') widgets = { 'date': DateInput(), } class Stock_Totalformsales(forms.ModelForm): class Meta: model = Stock_Total_sales fields = ('stockitem', 'Quantity', 'rate', 'Disc','gst_rate', 'Total') Sales_formSet = inlineformset_factory(Sales, Stock_Total_sales, form=Stock_Totalformsales, extra=6) I want upload and process file from excel into this specific form... How do I do that in django? I know how to process a single model but I have no idea how to process two model at the same time... Previously I have used third party app like django-import-export and openpyxl. But, I have done for single model. Is there any any third party app for this?Or any other way to perform this? -
Issue with DatetimeField and strftime
I would like to convert my DateTimeField : download_date = models.DateTimeField(verbose_name=_('download date'), null=True) with strftimelike this : from datetime import datetime, timedelta last_download_temp = Download.objects.exclude(download_date=None).order_by('-download_date')[0] print(f"Last download temp : {last_download_temp}") last_download = last_download_temp.strftime('%Y-%m-%d %H:%M:%S') print(f"Last download : {last_download}") It returns : Last download temp : 2019-01-07 09:10:01.509484+00:00 File "/home/Bureau/Projets/Publication/publication/src/web/freepub/views/main.py" in get_context_data 236. last_download = last_download_temp.strftime('%Y-%m-%d %H:%M:%S') Exception Type: AttributeError at /freepub/stats Exception Value: 'Download' object has no attribute 'strftime' I don't find why it doesn't work ? Do I need to convert my last_download_temp before ? -
How to add string to autofield/primary key using Django
I have created a model with few fields like name, type, date and Request_Id Whenever I insert a new record in database, I want to append a string eg: REQ to id (primary key/autofield) for request_Id field. EG: REQ_1, REQ_2, REQ3 Any suggestions to achieve this ? Thanks. -
How to add digital signature or signature image in PDF using python/django?
I am trying to insert an signature image in a contract pdf like the way we do in adobe acrobat in offline.I tried to install a 3rd party package signpdf 0.0.3 but it seems not maintained anymore and not working in python 3.6 and django 2.0. Is there any way i can achieve the desired result ? -
Celery beat task are not scheduling
I want to store my celery task in mongodb database and from database i want to pick task in execute according to schedule time, for i am using github project which allow me to do this. here is link https://github.com/zmap/celerybeat-mongo I am able to store my tasks in mongodb database, but mongoscheduler mentioned in project is not executing tasks, it execute tasks only first time when task in registered after that nothing is happening. Please take a look, I wasted 3 days but didn't find anything wrong with my code. settings.py TIME_ZONE = 'UTC' CELERY_BROKER_URL = 'mongodb://localhost:27017' CELERY_RESULT_BACKEND = "mongodb" CELERY_MONGODB_SCHEDULER_DB = "celery" CELERY_MONGODB_SCHEDULER_COLLECTION = "schedules" CELERY_MONGODB_SCHEDULER_URL = "mongodb://localhost:27017" CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' tasks.py from __future__ import absolute_import, unicode_literals import celery, json from rest_framework.exceptions import ValidationError from .serializers import PeriodicTaskSerializer from celery import task, shared_task @task def TestTaskOne(): msg = "DEFAULT TASK IS WORKING......" return msg @task def return_dict(): DEFAULT_CRONTAB = { "minute": "00", "hour": "00", "day_of_week": "*", "day_of_month": "*", "month_of_year": "*" } schedule = dict() schedule['name'] = 'TestTaskOne' schedule['task'] = 'UserAPI.tasks.TestTaskOne' schedule['enabled'] = True schedule['crontab'] = DEFAULT_CRONTAB schedule['crontab']['minute'] = '*/1' schedule['total_run_count'] = 0 schedule['run_immediately'] = True serializer = PeriodicTaskSerializer(data=schedule) if serializer.is_valid(): print('Inside serializers is … -
Tensor conv2d_1_input:0, specified in either feed_devices or fetch_devices was not found in the Graph error
I am working on a django application which contains a form for uploading an image and filling in some description about the image. Once the image is uploaded an image classifier run on the image and tries to fill some parts of the form automatically. This is the code so far upload_item.html template {% block content %} <div class="row justify-content-center"> <div class="col-6"> <center> <h2>Upload item</h2> <p>Upload the image before filling out the form. Our neural network will try to predict most fields after the image is uploaded</p> <div class="upload-btn-wrapper"> <form action="{{ request.build_absolute_uri }}image_classification/" method="POST" enctype="multipart/form-data" class='first_form'> {% csrf_token %} <input type="file" name="file" id="file" class="inputfile" /> <label for="file" class="btn btn-outline-dark btn-sm select">Choose a file</label> <input class='btn btn-primary btn-lg btn-block' type="submit" value="Upload image" /> </form> </div> </center> <div class="card mb-5 mt-3"> <div class="card-body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form_des|crispy}} <button type="submit" class='btn btn-primary save_btn'>Save item</button> </form> </div> </div> </div> </div> {% endblock content %} In the above template there are two forms. One is a form for uploading the image and the other is a form for the image description. I am facing another issue because of this but that is for another question. The views look like this views.py def … -
How to pass template parameter through widget attribute
i want to pass context from widget attr form. example self.fields['accesses'].widget.attrs['value'] = '{{company.id}},{{functionality.id}}' class ACLFormAdd(forms.Form): accesses = forms.BooleanField(required=False) def __init__(self, *args, **kwargs): super(ACLFormAdd, self).__init__(*args, **kwargs) self.fields['accesses'].widget.attrs['name'] = 'accesses' self.fields['accesses'].widget.attrs['value'] = '{{company.id}},{{functionality.id}}' -
FieldError: Unsupported lookup 'unaccent' for CharField or join on the field not permitted
I am getting FieldError: Unsupported lookup 'unaccent' for CharField or join on the field not permitted. Any help is appreciated. Any ideas? #template <form class="navbar-form navbar-left" method="GET" action="{% url 'search' %}" value="{{request.get.q}}"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" > </div> <button type="submit" class="btn btn-default">Submit</button> </form> #views.py def Search(request): queryset_list=Testimony.objects.all().order_by('timestamp') if request.user.is_staff or request.user.is_superuser: queryset_list=Testimony.objects.all() print('1') if request.method=='GET': query=request.GET.get("q") print('2') queryset_list = Testimony.objects.filter( Q(title__unaccent__lower__trigram_similar=query)| Q(body__unaccent__lower__trigram_similar=query)| Q(username__unaccent__lower__trigram_similar=query) #Q(firstname__unaccent__lower__trigram_similar__icontains=query) ).distinct().order_by('timestamp') print('3') paginator = Paginator(queryset_list, 20) page_request_var="page" page=request.GET.get(page_request_var) try: queryset=paginator.page(page) except PageNotAnInteger: queryset=paginator.page(1) except EmptyPage: queryset=paginator.page(paginator_num.pages) print('4') context={ "object_list": queryset, "title":"list", "page_request_var":page_request_var, } return render(request, 'search.html', {'queryset_list':queryset_list}) Traceback points to: Q(username__unaccent__lower__trigram_similar=query) -
Django-Celery creates and destroys new pid abruptly even when old process works smooth
Celery process is getting duplicated unexpectedly and closes the new process by its own. There occur no issues with the old process still. Any idea on this, how to set/limit process to any single PID, without fluctuations -
Not getting fields and their values which are ManyToManyField type
I have a django model named Persona: class Persona(models.model): name=models.CharField(max_length=100,primary_key=True) pages_visited = models.ManyToManyField(Page) items_searched = models.ManyToManyField(ItemsSearched) visits = models.IntegerField(null=True,blank=True) connect = models.CharField(max_length=True,null=True,blank=True) image = models.ForeignKey('Image',on_delete=models.CASCADE) def __str__(self): return self.name I have an object for this model: <QuerySet [<Persona: aman>]> Now when i am trying to get the values of all fields for this object i can see all fields and their corresponding values except fields which are ManyToManyField type. I get the following result when i execute this : Persona.objects.filter(name='aman').values() <QuerySet [{'visits': None, 'image_id': 3, 'name': 'aman', 'connect': 'call'}]> I cannot see 'items_searched' and 'pages_visited' fields and their corresponding values though when i log into admin i can see them. -
how to pass post parameter in Django rest swagger?
I have integrated swagger with django rest framework, but the swagger docs does not create a input box to post data for post request. I am using Function based views with decorator(@api_view) @api_view(['GET','POST']) @permission_classes((AllowAny, )) @renderer_classes([OpenAPIRenderer, SwaggerUIRenderer]) def preferences(request,format=None): try: "logic starts here " in urls.py i have added: schema_view = get_swagger_view(title='API') path('', schema_view, name="schema_view"), in settings.py : SWAGGER_SETTINGS = { 'USE_SESSION_AUTH': False, 'JSON_EDITOR': True, 'api_version': '0.1', 'enabled_methods': [ 'GET', 'POST', ], 'SECURITY_DEFINITIONS': { "api_key": { "type": "apiKey", "name": "Authorization", "in": "header" }, }, } But, when i open the api url i'm getting something like this (in image) where i'm unable to pass the parameters through post what can be the problem here?is there any other changes to be done ? -
Doesn't not render my data as graph format in DJango
I am new to dJango and I want to visualize my data which is stored on database in django. By following the tutorial on the website, I successfully implemented the code which allows me to store the data into database. Next step is to visualize the data into html web pages. I tried it but failed to visualize it. I can only see the json format string that is not the graph format. Here is my django code. urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^form/$', views.play_count_by_month), url(r'^api/play_count_by_month', views.play_count_by_month, name='playAround'), # url(r'^form/$',views.Form), url(r'^upload/$',views.upload_file_name), ] views.py def play_count_by_month(request): data = Data.objects.all() \ .extra(select={'c1': connections[Data.objects.db].ops.date_trunc_sql('c1', 'c2')}) \ .values('c2') \ .annotate(count_items=Count('c1')) return JsonResponse(list(data), safe=False) models.py from django.db import models # Create your models here. class Data(models.Model): c1=models.DecimalField(max_digits=20,decimal_places=4) c2=models.DecimalField(max_digits=20,decimal_places=4) c3=models.DecimalField(max_digits=20,decimal_places=4) c4=models.DecimalField(max_digits=20,decimal_places=4) c5=models.DecimalField(max_digits=20, decimal_places=4) def __unicode__(self): return self.c1 * form.html * <!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none; } .line { fill: none; stroke: steelblue; stroke-width: 1.5px; } </style> <body> <script src="http://d3js.org/d3.v3.js"></script> <script> var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 960 - margin.left … -
Django query to sort alphanumeric values
I have a column desc in which data like A1, A0, A9, A11, B3, B11 need to sort this data as A0, A1, A9, A11, B3, B11 but MyModel.objects.all().order_by('desc') query returns A0, A1, A11, A9, B11, B3 What can I do. Note: desc is CharField. -
djnago object.get(pk = sth) , how to check if input is not malicious
I want to see my user by their id vias this route: path('users/<int:pk>', views.UserDetail.as_view()), and in my view I have this code: users.objects.get(pk=sth) in this case input (sth) will check with all id in the database to check if input Id exists and if not found it will return an error. the problem is here if the user enters a script that causes erasing the database, I will not know. how can I check from beginning id input data is valid? -
NoReverseMatch: Reverse for 'testimonypost' not found. 'testimonypost' is not a valid view function or pattern name
I can't figure this out. I have tried different things to no avail. Any ideas? #models.py class Testimony(models.Model): title = models.CharField(max_length=100) def get_absolute_url(self): return reverse("Testimony:details", kwargs={"id": self.id} ) #urls.py app_name='Testimony' urlpatterns=[ path('testimonypost/', views.TestimonyOrderView, name='testimonypost'),] #template(traceback points to this line) <li><a href="{% url 'testimonypost'%}" class="glyphicon glyphicon-grain">&nbspTestimonies</a></li> -
base.css is not get imported into the page?
I am trying to override the class generated by page-down app and the django-crispy-forms . But the indentation class override is not working. base.html(initially) ... <link rel='stylesheet' href='{% static "css/base.css" %}'> <style> {% block style %}{% endblock style %} </style> {% block head_extra %}{% endblock head_extra %} ... base.css h1 { color: #777777; } post_forms.html {%extends "base.html" %} {% load crispy_forms_tags %} {% block head_extra %} {{form.media}} {% endblock head_extra %} ... By using the inspect feature in chrome I can spot the class that causes the indentation <div class="wmd-panel"> </div> The code CSS given below is automatically generated one .wmd-panel { margin-left: 25%; margin-right: 25%; width: 50%; min-width: 500px; } But after making changes to css/base.css , there is no class named wmd-panel from the file base.css in the styles tab of the chrome. And the changes made are not reflected in the webpage. base.css h1 { color: #777777; } .wmd-panel{ margin-right: 0px !important; margin-left: 0px !important; } This is what expected in chrome inspect styles tab .wmd-panel { margin-left: 0%; margin-right: 0%; } This above class is from basic.css -
How to fix-no such table: main.auth_user__old
Can someone give a detailed explanation on how to fix the ERROR: no such table: main.auth_user__old It arrises in my Django application when I am trying to add data to my registered models. Please don't give a referral link to an other stackoverflow answer as that is not solving my problem clearly. -
How to deal with a note-making website when I need to store and redisplay information of user-selected vocabularies and phrases?
My plan is to set up a foreign-language-learning note-taking website using python django framework. The website mainly features these characteristics: user can type in paragraphs in two different languages and match them later on( I can solve this by myself so you don't need to answer this) the website detects the events of user highlighting some words/sub-sentences( I can imagine how to solve this by myself so you don't need to answer this) user can add comments on what they've highlighted; however I don't have a concrete plan on some best practice of saving and re-displaying what the users have done to their added notes/comments. To be exact, I am meaning that when a user later open his/her saved notes, how do I design my database schema so that when he/she hovers on one vocabulary/phrase, the website automatically responds him/her the note which was saved before? The answers I need could be in the format of codes or some detail concepts explanations. -
DJANGO: The value of annotation is coming NONE after performing subquery
This are my models: class Stockdata(models.Model): stock_name = models.CharField(max_length=32,unique=True) class Stock_Total_sales(models.Model): sales = models.ForeignKey(Sales,on_delete=models.CASCADE,null=True,blank=False,related_name='saletotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='salestock') quantity = models.PositiveIntegerField() class Stock_Total(models.Model): purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') quantity_p = models.PositiveIntegerField() I want to calculate the quantity of both purchase and sale and perform a Subtraction between the annotated values.. So, I have done this: qs = Stockdata.objects.annotate( sales_sum = Subquery( Stock_Total_sales.objects.filter( sales = OuterRef('pk') ).values( 'sales' ).annotate( the_sum = Sum('quantity') ).values('the_sum') ), purchase_sum = Coalesce(Sum('purchasestock__quantity_p'),0) ) qs1 = qs.annotate( difference = ExpressionWrapper(F('purchase_sum') - F('sales_sum'), output_field=DecimalField()) But the value of sales_sum is coming NONE is there any problem with my subquery or anything else? Can anyone tell me what mistake I have done In my code. Thank you -
How to parse original file path before it is uploaded
Is there a method/property to get and/or parse the original file path before the file is uploaded in Django? For example, I want to upload a file/image named: thefile, using FileField or ImageField from \some\folder\in\my\PC and then save that path to the database. Trying to use thefile.path property or {{ thefile.url }} in the template only gives me the uploaded file path. Any help would be appreciated. Thanks -
How to access foreign key in a django template? (DetailView)
I want to display products in a Campaign DetailView template. In my project each campaign has a shop which contains products, so the flow is like, Campaign --> Shop --> Products Campaign models.py class Campaign(models.Model): team = models.OneToOneField(Team, related_name='campaigns', on_delete=models.CASCADE, null=True, blank=True) shop = models.OneToOneField(shop_models.Shop, on_delete=models.CASCADE, null=True, blank=True) Shop models.py class Product(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=700, null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=0) class Shop(models.Model): product = models.OneToOneField(Product, related_name='shop_product', on_delete=models.CASCADE, null=True, blank=True) product2 = models.OneToOneField(Product, related_name='shop_product2', on_delete=models.CASCADE, null=True, blank=True) product3 = models.OneToOneField(Product, related_name='shop_product3', on_delete=models.CASCADE, null=True, blank=True) I tried to access the products like {% for item in obj.shop_set.all %} {{ item.title }} {{ item.price }} {% endfor %} but the fields turned out to be empty in the template. Any help would be appreciated. -
AttributeError: 'NoneType' object has no attribute due to related object slug not in view
my app (deployed to Heroku fwiw) had two model objects, Org and Event with corresponding object views and no issues/errs. when I introduced a third object Theme and modified some url routes to use its slug, I'm now getting the following err requesting the view for Org (url path whose view takes org.slug as a param): AttributeError: 'NoneType' object has no attribute 'org' and a 404 orgs.models.py class Org(models.Model): name = models.CharField(max_length=100, unique=True) slug = AutoSlugField(populate_from='name') themes = models.ManyToManyField('common.Theme', related_name='orgs', blank=True) ... def __str__(self): return self.name def get_absolute_url(self): return reverse('org-detail', args=[self.slug]) class Event(models.Model): org = models.ForeignKey('Org', on_delete=models.CASCADE, related_name='events') name = models.CharField(max_length=120) slug = AutoSlugField(populate_from='name', unique_with='org', sep='-') ... def __str__(self): return self.name def get_absolute_url(self): return reverse('event-detail', args=[self.org.slug, self.slug]) common.models.py class Theme(models.Model): name = models.CharField(max_length=50) slug = AutoSlugField(populate_from='name') class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('themes', args=[self.slug]) orgs.urls.py urlpatterns = [ url(r'^org/(?P<org_slug>[-\w]+)/?$', views.org, name='org-detail'), url(r'^org/(?P<org_slug>[-\w]+)/event/(?P<slug>[-\w]+)/', include([ url(r'^$', views.event, name='event-detail'), ... ])), ... ] common.urls.py urlpatterns = [ url(r'^(?P<slug>[-\w]+)/?$', views.theme, name='theme'), ... ] orgs.views.py def event(request, org_slug, slug): event = Event.objects.filter(slug=slug).order_by('id').first() if event.org.slug != org_slug: raise Http404 event_url = '{}{}{}'.format(settings.DEFAULT_PROTOCOL, settings.APP_DOMAIN, event.get_absolute_url()) context = { 'event': event, 'event_url': event_url, 'event_url_encode': urlquote_plus(event_url), } return render(request, 'orgs/event.html', context) def org(request, … -
django-filter field with widget 'SelectMultiple' gives pre-selected values from passed queryset
I am implementing filters for a given set of objects using django-filters. For one of the field I am using bootstrap tagsinput with multiple select. So, first in my filters.py (code below) I have passed the queryset in ModelMultipleChoiceFilter with the widget SelectMultiple. But when I load the page, the select comes with pre-selected (selected="selected") options with all the queryset objects value in it. So, I basically want these select multiple options to be 'unselected' by default. Thanks in advance. #filters.py class JobFilter(django_filters.FilterSet): job_category = django_filters.ModelMultipleChoiceFilter(queryset=Interests.objects.all(), widget=forms.SelectMultiple(attrs={'class': "form-control", 'data-role': "tagsinput"})) class Meta: model = JobPost fields = ['job_category', 'job_type', 'intake', 'duration'] #html as per inspection mode <select name="job_category" class="form-control" data-role="tagsinput" id="id_job_category" multiple> <option value="45" selected="selected">Interests object (45)</option> <option value="46" selected="selected">Interests object (46)</option> </select> -
How to fix analytics installation error in open edX.
I'm installing analytics(insights and analytics API) using this https://openedx.atlassian.net/wiki/spaces/OpenOPS/pages/43385371/edX+Analytics+Installation URL. I have installed successfully till 5-b step. when I try to run 5-c step then we are getting an error. Error details- (pipeline) hadoop@ubuntu:~/edx-analytics-pipeline$ remote-task --host localhost --repo https://github.com/edx/edx-analytics-pipeline --user ubuntu --override-config $HOME/edx-analytics-pipeline/config/devstack.cfg --wheel-url http://edx-wheelhouse.s3-website-us-east-1.amazonaws.com/Ubuntu/precise --remote-name analyticstack --wait TotalEventsDailyTask --interval 2015 --output-root hdfs://localhost:9000/output/ --local-scheduler Parsed arguments = Namespace(branch='release', extra_repo=None, host='localhost', job_flow_id=None, job_flow_name=None, launch_task_arguments=['TotalEventsDailyTask', '--interval', '2015', '--output-root','hdfs://localhost:9000/output/', '--local-scheduler'], log_path=None, override_config='/edx/app/hadoop/edx-analytics-pipeline/config/devstack.cfg', package=None, private_key=None, remote_name='analyticstack',repo='https://github.com/edx/edx-analytics-pipeline', secure_config=None, secure_config_branch=None, secure_config_repo=None, shell=None, skip_setup=False, sudo_user='hadoop', user='ubuntu', vagrant_path=None, verbose=False,virtualenv_extra_args=None, wait=True, wheel_url='http://edx-wheelhouse.s3-website-us-east-1.amazonaws.com/Ubuntu/precise', workflow_profiler=None) Running commands from path = /edx/app/hadoop/pipeline/share/edx.analytics.tasks Remote name = analyticstack WARNING: wheel_url argument is no longer supported: ignoring http://edx-wheelhouse.s3-website-us-east-1.amazonaws.com/Ubuntu/precise Running command = ['/edx/app/hadoop/pipeline/bin/ansible-playbook', '-i', 'localhost,', 'task.yml', '-e', '{"pipeline_repo_dir_name": "repo", "name": "all", "repos": [{"url": "https://github.com/edx/edx-analytics-pipeline", "dir_name": "repo", "branch": "release"}], "write_luigi_config": false, "root_log_dir": "/var/log/analytics-tasks", "root_data_dir": "/var/lib/analytics-tasks", "override_config": "/edx/app/hadoop/edx-analytics-pipeline/config/devstack.cfg", "uuid": "analyticstack"}', '-u', 'ubuntu'] PLAY [Configure luigi] ******************************************************** GATHERING FACTS *************************************************************** fatal: [localhost] => SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue TASK: [luigi | configuration directory created] ******************************* FATAL: no hosts matched or all hosts have already failed -- aborting PLAY RECAP ******************************************************************** to retry, use: --limit @/edx/app/hadoop/task.retry localhost : … -
Passing request.user to a queryset in ModelChoiceFilter
I want to pass request.user to a queryset in ModelchoiceFilter, because choice entry should be limited according to login user group. I try it, but getting kwargs in filters.py did not work. models.py class Score(models.Model): group = models.ForeignKey(Group, null=True, blank=True, on_delete=models.DO_NOTHING) member = models.ForeignKey(Member, on_delete=models.CASCADE,) date = models.DateField() lane = models.PositiveSmallIntegerField(null=True) score = models.PositiveSmallIntegerField(null=True) filters.py class ScoreFilter(django_filters.FilterSet): class Meta: model = Score fields = {'member': ['exact'], 'date': ['gte','lte'], } def __init__(self, *args, **kwargs): group = kwargs.pop('group', None) super(ScoreFilter, self).__init__(*args, **kwargs) self.filters['date__gte'].label="Start Date" self.filters['date__lte'].label="End Date" self.fields['member'].queryset = Member.objects.filter(group=group) views.py @login_required(login_url='/login/') def MemberResult(request, *args, **kwargs): for group in request.user.groups.filter(Q(name='mon') | Q(name='wed')): group = group s_filter = ScoreFilter(request.GET, group=group, queryset=Score.objects.filter(group=group).order_by('-date') I tried many solutions related to similar questions from this site, but could not solve yet.