Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django with mongoDB model designing
Could you please help me to create the DB design/Model for this below json data. { "myCart": { "dev": { "dev-1": { "version": "pi-2", "test": "pravil-nov-2022", "test2": "1.x.bi-9", "test3": "dev", }, "dev-2": { "version": "pi-1", "pravil": "pravil-nov-2021", "test2": "1.x.bi-8", "test3": "dev", } }, "stage": { "stage-1": { "version": "pi-2", "test": "pravil-nov-2021", "test2": "1.x.bi-1", "test3": "stage", }, "stage-2": { "version": "pi-4", "test": "pravil-nov-2021", "test2": "1.x.bi-5", "test3": "stage", } }, "prod": { "Prod-1": { "version": "pi-6", "test": "pravil-nov-2021", "test2": "1.x.bi-2", "test3": "Prod", } } } i have tried to create DB design for this data and im strugling to create it because of this random key(dev, staging, prod) -
How to deploy Django Application with Celery + Reddis on Google Cloud Run (docker-compose)
I have a docker-compose.prod.yaml containing 7 services which I'd like to deploy to Google Cloud Run. I like the benefits of a serverless solution, to my understanding the two other options are: Google App Engine, however this answer suggest multiple containers isn't possible GKE is a good fit but we're a small team without a dedicated DevOps engineer or internal Kubernetes expertise which is what would be required Is deploying such application possible on Google Cloud Run or even desirable? Some guidance on how to achieve this would be greatly appreciated. I'm favouring simplicity and cost efficiency. Some potential issues I'm foreseeing: Setting up networking between containers Instances are destroyed within 15 minutes Connecting all the volumes together Deploying 7 containers individually potentially tedious I do acknowledge that Google offers Cloud Tasks however, that would tie us to GCP and we'd miss the extensive functionality of Celery. One of the changes made to the docker-compose.prod.yaml will be switching the db container for a Cloud SQL managed instance. version: '3.8' services: nginx: build: ./compose/production/nginx volumes: - staticfiles:/app/staticfiles - mediafiles:/app/mediafiles ports: - 80:80 - 5555:5555 - 15672:15672 depends_on: - web - flower web: build: context: . dockerfile: ./compose/production/django/Dockerfile command: /start volumes: - … -
How to store directory, sub directory and file paths in a Python Dictionary?
I am developing a software which analyze excel files stored in Years directories which contains months directories and each month directory consist of excel files. Structure as shown below. In order to achieve my goal, I have used the code below os.walk("..\..\..\..\ema_monthly_reports") the above code shows all the directories, sub directories and files ('..\..\..\..\ema_monthly_reports', ['2022', '2023'], [])('..\..\..\..\ema_monthly_reports\2022', ['1', '10', '11', '12', '2', '3', '4', '5', '6', '7', '8', '9'], []) ('..\..\..\..\ema_monthly_reports\2022\1', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\10', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\11', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\12', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\2', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\3', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\4', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\5', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\6', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\7', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\8', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2022\9', [], ['Basic Facilities.csv'])('..\..\..\..\ema_monthly_reports\2023', ['1'], [])('..\..\..\..\ema_monthly_reports\2023\1', [], ['Basic Facilities.xlsx']) but I don't know how to properly manage years, months and files names in dictionary format. -
I am trying to get UserProfile using Django Simple JWT, but however I get error "Invalid data. Expected a dictionary, but got User."
I wanted to use email instead of username to login the user, so I obtained below code from the django documentation from custom authorization section. class UserManager(BaseUserManager): def create_user(self, email, name, password=None, password2=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('User must have an Email Address') user = self.model( email=self.normalize_email(email), name = name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, name=name, password=password ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) name = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return self.is_admin def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are … -
how to can run mindee doctr with python file
The tutorial is for Jupiter or google Collab How can I achieve that import os os.environ['USEA-TF'] ='1' from doctr.io import DocumentFile from doctr.models import ocr_predictor model = ocr_predictor(pretrained=True) document = DocumentFile.from_images('IM.jpg') result = model(document) result.show(document) json_response = result.export() print(json_response) I want to run the doctr in python file -
How to come back to DJANGO project
I'm pretty new in DJANGO. I was creating and editing my page I Sublime, but I accidentally closed my terminal where the DJANGO link was working. now when I tried to generate a new one this error comes out. It is possible to find a working link in files I used to editing? Probably gonna be a simple mistake I'm doing. Thanks guys. photo of the error The error I'm sure you know what to do. -
Github Actions - ImportError: Couldn't import Django
I am trying github actions on our project but it seems it cant find the django module even when it gets installed via the requirements.txt Any feedback would be greatly appreciated ` name: Eccounting tests on: push: branches: [ "main", "development", "features", "amazon", "shopify", "front_end", "wallmart"] pull_request: branches: [ "main", "development", "features", "amazon", "shopify", "front_end", "wallmart"] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.9] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Validate version run: python --version - name: Run simple python code run: python -c 'import math; print(math.factorial(5))' - name: Install Dependencies run: | python3 -m pip install --upgrade pip python3 -m venv .venv source .venv/bin/activate python3 -m pip install -r requirements.txt - name: Start Redis uses: supercharge/redis-github-action@1.4.0 - name: Run Tests env: DJANGO_SETTINGS_MODULE: ${{ secrets.DJANGO_SETTINGS_MODULE }} SECRET_KEY: ${{ secrets.SECRET_KEY }} DEBUG: ${{ secrets.DEBUG }} SP_API_REFRESH_TOKEN: ${{ secrets.SP_API_REFRESH_TOKEN }} LWA_APP_ID: ${{ secrets.LWA_APP_ID }} LWA_CLIENT_SECRET: ${{ secrets.LWA_CLIENT_SECRET }} SP_API_ACCESS_KEY: ${{ secrets.SP_API_ACCESS_KEY }} SP_API_SECRET_KEY: ${{ secrets.SP_API_SECRET_KEY }} SP_API_ROLE_ARN: ${{ secrets.SP_API_ROLE_ARN }} SP_APPLICATION_ID: ${{ secrets.SP_APPLICATION_ID }} SHOPIFY_API_KEY: ${{ secrets.SHOPIFY_API_KEY }} SHOPIFY_API_SECRET_KEY: ${{ secrets.SHOPIFY_API_SECRET_KEY }} SHOPIFY_API_SCOPES: ${{ secrets.SHOPIFY_API_SCOPES }} CELERY_BROKER_URL: ${{ secrets.CELERY_BROKER_URL }} REDIS_BACKEND: ${{ secrets.REDIS_BACKEND }} APP_URL: … -
Django - on_rollback using transaction.atomic
What exactly I want to do On rollback, I want to run a do_something function. Is it possible to do so? Right now, transaction.atomic does its job perfectly, but it only takes care of database. On rollback, I want to take care of a few other things using that do_something function I mentioned before. My use cases for transaction.atomic are pretty simple and there's not much to say about, I just use it on typical views which are creating and updating objects. -
Remote Access Database
I would like to connect to a remote database to continue the development of my application, say in another city, so we are not local but the two machines with the databases have access to the internet ; I use Sql server, how to have access to the other database? . I want to connect two remote databases via internet -
Migrate development PostgreSQL data to Railway
I've been using PostgreSQL in development and populating the database with some data. I deployed the whole app to Railway following these steps. When I create a new database in the railway production server it will always be a blank database. How can I migrate the data of my development database to Railway production's? The code I have in my Django's settings.py file is this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'basededatos1', 'USER': 'db_admin', 'PASSWORD': 'mYWZQy65viXG50wohppK.Z%uauhghs.CuB#k}nE45A=nK}Qe1*_g=sJF~*0}nQ^!aMuCL#]1i+i-hvs1N8:0Q9fGCdC1gNGc5g~T', 'HOST': 'localhost', 'PORT': '5432', } } And added this code while following the deployment tutorial: import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) The newly created PostgreSQL database in the Railway production dashboard is a blank, new database with different parameters to the one I had, but can't edit them. What is the way to go for using my development database's data into production? -
How do I integrate video calling with django (simple)?
I have a django backend setup, and I want to integrate video calling for people on the same url (only 2 people will be in the call per page and it has url patterns so they will be on independent urls). Whats an easy way of implementing this? -
How do I Integrate my Django application with Salesforce
I'd like to integrate Salesforce with my app/website, which was developed in Django and takes in a lot of data from users. So I guess I'd like to replicate my app's database into salesforce and use salesforce email service. How should I get started on this project. Thank you in advance I didn't try doing any stuff, I got to know we can deploy our app to heroku or create a new connected app, but I don't know which option to choose. -
How do I compare 2 ids, uuid of a logged in user and id sent through session variable?
I am trying to compare uuid of logged in user and id of user whose profile I have to see. I am comparing them using '==' operator, but the statements inside the 'if' are not getting executed although the condition is true. This is my function 'userProfile()' in 'views.py' that corresponds to the user profile of user I have to see. def userProfile(request, pk): profile = Profile.objects.get(id=pk) proj = P1.objects.filter(owner=pk) topskills = profile.skill_set.exclude(description__exact="") otherskills = profile.skill_set.filter(description="") context = {'profile':profile, 'ts':topskills, 'os':otherskills, 'projects':proj} if request.user.is_authenticated: uid = request.user.profile.id if uid == pk : return redirect('account') else : return render(request, 'users/user_profile.html', context) else : return render(request, 'users/user_profile.html', context) 'account' is the name of url which points to 'userAccount()' in views.py which is only available for authenticated users to display their profile where they can edit their profiles details : path('account/', views.userAccount, name="account") while, 'users/user_profile.html' is available for everyone even unauthenticated users but uneditable profile section(just to view the profile details) I want that when a logged in user clicks on any user's name (even his), if he clicks on his/her name, 'account.html' should open while for any other user, 'user_profile.html'. By default, clicking on any name, will redirect user to 'userProfile()' in … -
Modal Is Deleting The First Row In The Table Incorrectly. How Do I get the right ID associated with my DELETE button?
I've been at this all day. I've researched it and the docs are a bit scarce. I do recognize that I am getting the first ID at the top of the table because the IDs are all the same. I don't know how to get the "right" ID when I'm deleting the row. The modal is popping..and the delete works...it's just the wrong record gets deleted... HTML {% for notify in notify_list %} <tr style="vertical-align:top"> <td class="hide"> <div id="myModaldelete" class="modaldelete"> <div class="modal-content-delete"> <span class="closedelete"></span> <img class="logo4" src="/static/images/threecircles.svg"> <p>Delete Request?</p> <button type="button" class="button165" id="yesBtndelete" value="{{ notify.id }}">Yes</button> <button type="button" class="button160" id="noBtndelete">No</button> </div> </div> <button type="button" class="button114"> <div class="txtalgn114"><h2 class="txtalgn114a">Delete</h2></div></button> </td> </tr> {% endfor %} My Javascript... // Get the modal var modaldelete = document.getElementById("myModaldelete"); // Get the button that opens the modal var btndelete = document.getElementById("myBtndelete"); // Get the button that opens the modal var nobtndelete = document.getElementById("noBtndelete"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("closedelete")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function(e) { e.preventDefault(); modaldelete.style.display = "none"; } // When the user clicks on the No button, close the modal nobtndelete.onclick = function(e) { e.preventDefault(); modaldelete.style.display = "none"; … -
Djongo EmbeddedField raises ValidationError because of renamed field
I've got a Django application with djongo as a database driver. The models are: class Blog(models.Model): _id = models.ObjectIdField() name = models.CharField(max_length=100, bd_column="Name") tagline = models.TextField() class Entry(models.Model): _id = models.ObjectIdField() blog = models.EmbeddedField( model_container=Blog ) When I run this application, I got an error: File "\.venv\lib\site-packages\djongo\models\fields.py", line 125, in _validate_container raise ValidationError( django.core.exceptions.ValidationError: ['Field "m.Blog.name" of model container:"<class \'project.m.models.Blog\'>" cannot be named as "name", different from column name "Name"'] I want to keep the name of field name in my model and database different because the database already exists and I can't change it. Database uses camelCase for naming fields whereas in application I want to use snake_case. How to avoid this error? -
Ignore diacritics in django queries with sqlite
I have following querries inside my django app that is runninng with sqlite: movies = Movie.objects.filter(Q(title__icontains=query)) actors = Actor.objects.filter(Q(name__icontains=query)) Is there a way to ignore diacritics as well? I know about unaccent but AFAIK that works only with postgres and I need to stay with sqlite. -
How to deploy Docker Compose Django Application with Celery + Reddis on Google Cloud Run
I have a docker-compose.prod.yaml containing 7 services which I'd like to deploy to Google Cloud Run. I like the benefits of a serverless solution, to my understanding the two other options are: Google App Engine, however this answer suggest multiple containers isn't possible GKE is a good fit but we're a small team without a dedicated DevOps engineer or internal Kubernetes expertise which is what would be required Is deploying such application possible on Google Cloud Run or even desirable? Some guidance on how to achieve this would be greatly appreciated. I'm favouring simplicity and cost efficiency. Some potential issues I'm foreseeing: Setting up networking between containers Instances are destroyed within 15 minutes Connecting all the volumes together Deploying 7 containers individually potentially tedious I do acknowledge that Google offers Cloud Tasks however, that would tie us to GCP and we'd miss the extensive functionality of Celery. One of the changes made to the docker-compose.prod.yaml will be switching the db container for a Cloud SQL managed instance. version: '3.8' services: nginx: build: ./compose/production/nginx volumes: - staticfiles:/app/staticfiles - mediafiles:/app/mediafiles ports: - 80:80 - 5555:5555 - 15672:15672 depends_on: - web - flower web: build: context: . dockerfile: ./compose/production/django/Dockerfile command: /start volumes: - … -
anchor do nothing after second index
I created a qcm django with sections that change with each click with anchors and the scroll snap type property here is my code <body> <section> {% for Question_reponse in Questions_reponses %} <div id="{{forloop.counter}}" class="container"> <div class="question_title"> <div class="space_title"></div> <p>{{Question_reponse.question}}</p> </div> <div class="container_reps"> {% for rep in Question_reponse.reps %} <div class="rep"> <span class="dot_rep">1</span><p class="text_rep">{{rep}}</p> </div> {% endfor %} </div> </div> {% endfor %} </section> <script> function scrollToAnchor(ind){ const aTag = $("#"+ind); $('body,section').animate({scrollTop: aTag.offset().top},'slow'); } var container_page = document.getElementsByClassName('container') const reps = document.getElementsByClassName('rep'); [].forEach.call(reps,function(rep){ $(rep).click(function(){ if(! rep.querySelector('.check')){ [].forEach.call(reps,function(repToDel){ if(repToDel.querySelector('.check')){ repToDel.querySelector('.check').remove() $(repToDel).css("border", "1px solid white") } }) $(rep).last().append('<div class="check"><object data="{% static "img/Coin-Magpharm-V3.png" %}" width="20" > </object></div>'); $(rep).css("border", "2.5px solid white"); let x = parseInt($(rep).closest('.container').attr('id')) //var y = x.toString() console.log(x) scrollToAnchor(x+1) } }) }) </script> </body> and my css: html{ scroll-behavior: smooth; } body{ background-color: #72a9d6; color: white; font-family: "Mont", sans-serif; overflow: hidden; } section{ overflow: hidden; height: 100vh; /*overflow-y: scroll;*/ scroll-snap-type: y mandatory; scroll-behavior: smooth; } .container{ padding: 5%; display: grid; position: relative; justify-items: center; gap: 3px; scroll-snap-align: center; height: 100%; } .question_title{ height: 50px; font-size: 25px; font-weight: 500; text-align: center; } .space_title{ height: 150px; } .container_reps{ max-width: 30%; display: flex; flex-wrap: wrap; justify-content: center; column-count:2; height: 20%; } .rep{ display: flex; … -
Multiples def, same method in one view
I'm trying to define 4 GET endpoints (max,min,sum,avg) to access by REST. I did this but making 4 views, and I want to know if I can define the 4 methods in a single view. I can't specify through the url which GET to hit. It's possible? my urls.py set urlpatterns =[ path('medidores/', MedidorView.as_view()), path('mediciones/', MedicionView.as_view()), path('medicion_max/<str:id>', MedicionMaxView.as_view()), path('medicion_min/<str:id>', MedicionMinView.as_view()), path('medicion_total/<str:id>', MedicionTotalView.as_view()), path('medicion_prom/<str:id>', MedicionPromedioView.as_view()) ] my view.py set class MedicionMaxView(View): def get(self, request, id): return JsonResponse(Medicion.objects.filter(medidor=id).aggregate(Max('consumo_kwh'))) class MedicionMinView(View): def get(self, request, id): return JsonResponse(Medicion.objects.filter(medidor=id).aggregate(Min('consumo_kwh'))) class MedicionTotalView(View): def get(self, request, id): return JsonResponse(Medicion.objects.filter(medidor=id).aggregate(Sum('consumo_kwh'))) class MedicionPromedioView(View): def get(self, request, id): return JsonResponse(Medicion.objects.filter(medidor=id).aggregate(Avg('consumo_kwh'))) Separate by name in urls but not have effect -
Transfering kwargs from get to post
Is this the correct way to transfer kwargs from get request to a subsequent post request initated by the same page? Why cannot I call self.get if form is invalid? class Req(TemplateView): @login_required def get(self, request, *args, **kwargs): recepient=self.kwargs['recepient'] ftype=self.kwargs['type'] req_form = ReqForm(recepient=recepient) return render(request, 'req.html',{'form':req_form,'recepient':recepient,'ftype':ftype}) @login_required def post(self, request, *args, **kwargs): recepient=self.kwargs['recepient'] ftype=self.kwargs['type'] req_form = ReqForm(data=request.POST,recepient=recepient) if req_form.is_valid(): messages.success(request, f'Your request has been sent to {recepient}!') -- More Code -- return redirect('users-profile',request.user.username) else: self.get(self, request, *args, **kwargs): -
What is the correct way to convert Django date and time fields to current timezone?
I feel like I'm missing something obvious: I implemented timezones in my Django app using the SO solution here and it seems to be working (i.e. when the user changes to their timezone, Django's {% get_current_timezone as TIME_ZONE %} and timezone.get_current_timezone.now() reflect that change) However, I have a Django model with both a naive DateField and TimeField input. I have defined a property to return the formatted string with the date and time as follows: # imports from django.db import models import pytz from django.utils import timezone from django.template.defaultfilters import date as format_date from django.template.defaultfilters import time as format_time class MyModel(models.Model): date = models.DateField(default=timezone.now, null=True, blank=True) time = models.TimeField(default=timezone.now, null=True, blank=True) ... @property def datetime(self): date_str = format_date(self.date, "j N Y") time_str = format_time(self.time, 'g:i a') return f"{date_str} at {time_str}" How would I make the dates and times returned in the string changed to suit the timezone? (It can be assumed that they currently refer to UTC.) I'm currently trying with the time field. I tried both of these functions to make the time aware: pytz.utc.localize(self.time) self.time.replace(tzinfo=pytz.UTC) But whenever I try to get the subsequent time for the zone through the statement: aware_time = self.time.replace(tzinfo=pytz.UTC) I get the error: 'datetime.time' … -
Full Stack Web Developer Related Question
Hey I am in my journey to become full stack web developer and i bought a course where i am learning node js express js as backend. But i heard we can use any other programming language as well but i have one confusion please help me. QUESTION :- In The course i am learning node js. if I learn django instead of node js. Can i call myself full stack web developer ?. Or Can we use any porgramming language or framework in backend but can only use html css javascript on the frontend ? Can we use any programming language or framework in backend in web development and can call ourself full stack web developer -
how to retrieve a Django model from a html template form
I am having a user select from a list of Pending shift swap requests. in the html page the form is as such #pending_swaps.html {% for pending in swappie_pending_list %} <form action="{% url 'ShiftSwap:pending_swaps' %}" method="post"> {% csrf_token %} <p>{{ pending.swapper.name }} wants to switch your {{ pending.get_swappie_day_display }} for their {{ pending.get_swapper_day_display }} <input type="hidden" name="Swap_Obj" value="{{ pending }}"> <input type="submit" name="Confirm" value="Confirm"> <input type="submit" name="Deny" value="Deny"> </p> </form> {% endfor %} in this code the swappie_pending_list is a list of Pending_Swap Model objects. However when I try to make a hidden input of value={{ pending }} it simply returns the str of the model instead of an instance to the model itself here is the Pending_swap model class Pending_Swap(models.Model): ''' a model to house two users, and two days to keep track of which swaps are currently pending \n swapper: user swappie: who they want to swap with swapper_day: day they are giving up swappie_day: day the user wants to take ''' Days_of_week = ( ('SU', 'Sunday'), ('MO', 'Monday'), ('TU', 'Tuesday'), ('WE', 'Wednesday'), ('TH', 'Thursday'), ('FR', 'Friday'), ('SA', 'Saturday'), ) swapper = models.ForeignKey(Person, on_delete=models.CASCADE, default=" ", related_name='Swapper') swappie = models.ForeignKey(Person, on_delete=models.CASCADE, default=" ", related_name='Swappie') swapper_day = models.CharField(max_length=2, choices=Days_of_week) … -
How to add multiple types of cache in CACHES setting in settings.py is django
I have a django application. I want to use both database cache and redis cache at different places in my application. How do I write the settings in settings.py? How do I import both redis and database cache in my code and set some data into both types of cache? I tried this in django settings.py CACHES = { 'default': { 'BACKEND':'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'data-caches', }, 'Redis': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', 'OPTIONS': { 'db': '1', 'parser_class': 'redis.connection.PythonParser', 'pool_class': 'redis.BlockingConnectionPool', } } } but when I import in my code from django.core.cache import cache It always picks the default one. How do I import database cache in one python file and redis cache in a different python file? -
How to filter data by start date to end date django then display the data in the template
models.py class Income(models.Model): date = models.DateField() capital = models.IntegerField(null=True, verbose_name='Money Capital') revenue = models.IntegerField(null=True, verbose_name='Total Revenue') profit = models.IntegerField(null=True, verbose_name='Total Profit') def __str__(self): return self.profit forms.py from django import forms from . models import Income class DateChoiceField(forms.Form): date1 = forms.ModelChoiceField ( queryset=Income.objects.values_list("date", flat=True).distinct(), ) date2 = forms.ModelChoiceField ( queryset=Income.objects.values_list("date", flat=True).distinct(), ) views.py if request.method == "POST": form = DateChoiceField(request.POST) date1 = request.POST.get('date1') date2 = request.POST.get('date2') if 'form1' in request.POST: if form.is_valid(): selectedDate1 = form.cleaned_data["date1"] selectedDate2 = form.cleaned_data["date2"] start = datetime(selectedDate1) end = datetime(selectedDate2) filterYearMonth = Income.objects.filter(date__gte=start).filter(date__lte=end) else: filterYearMonth = Income.objects.all() else: form = DateChoiceField() filterYearMonth = Income.objects.all() context = { 'filterYearMonth': filterYearMonth, 'form': form, } return render (request, "dashboard/dashboard.html", context) dashboard.html <form method="POST" action="/dashboard/"> {% csrf_token %} {{ form }} <button type="submit" name="form1">Submit</button> </form> <h4>Filter</h4> <table> {% for item in filterYearMonth %} <tr> <td>{{ item.date }}</td> <td>{{ item.capital }}</td> <td>{{ item.revenue }}</td> <td>{{ item.profit }}</td> </tr> {% endfor %} </table> I'm close to solving it but it keeps displaying all the data and i got this "Select a valid choice. That choice is not one of the available choices." whenever i try submitting the start and end date.This is what it looks like