Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Combining javascript search with dropdown filter
I have a working code with a live javascript search where I can search in a table for a user by either their first and last name or one of them. I also have a working dropdown filter, where you can choose a rank, which will only show the users with that specific rank. The problem is, they don't combine --> If I do a search and then select the rank, it shows all users with that rank, and it doesn't use the search. It also doesn't work the other way. Does anyone have an idea how I can combine the two filters? I work in Django, so my java and HTML are on the same page. I left out the sort function because it's not relevant for my question. Here a pic of how it looks: How it looks right now HTML: {% extends 'puma_core/layouts/navbar.html' %} {% load static %} {% block content %} <div class="container mt-5"> <div class="mb-4"> <div> <div class="row"> <div class="col-8"> <h1> Gebruikers {{ peloton }} </h1> </div> <div class="col position-relative mt-sm-2 me-3"> <a class="btn btn-secondary btn-sm position-absolute end-0" href="{% url 'peloton' peloton.id %}" role="button"> Terug </a> </div> </div> </div> </div> <input id="userInput" placeholder="Zoek een gebruiker..." … -
DJango ProgrammingError: can't execute an empty query
My sql command are inside csv file after that I read and forloop each row, SQL command are printout like this also Im using multi database. SELECT value AS id from test_table WHERE name ='James' AND age ='10' AND gender ='male' AND number ='205485' But if I execute the sql I got an error django.db.utils.ProgrammingError: can't execute an empty query Here's my code: @api_view(['GET']) def filter(request): field = {"James","Chris"} number = "205485" df = pd.read_csv('path/to/file/filter.csv') for name in field: data = df[df['Name'] == name] sql = data['sql_query'].values[0] query = sql + ' number =' + "'"+ number +"'" try: data = test_table.objects.using("database_2").raw(query) cursor = connection.cursor() cursor.execute(data) row = cursor.fetchone()[0] finally: cursor.close() -
how to show list of categories in navbar using django framework
hello I want to list my categories in navbar from database but the navbar is a partial view and I included my navbar in base.html . how can i give the data to this navbar -
Unable to use multiple Authentication Classes in Djangorestframework
I have the following permission class: class FirebaseAuthentication(authentication.TokenAuthentication): """ Token based authentication using firebase. """ keyword = "Token" def authenticate_credentials( self, token: str ) -> Tuple[AnonymousUser, Dict]: try: decoded_token = self._decode_token(token) firebase_user = self._authenticate_token(decoded_token) local_user = self._get_or_create_local_user(firebase_user) return (local_user, decoded_token) except Exception as e: raise exceptions.AuthenticationFailed(e) def _decode_token(self, token: str) -> Dict: """ Attempt to verify JWT from Authorization header with Firebase and return the decoded token """ try: token = self.__generate_id_token(token) # appliable only when testing with ID token decoded_token = firebase_auth.verify_id_token( token, check_revoked=True ) log.info(f'_decode_token - decoded_token: {decoded_token}') return decoded_token except Exception as e: log.error(f'_decode_token - Exception: {e}') raise Exception(e) def _authenticate_token( self, decoded_token: Dict ) -> firebase_auth.UserRecord: """ Returns firebase user if token is authenticated """ try: uid = decoded_token.get('uid') log.info(f'_authenticate_token - uid: {uid}') firebase_user = firebase_auth.get_user(uid) log.info(f'_authenticate_token - firebase_user: {firebase_user}') if not firebase_user.email_verified: raise Exception( 'Email address of this user has not been verified.' ) return firebase_user except Exception as e: log.error(f'_authenticate_token - Exception: {e}') raise Exception(e) def __generate_id_token(self, token: str) -> str: """ Follow """ id_token_endpoint = ( "https://identitytoolkit.googleapis.com/v1/accounts" ":signInWithCustomToken?key={api_key}" ) url = id_token_endpoint.format( api_key="AIzaSyCurgq3Cn_3UzaPerWkhuHe8omS_RlIQTU" ) data = {"token": token, "returnSecureToken": True} res = requests.post(url, data=data) time.sleep(5) # Sleep for 5 seconds to avoid exception … -
limiting __in lookup in django
i have are question about "__in" lookup in Django ORM. So here is the example of code: tags = [Tag.objects.get(name="sometag")] servers = Server.objects.filter(tags__in=tags)[offset_from:offset_to] server_infos = [] for server in servers: server_infos.append(query.last()) So here is the problem: we making about 60-70 sql requests for each server. But i want to do something like this: tags = [Tag.objects.get(name="sometag")] servers = Server.objects.filter(tags__in=tags)[offset_from:offset_to] server_infos = ServerInfo.objects.filter(contains__in=servers) assert servers.count() == server_infos.count() Can i do this without raw sql request? All i need to understand is how to limit "__in" expression in Django to get only last value as in example above. Is it possible? -
VariableDoesNotExist at /blog/blog_posts/ Failed lookup for key [categories] in [{'True': True, 'False': False, 'None': None}, {}, {},
I trying to create categories with MPTT and I get this error: eVariableDoesNotExist at /blog/blog_posts/Failed lookup for key [categories] in `enter code here`[{'True': True, 'False': False, 'None': None}, {}, {}, I know that I have to pass the queryset from views.py to my template and its still does not work. views.py class BlogCategoriesList(generic.ListView): model = Category template_name = 'blog/blog_categories_list.html' def get_queryset(self): content = { 'categories': Category.objects.all() } return content models.py class Category(MPTTModel): name = models.CharField(max_length=100, null=True,default=None) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] verbose_name_plural = 'Categories' def get_absolute_url(self): return reverse('blog:category_details_view', args=[str(self.slug)]) def __str__(self): return self.name class Post(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') options = (('draft','Draft'),('published','Published'),) title = models.CharField(max_length=300,null=True) category = TreeForeignKey(Category, on_delete=models.PROTECT, null=True, blank=True, default=None) excerpt = RichTextField(blank=True,max_length=30000,null=True) slug = models.SlugField(max_length=300, unique_for_date='published',null=True) featured_image = models.ImageField(upload_to='media/blog_featured_images', null=True) published = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts',null=True) content = RichTextField(blank=True,null=True) status = models.CharField(max_length=10, choices=options, default='draft',null=True) objects = models.Manager() newmanager = NewManager() def get_absolute_url(self): return reverse('blog:single_post', args=[self.slug]) class Meta: ordering = ('-published',) verbose_name_plural = 'Posts' unique_together = ('title','slug') def __str__(self): return self.title blog_category_list.html {% block content %} {% load mptt_tags %} <ul> {% recursetree categories %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ … -
xhtml2pdf not show the personal font, i don't understand how i should import my font
I need to create a pdf and I need my own font which is present in static / font / I just don't understand how to import it. the font always remains the same and I don't know how to do it, can someone help me? I used: http://127.0.0.1:8000/static/font/titolo.ttf /static/font/titolo.ttf {% static 'font/titolo.ttf' %} but not work, how should i import my font for it to work correctly? css <style> @font-face { font-family: "Titolo"; src: url('/static/font/titolo.ttf'); } @page { size: A4 portrait; @frame header_frame{ -pdf-frame-content: header; top: 10mm; width: 210mm; margin: 0 10mm; } @frame content_frame{ width: 210mm; top: 40mm; margin: 0 10mm; } @frame footer_frame{ -pdf-frame-content: footer; top: 276mm; width: 220mm; margin: 0 10mm; } } h1 {font-size: 4rem; margin-bottom: 0; font-family: 'Titolo';} #header p, .total p {font-size: 1.4rem;} .title-element {margin-bottom: 1.5rem} .element img {width: 60px; height: 60px;} .element p, .title-element p {font-size: 1.2rem;} .element td {text-align: center;} .title-element p {line-height: 1;} </style> views from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def pdf_order(request, id): ordine = get_object_or_404(Summary, user = request.user, id = id) # template e context template_path = 'pdf.html' context = {'ordine': ordine} # oggetto django formato pdf response = HttpResponse(content_type='application/pdf') # view … -
AnonymousUser automatically created for TestCase
I'm encountering a situation where an anonymous user is automatically created upon constructing a TestCase which is not expected nor desired. The example test case that is posted below is not the sole test case experiencing this behavior. A custom User model has been created for my project, but I'm not sure if that has inadvertently done something to cause this. In python manage.py shell, I queried all users with get_user_model().objects.all(); within the queryset there was an instance of <User: AnonymousUser>. That was deleted as I closed/re-opened the shell and checked the admin as well. To specify what database I'm using for testing I'm using the built in test database Django provides with SQLite What would be causing the testcase to automatically populating with an AnonymousUser? from django.test import TestCase class TestViewUserQuestionsPostedPage(TestCase): @classmethod def setUpTestData(cls): cls.viewed_user = get_user_model().objects.create_user("ItsYou") testcase_users = get_user_model().objects.all() request = RequestFactory().get(reverse("authors:profile", kwargs={'id': 1})) cls.view = UserProfilePage() cls.view.setup(request, id=2) cls.view_context = cls.view.get_context_data() def test_viewed_profile_of_user(self): self.assertIsInstance(self.view, Page) self.assertIn('user', self.view_context) self.assertEqual(self.view_context['object'], self.viewed_user) (Pdb) testcase_users = get_user_model().objects.all() (Pdb) testcase_users <QuerySet [<User: AnonymousUser>, <User: ItsYou>]> from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = CharField( unique=True, max_length=16, error_messages={ "unique": "Username not available" } ) -
Load balancer : upstream timed out (110: Connection timed out) while reading response header from upstream
I am new for AWS codepipeline and docker for deploy my django app with load balancer. My app normally work fine. But when i send 10 request in parallel it works. But when i send more than 10 request in parallel than it return 504 gateway timeout error. When i checked in log it return me this error. *257 upstream timed out (110: Connection timed out) while reading response header from upstream, client: xxx.xx.xx.xxx, server: , request: "GET path HTTP/1.1", upstream: "requested url", host: "example.com" I do not know why i got this error error. I try ngnix timeout increase and connection idle timeout also. But did not get any success. I think problem is ==> when my ec2 instance is overload and it create new ec2 instance with load balancer than i got this error. Please help me how can i fix this error. Thank you in advance -
I've a django app connected with my local postgresdb,I've built a docker image of that project using dockerfile but, when I run i'm getting this error
This is my docker file FROM python:3.8.10 # Install required packages # RUN apk add --update --no-cache \ # build-base \ # postgresql-dev \ # linux-headers \ # pcre-dev \ # py-pip \ # curl \ # bash \ # openssl \ # nginx \ # libressl-dev \ # musl-dev \ # libffi-dev \ # rsyslog # Install all python dependency libs RUN mkdir -p /ds_process_apis COPY requirements.txt /ds_process_apis RUN pip install -r /ds_process_apis/requirements.txt # Copy all source files to the container's working directory COPY ./ /ds_process_apis/ WORKDIR /ds_process_apis EXPOSE 8020 CMD ./manage.py migrate --noinput && ./manage.py initadmin && ./manage.py collectstatic --noinput && gunicorn ds_process_apis.wsgi --bind 0.0.0.0:8020 --workers 2 --worker-class sync --threads 6 I'm getting this error I'm new to docker psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? -
student teacher management system
There are two type of users teacher and student: Teacher attributes: First name, last name, teaching since, instrument, email Student attributes: First name, last name ,skill, instrument, student since, email, birthday For every teacher there are one or more students for every student there is only one teacher Teacher roles: Administrator ,assistant and regular teacher Adminstrator: -Can create ,read ,update and delete teacher and student in his school Assistant teacher: -Can read only teacher and student Regular teacher -Can create ,read ,update and delete student -
Cannot change value on form field on Django from template
I am trying to change the value dynamically on a django template via javascript but it is not working, which other ways do I have? Thank you. I have to set a property from Model as a value $('#id_myvariable').change(function() { var name_object = $('#id_myvariable'); var current_name = name_object.val(); var new_name = "new_name" name_object.attr('value',new_name); }); -
How to upload multiple files in Django
I've been trying to find a solution to add multiple files using a drag and drop form. I'm using Django's Rest API and React. This is what i have been trying so far but it seems like this will only do for one file at a time: class FileCollection(models.Model): Name = models.CharField(max_length=150, null=True, blank=True) Files = models.FileField(upload_to='videos_uploaded', null=True, blank=True, validators=[ FileExtensionValidator(allowed_extensions=['mp4', 'm4v', 'mov', 'mpg', 'mpg2', 'mpeg'])]) How can i make it so i can upload multiple files at once with the rest api? I only found some answers on here regarding images. -
cant activate virtual Enviroment
I have tried many ways to enable it, even changing the interpreter, but I still get this error -- ERROR: File C:\Users\Me\Desktop\code.py\learning_log\env\Scripts\Activate.ps1 cannot be loaded because the exe cution of scripts is disabled on this system. Please see "get-help about_signing" for more details. At line:1 char:2 & <<<< c:/Users/Me/Desktop/code.py/learning_log/env/Scripts/Activate.ps1 CategoryInfo : NotSpecified: (:) [], PSSecurityException FullyQualifiedErrorId : RuntimeException -
how to get a particular field from django model
I want a command for getting a query set from the model. The SQL command will be like - SELECT teamName FROM TABLE WHERE userName=userName; -
how can I generate an unique id for a string. in python
how can I generate an unique ID for a string, which means only that string has a that id and if we try to put another string in that function it does not match. -
Django - Displaying model data based on primary key
I have a model of multiple images and I want to display each of them in their own separate Owl carousel when an image is clicked by using the primary key as a reference. I have everything set up but for some reason my images are not being loaded into the carousel. I have no bad responses so If anyone can help me I'd be grateful. urls.py: urlpatterns = [ # homepage path('', views.index, name='index'), # get the primary key when an image is clicked path('<int:pk>', views.index, name='index_with_pk'), # use that primary key to fetch that image's data path('carousel/', views.carouselData, name="carousel_data") ] ajax call in index.html when image is clicked: $.ajax({ type: "GET", url: '{% url "carousel_data"%}', data: { "prime_key": prime_key }, success: function(data) { console.clear(); console.log("Image object primary key: " + prime_key); $(".owl-carousel").owlCarousel({ items:1, loop:true, nav:true, dots: false, autoplay: false, autoplayTimeout: 5000, smartSpeed: 500, autoplayHoverPause: false, margin: 20, touchDrag: true, mouseDrag: false, navText : ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"] }); }, error: function(data){ console.log('something went wrong'); } }) views.py: def carouselData(request): if request.method == "GET": # get the primary key from ajax my_key = request.GET.get('prime_key') carouselObjects = Portrait.objects.filter(pk=my_key).values( 'painting_left', 'painting_right', 'painting_top', 'painting_bottom', 'painting_back' )[0] carouselContext = { 'carouselObjects': carouselObjects … -
In Django Query set using filter with custom arguments
I am using the filter in Django queryset, as it takes arguments like: Model.objects.filter(name="Amit") here is name and it's value, I am getting from the request of API: def get(self, request): column = request.query_params.get('column') val = request.query_params.get('value') query = Data.objects.filter(column=val).values() serializer = DataSerializer(query, many=True).data return Response(serializer) but here column [inside filter] is not getting recognized as the request parameter, it is taken as the column name of the table which is not available. The error I got: django.core.exceptions.FieldError: Cannot resolve keyword 'column' into field. Hope this information is suitable for understanding the problem, if something is missing please let me know and kindly help me out with this. -
corrupted files uploading csv and zip files via postman toward django rest api
Hi, I'm using django 4.0.6 (python 3.8) with djangorestframework 3.13.1 on windows. I'm testing on localhost my app with postman and postman agent up to date. The authorization JWT is working fine. If I upload an image or a txt the files are ok. If I upload csv or zip files they result in corrupted files. Only short csv files are correctly uploaded, long csv files result in corrupted lines on the lower part of the text with this sort of characters: Û™eÞqHÂÔpŠl°‹<û yjϪ›kÃx›Ûr-¥x¡S¼à2SÕkÛår'mÒÕµd5ÿ¶Vê0@1 ̦Záë1§ŠIÇaÎ “’ÏÛ€t»vRoT"·‡Qf„¾´é-Oa)]ЧK‹5C¤sWB0),3 Zž—2¸Ñóo«jŸH“ I can't figure out how to fix it, reading other posts I couldn't find a solution that fit with this situation. Thank You for any suggestion! Here my model: class FileUploader(models.Model): id_file = models.AutoField('id_file', primary_key=True) Campaign_Name = models.CharField('Campaign_Name', max_length=255) ViewpointSurvey = models.FileField('ViewpointSurvey',upload_to=path_and_rename_base,max_length=255,blank=False,null=False,db_column='ViewpointSurvey', name='ViewpointSurvey') ProjectSurvey = models.FileField('ProjectSurvey', upload_to=path_and_rename_base, max_length=255, blank=False, null=False, db_column='ProjectSurvey', name='ProjectSurvey') Trajectories = models.FileField('Trajectories', upload_to=path_and_rename_base, max_length=255, blank=False, null=False, db_column='Trajectories', name='Trajectories') screenshots = models.FileField('screenshots', upload_to=path_and_rename_base, max_length=255, blank=False, null=False, db_column='screenshots', name='screenshots') timestamp=models.DateTimeField('timestamp',auto_now_add=True,db_column='timestamp', name='timestamp') id_project=models.CharField('id_project', max_length=255) class Meta: db_table = "file_uploader" verbose_name_plural = 'file_uploader' verbose_name = "file_uploader" Here the view: class CSVUploadAPI(GenericAPIView): parser_classes = [MultiPartParser] serializer_class = UploadSerializer def put(self, request): data_collect = request.data serializer = UploadSerializer(data=data_collect) if serializer.is_valid(): serializer.save() Here the serializer: class UploadSerializer(serializers.ModelSerializer): … -
The joined path (/static/logo/my_project_logo.jpg) is located outside of the base path component (/home/softsuave/project/my_project_api/static)
I got this error while using this command. The joined path (/static/logo/my_project_logo.jpg) is located outside of the base path component (/home/softsuave/project/my_project_api/static) Traceback (most recent call last): File "", line 1, in File "/home/softsuave/project/my_project_api/venv/lib/python3.10/site-packages/django/contrib/staticfiles/finders.py", line 276, in find result = finder.find(path, all=all) File "/home/softsuave/project/my_project_api/venv/lib/python3.10/site-packages/django/contrib/staticfiles/finders.py", line 110, in find matched_path = self.find_location(root, path, prefix) File "/home/softsuave/project/my_project_api/venv/lib/python3.10/site-packages/django/contrib/staticfiles/finders.py", line 127, in find_location path = safe_join(root, path) File "/home/softsuave/project/my_project_api/venv/lib/python3.10/site-packages/django/utils/_os.py", line 29, in safe_join raise SuspiciousFileOperation( django.core.exceptions.SuspiciousFileOperation: The joined path (/static/logo/my_project_logo.jpg) is located outside of the base path component (/home/softsuave/project/my_project_api/static) result = finders.find(uri) from django.contrib.staticfiles import finders settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'site/assets/') STATICFILES_DIRS = [ BASE_DIR / "static/", BASE_DIR, ] MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/qr_code') file structure: my_project my_app static logo my_project_logo.jpg template my_app my_template.html my_tempate.html {% load static %} <!DOCTYPE html> <html> <head> <title> QR Code </title> <style> #goable{ width: 300px; height: auto; margin: 40%; border: 1px solid black; } #img1{ height:100px ; margin:10px 100px 0px 100px; }#img2{ height: 200px; margin:10px 50px 0px 50px; } h1,p{ text-align: center; } </style> </head> <body> <div id="goable"> <img id='img1' src="{% static 'logo/my_project_logo.jpg' %}" alt="My image"> <h1>SCAN ME!!!</h1> <p> TO Notify Drivers that their car is about to get a parking … -
How to get soap request body with spyne
@rpc(Request91Type, _returns=AnyDict, _out_variable_name="Response91") def Request91(ctx, Request91Type): try: logging.info( f'Initialized objects {str(Request91Type).encode("utf-8")}') return { "GUID": 'aaa', "SendDateTime": "2022-04-11T19:50:11", "Certificate": CertificateMinimumType.generate(), "Status": "Выдан", "StatusCode": "1601", "Inspector": None } except Exception as e: logging.info(f'Exception occurred: {str(e)}') I tried to access Request91type.guid but it did not work:) This is my soap request example:https://pastebin.com/QyJWL2jJ And this one is for complex models : https://pastebin.com/gdZGkmqN I also tried to print(ctx.in_string) but returned <generator object WsgiApplication.__wsgi_input_to_iterable at 0x7faf41451e70> like this message -
The view mainsite.views.winner_detail didn't return an HttpResponse object. It returned None instead
Guys I'm losing my freaking mind. I Keep getting this error after updating a model form. I've made many of these forms before in previous projects and before and never had this issue. I've looked at every single question here with the same issue and got nowhere. this is the view def winner_edit_form(request, pk): winner = PrizeWinner.objects.get(id=pk) if request.method == 'POST': form = WinnerForm(request.POST, instance=winner) if form.is_valid(): form.save() return HttpResponseRedirect('winner-details.html', winner.id) else: form = WinnerForm(instance=winner) return render(request,'edit-winner-form.html',{'form': form}) I've tried several versions of this, including: def winner_edit_form(request, pk): if request.method == 'POST': winner = PrizeWinner.objects.get(id=pk) form = WinnerForm(request.POST or None, instance=winner) if form.is_valid() and request.POST['winner'] != '': form.save() return HttpResponseRedirect('winner-detail') else: form = WinnerForm(instance=winner) context = {'winner': winner, 'form': form} return render(request, 'partials/edit-winner-form.html', context) I literally copied and pasted from previous and more complex projects and from other examples and I keep getting this error. These are my urls from django.urls import path from mainsite import views urlpatterns = [ path('',views.HomePage.as_view(), name='home'), path("winner-detail/<int:pk>", views.winner_detail, name='winner-detail'), path("winner-detail/<int:pk>/edit/", views.winner_edit_form, name='winner_edit_form'), ] models.py class PrizeWinner(models.Model): name = models.CharField(max_length=200, blank= False) prizecode = models.CharField(max_length=120, blank=True) prizestatus = models.CharField(max_length=200, null=True, blank=True, choices=STATUS_CHOICES, default='Unclaimed') prizechoices = models.CharField(max_length=200, null= True, blank= True, choices =PRIZE_CHOICES, default='£10 Bar Tab') … -
Don't want to change value of specific variable when function run with threading
want to store that value of variable and don't want to change it until condition meets in function which run in threading in python...I don't want to change value of that variable -
How would I be able to use the Emmet tag "!" in Djang-html?
I know that to fix the emmet abbreviations for most tags for Django-html is by going to preferences ---> settings ---> Emmet. After getting there I proceeded to add (Django-html, html) into the item and value area. After doing so I am able to use normal emmet abbreviations but I want to use the "!" tag. is there a reason why I cannot use it or is there a fix needed. Thank y'all in advance. -
Django filters date range filter is not working
I really don't understand how to connect these two fields or should I just create one. On my front, I have a starting date and end date I can not connect to the backend properly using django-filters Please see the below code My filters.py class VideoFolderFilter(FilterSet): name = CharFilter(field_name='name', lookup_expr='icontains', widget=forms.TextInput(attrs={'class': "form-control"})) subscription_plan = ModelChoiceFilter( label='subscription_plan', queryset=Plans.objects.all()) start_date_range = DateFromToRangeFilter(field_name='start_date_range', widget=forms.TextInput(attrs={'class': "form-control"})) end_date_range = DateFromToRangeFilter(field_name='end_date_range', widget=forms.TextInput(attrs={'class': "form-control"})) def get_date_range(self, start_date_range, end_date_range): return Sample.objects.filter(sampledate__gte=start_date_range, sampledate__lte=end_date_range) class Meta: model = VideoFolder fields = '__all__' widgets = {'start_date_range': DateInput(),} exclude = [ 'thumbnail_link', 'link', 'name'] My views.py @login_required def search_videos(request): if Subscriber.objects.filter(user=request.user).exists(): subscription = Subscriber.objects.get(user=request.user) else: message = "Seams like you don't have subscription with us please select one of the plans" return redirect(reverse('main')) video_filter = VideoFolderFilter(request.GET, queryset=VideoFolder.objects.filter(type='video').order_by('-created_date')) videos = video_filter.qs return render(request, 'search-videos.html', locals()) Should I change the views.py to query if yes how to date range and other fields will be included And my search-videos.html <div class="search-video-form-section mb-3"> <p>Use one or more filters to search below</p> <form method="GET"> <div class="form-group mb-px-20 filter-form"> <label class="text-base">Name Contains</label> <!-- <input type="text" class="form-control" placeholder="Keyword" /> --> {{ video_filter.form.name }} </div> <div class="d-flex flex-wrap date-box"> <div class="form-group input-field"> <label class="text-base">Start Date</label> <div class="input-group input-daterange"> {{ video_filter.form.start_date_range …