Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django signales do not trigger
I need to create a few instances of another model once the instance of main model has been created. To do this I'm using the signals. My code does not throw any error, just the desired instances do not get created when I create the main instance. What might be wrong in the below code ? Appreciate :) hours = [ "10:00:00", "12:00:00", "15:30:00", "18:00:00", "22:00:00", ] @receiver(post_save, sender=Movies) def create_movie_dates(sender, instance, created, **kwargs): if created: for x in range(7): date = datetime.now() + timedelta(days=x) time = datetime.strptime(hours[x], "%H:%M:%S").time() Movie_dates.objects.create(movie=kwargs[instance], date=kwargs[date], time=kwargs[time]) -
Django - Retrieve Data for 2 Separate Querysets On One Page
I am using Django, PyCharm 2018.3.7, Python 3.7, and Postgres. Unfortunately, I do not understand how to display on one screenpage (Django form) the results for 2 separate querysets that need the same ID passed by a dynamic filter request (GET). There is a table/model (ASSIGNMENTS) with a One-To-Many relationship to another table/model (PRODUCTS). The ID being passed is the ASSIGNMENTS.ID, which is the PK of ASSIGNMENTS and the FK of PRODUCTS. I am not trying to join these 2 querysets. I need the user to see the information for the ASSIGNMENT first and then below I want them to see all of the PRODUCTS that belong to that ASSIGNMENT. I do not need to update/create data, so no POST is needed. Only want to retrieve, GET, data that exists. Below are the code for models.py, views.py, and templates. It works perfect with just ASSIGNMENTS. MODELS.PY class Assignments(models.Model): id = models.DecimalField(db_column='ID', primary_key=True, max_digits=9, decimal_places=0) name = models.CharField(db_column='NAME', unique=True, max_length=40) def __str__(self): return self.name + ' ' + '(' + '#' + str(self.id) + ')' class Meta: ordering = 'name', db_table = 'ASSIGNMENTS' class Products(models.Model): id = models.DecimalField(db_column='ID', primary_key=True, max_digits=11, decimal_places=0) assignment = models.ForeignKey(Assignments, models.DO_NOTHING, related_name='productsfor_assignment', db_column='ASSIGNMENT_ID', blank=True, null=True) def __str__(self): … -
Trying to verify a user with Django email confirmation, however some user's are getting this error when they try to confirm their email
I asked a variant of this question before, but realized I was very unclear. This is my attempt at doing a better job of explaining the issue. I send a link to a user's email to confirm sign-up after they have registered for the site. However, a small proportion of users are getting the following error when they try to confirm their email. Error: TypeError/activate/{uidb64}/{token}/ error 'AnonymousUser' object is not iterable I think the problem is that the activate function is not recognizing them. However, not sure how to make this activation link work if I send them back to the login page. Any ideas? Do I need to add something like if not user.is_authenticated then send them to login? But, how do I come back to activate function? Login is general in my app to all situations. Activate code: try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): .... do something else: return HttpResponse('Activation link is invalid!') Here is where I create the email: def activation_email(request): if request.user.is_authenticated: user=request.user message = render_to_string('email.html', { 'user':user, 'token':account_activation_token.make_token(user), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), }) ....send mail else: return redirect('somewhere_else') -
NoReverseMatch in Django 2
I'm kinda new at this, and I believe I have misunderstood some things so I'll try to describe it as best possible. I have 3 tables(models), Game, Chapter, Thread. Chapter and Thread are connected with the Game table. models.py class Game(models.Model): title = models.CharField(max_length=100) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title class Chapter(models.Model): title = models.CharField(max_length=80) content = models.CharField(max_length=10000, null=True) game = models.ForeignKey(Game, on_delete=models.CASCADE) def __str__(self): return self.chapter class Thread(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=1000, null=True) game = models.ForeignKey(Game, on_delete=models.CASCADE) def __str__(self): return self.title views.py def chapter(request, game_id): auth = top_menu = True chapters = Chapter.objects.filter(game=game_id) return render(request, 'chapters.html', {"chapters": chapters, "auth": auth, "top_menu": top_menu}) def thread(request, game_id): auth = top_menu =True threads = Thread.objects.filter(game=game_id) return render(request, 'threads.html', {"auth": auth, "threads": threads, "top_menu": top_menu}) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', index, name="index"), path('signup/', signup, name="signup"), path('logout/', logout_view, name="logout"), path('login/', login_view, name="login"), path('<int:game_id>/chapters/', chapter, name="chapter"), path('<int:game_id>/threads/', thread, name="thread"), ] index.html {% extends 'base.html' %} {% block content %} <div class="container"> <div class="wrapper"> <div class="row"> <div class="col-lg-12 text-center" style="margin-bottom:80px;"> <h1>Welcome to Solo Rpg Helper</h1> </div> </div> {% if auth %} <div class="row"> <div class="col-lg-12 text-center"> <h1>Your games:</h1> <ul class="list-group list-group-flush"> {% for game in games.all %} <a href="{% url … -
Django/Pandas - uploaded file gets 'MultiValueDictKeyError at /' followed by the entire database when I try to save the file to a form
I am new to Django and relatively new to python. I have written a program that allows a user to upload an excel file. The excel file is saved to a form in Django. I am unable to figure out how to save an uploaded file to my form after I run a script over it(the script uses pandas). When I try to upload the file I get 'MultiValueDictKeyError at /' followed by the entire database when I try to save the file to a form. My goal is for the user to be able to download the new file. My code is below. views.py def file_list(request): files = File.objects.all() return render(request, 'file_list.html',{ 'files':files }) def upload_file(request): if request.method == 'POST': uploaded_file = request.FILES['xlsx'] import pandas as pd df = pd.read_excel(uploaded_file) df.dropna(subset=['Email', 'First Name'], inplace=True) df.fillna('', inplace=True) df = df.applymap(str) df['Company'] = df['Company'].str.upper() df['First Name'] = df['First Name'].str.lower() df['First Name'] = df['First Name'].str.capitalize() df['Last Name'] = df['Last Name'].str.lower() df['Last Name'] = df['Last Name'].str.capitalize() df['Company'] = df['Company'].str.lower() df['Company'] = df['Company'].str.capitalize() df['Title'] = df['Title'].str.lower() df['Title'] = df['Title'].str.title() form = FileForm(request.POST, request.FILES[df.to_csv(index=False)]) if form.is_valid(): form.save() return redirect('file_list') else: form = FileForm() return render(request, 'upload_file.html', { 'form': form }) forms.py from django import forms … -
Django-tables2 Row Selection
How do I select a row from a table generated from django-tables2? I'd prefer not to have to select a row by checking a checkbox cell (selection = tables.CheckBoxColumn(accessor='pk')) in the row. -
Reverse for 'blog_detail' with no arguments not found. 1 pattern(s) tried: ['blog/(?P<pk>[0-9]+)$']
Reverse for 'blog_detail' with no arguments not found. Reverse for 'blog_detail' with no arguments not found. 1 pattern(s) tried: ['blog/(?P[0-9]+)$'] models.py class Blog(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=80) slug = models.SlugField(max_length=80, unique=True, db_index=True, blank=True, null=True) description = models.TextField(max_length=1080, blank=True, null=True) image = models.ImageField(upload_to='blog/') tags = models.CharField(max_length=30, blank=True, null=True) category2 = models.CharField(max_length=50, blank=True, null=True) category = models.ManyToManyField("BlogCategory") created_on = models.DateTimeField(default=timezone.now()) is_active = models.BooleanField(default=True) def __unicode__(self): return self.title def get_absolute_url(self): return reverse("blog_detail", kwargs={"pk": self.pk}) views.py class BlogDetail(DetailView): model = Blog queryset = Blog.objects.all() template_name = "testapp/blogd.html" urls.py from django.urls import path from .views import (BlogList, BlogDetail) urlpatterns = [ path('blog/l', BlogList.as_view(), name='blog_list'), path('blog/<int:pk>', BlogDetail.as_view(), name='blog_detail'), ] -
Failed lookup for key [start_index]
i got some problem with the pagination this is my code template {% for post in post %} <tr class="text-center"> <td> {{forloop.counter|add:post.start_index }} </td> {%endfor%} view.py def rankpag(request): with connection.cursor() as cursor: cursor.execute("SELECT c.CharName,gu.GuildName,c.Level,c.Family,c.Sex,c.Job,c.K1,c.K2,Str,Dex,Rec,Int,Luc,Wis,HP,MP,SP,g.Country FROM PS_GameData.dbo.Chars c JOIN PS_UserData.dbo.Users_Master m ON m.UserUID=c.UserUID JOIN PS_GameData.dbo.UserMaxGrow g ON g.UserUID=c.UserUID LEFT JOIN PS_GameData.dbo.GuildChars gc ON (gc.CharID=c.CharID and gc.Del=0) LEFT JOIN PS_GameData.dbo.Guilds gu ON gu.GuildID=gc.GuildID ORDER BY c.K1 DESC") row = cursor.fetchall() paginator = Paginator(row,10) page = request.GET.get('page') post = paginator.get_page(page) return render(request,'Ranks.html',{'post':post}) i added a pagination and it's working good but i want to count the row and this what i see -
Does the django_address module provide a way to seed the initial country data?
I'm using Django 2.0, Python 3.7, and MySql 5. I recently installed the django_address module. I noticed when I ran my initial migration based on my models.py file ... from django.db import models from address.models import AddressField from phonenumber_field.modelfields import PhoneNumberField class CoopType(models.Model): name = models.CharField(max_length=200, null=False) class Meta: unique_together = ("name",) class Coop(models.Model): type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() It created some address tables, including ... mysql> show create table address_country; +-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | address_country | CREATE TABLE `address_country` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) COLLATE utf8_bin NOT NULL, `code` varchar(2) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin | +-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ However, this table has no data in it. Is there a way to obtain seed data for the table generated by the module or do I need to dig it up on my own? -
Set the current user to the model when posting a form
I am trying to add the request user to a model. def fileupload(request): files = Download.objects if request.method == "POST" : form = DownloadForm(request.POST, request.FILES) if form.is_valid(): author = request.user savefile = form.save() savefile.save() My models is : class Download(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE, related_name="filedownload") upload = models.FileField(upload_to='uploads/') But the author is not updating, any clue ? -
Can assertFieldOutput be tested on fields that are not Text Input based?
https://docs.djangoproject.com/en/3.0/topics/testing/tools/#django.test.SimpleTestCase.assertFieldOutput Going over documentation of assertFieldOutput(), it shows the ease of testing user text input via a dictionary. The key acts as the input into the form and the value acts the cleaned data that is returned or returns whatever error that is supplied to the field. self.assertFieldOutput( EmailField, {'a@a.com': 'a@a.com'}, # valid email {'aaa': ['Enter a valid email address.']} # invalid email; results in validation error ) Given dictionary keys are hashable, is there no way to test fields that are non text based such as select menus like ModelMultipleChoiceField? -
Load testing throws Server 502 error: Bad Gateway after 700 users. Gunicorn, Gevent, Nginx, Django
I'm trying to reach 2000 concurrent users with my benchmarking tool. I'm using locust to simulate them. My server has 24vCPUs, 128GB RAM, 25SSD. I want to be able to serve 2000 concurrent users without errors but after only 700 users I run into trouble. Gunicorn I installed gevent to be able to serve async but this didn't change anything on my load test (can gevent not be working?). My systemd file is as follows: mysite-production.conf [Unit] Description=mysite production daemon After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/mysite/production/src ExecStart=/var/www/mysite/production/venv/bin/gunicorn --worker-class=gevent --worker-connections=1000 --workers=49 --bind unix:/var/www/mysite/production/sock/gunicorn --log-level DEBUG --log-file '/var/www/mysite/production/log/gunicorn.log' mysite.wsgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID [Install] WantedBy=multi-user.target According to my calculations: 49 x 1000 = 49000 requests per second that I could be serving. Instead at about 700 users I get the following error in my locust failures tab: # fails Method Name Type 1227 GET // HTTPError('500 Server Error: Internal Server Error for url: http://my.site.com//') It basically says I have a internal server error. when I open my gunicorn.log I see Ignoring EPIPE: gunicorn.log [2020-01-27 20:22:30 +0000] [13121] [DEBUG] Ignoring EPIPE [2020-01-27 20:22:31 +0000] [13121] [DEBUG] Ignoring EPIPE [2020-01-27 20:22:31 +0000] [13121] [DEBUG] Ignoring EPIPE [2020-01-27 20:22:31 +0000] [13121] [DEBUG] … -
Django Templates Rendering
We need to solve problem with reports rendering (mainly to Excel and CSV) in our Django projects. Actually we do not use report template. We simply generate them in backend with csv, xlsxwriter libs. What we would like to achieve is to prepare a template (sort of Django HTML template), to pass data into it and get rendered with data report. There is library https://templated-docs.readthedocs.io/ which can what we want. But it needs LibreOffice to be install which is extra 800 Mb to docker image size (install LibreOffice from this Dockerfile https://github.com/ipunkt/docker-libreoffice-headless/blob/master/Dockerfile). Maybe to run separate service... I believe there are approaches or even ready solutions exist. Can you give me a hint, please? -
How to create several resources with one request Django Rest Framework?
I got a model Slider that has a simple one to many relationship with ImageSlider, thanks to ModelViewSet I can create sliders and then create ImageSliders and asociate them with a slider. But I would also like to be able to just upload a bunch of images and make several SliderImages and asociate them with the same slider I mean I want to have both options but Im not sure how to do that and how to test it with something like Postman. I hope you guys can help me understand that since Im still learning about DRF Slider View """Slider view""" # Django REST Framework from rest_framework import viewsets # Serializers from api.sliders.serializers import SliderModelSerializer # Models from api.sliders.models import Slider class SliderViewSet(viewsets.ModelViewSet): """Slider viewset""" queryset = Slider.objects.all() serializer_class = SliderModelSerializer Slider Image View """Slider Images view""" # Django from django.shortcuts import get_object_or_404 # Django REST Framework from rest_framework import viewsets # Serializers from api.sliders.serializers import SliderImageModelSerializer # Models from api.sliders.models import SliderImage class SliderImageViewSet(viewsets.ModelViewSet): """Slider Image viewset""" queryset = SliderImage.objects.all() serializer_class = SliderImageModelSerializer Slider serializer """Slider Serializers""" # Django Rest Framework from rest_framework import serializers # Serializers from api.sliders.serializers import SliderImageModelSerializer # Model from api.sliders.models import Slider class … -
Django call 'id' expected a number but got string
Django errors with django-import-export libraries. I want to import data from excel to db via django admin. I use for it django-import-export, but i got Field 'id' expected a number but got 'HPI'. Excel file contains I found answer, that I have to add exclude = ('id',), but it didn't help. Also i did migrations, it didn't help too. How to fix it and have ability to import 6 columns data from excel to db via django admin? models.py from django_mysql.models import JSONField, Model from django.db import models class Category(Model): title = models.CharField(max_length=100) class Meta: ordering = ('-id',) verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.title class Tag(Model): title = models.CharField(max_length=100) class Meta: ordering = ('-id',) def __str__(self): return self.title class Type(Model): title = models.CharField(max_length=100) class Meta: ordering = ('-id',) verbose_name = 'Type' verbose_name_plural = 'Types' def __str__(self): return self.title class Macro(Model): type = models.ForeignKey( Type, max_length=100, null=True, blank=True, on_delete=models.SET_NULL) tags = models.ManyToManyField(Tag, blank=True) category = models.ForeignKey( Category, null=True, blank=True, on_delete=models.SET_NULL) abbreviation = models.CharField(max_length=100, unique=True) title = models.CharField(max_length=100, verbose_name='Title') content = models.TextField(max_length=1000, null=True, blank=True) class Meta: ordering = ('-id',) def __str__(self): return self.title admin.py from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin from .models … -
Django filter __in multiple fields
I have a model for user timetable. class Schedule(models.model): user = models.ForeignKey(User) day = models.SmallIntegerField() hour = models.SmallIntegerField() I would like to select common time slots for two given users A and B. Using this code: user_schedule = models.Schedule.filter(user=user_a) models.Schedule.filter(user=user_b).filter(day__in=user_schedule.values('day'),hour__in=user_schedule.values('hour')) The results returned don't use both fields to select. Inspecting the query shows that the query is not doing what I want WHERE ("profiles_schedule"."day" IN (SELECT U0."day" FROM "profiles_schedule" U0 WHERE U0."user_id" = 1) AND "profiles_schedule"."hour" IN (SELECT U0."hour" FROM "profiles_schedule" U0 WHERE U0."user_id" = 1) I need it to do something like: WHERE "profiles_schedule"."day", "profiles_schedule"."hour" IN (SELECT U0."day", U0."hour" FROM "profiles_schedule" U0 WHERE U0."user_id" = 1) If I normalize the model further by creating a day/hour lookup table it would make the selection easy but I feel like it doesn't really make sense to try to normalize two SmallINT fields as I would be creating 2 columns of SmallINT for the IDs anyway. Thanks! -
Django app_label is wrong on models
I have a Django DRF application. Here is my project structure. myproject/ myproject/ apps/ myApp1/ __init__.py admin.py models.py urls.py views.py myApp2/ __init__.py static/ manage.py and myINSTALLED_APPS contains: INSTALLED_APPS = [ 'apps.myApp1', 'apps.myApp2', ] When I went to ./manage.py shell_plus and run: SomeModel._meta.label I see myApp1 or myApp2 instead of apps.myApp1 && apps.myApp2. And even in migrations Models are referred as myApp1.Model or myApp2.Model not as apps.myApp1.Model or apps.myApp2.Model Is that expected ? I am pretty new to Django. Can anyone suggest what the mistake was? -
Django: how to control time format in DataTable?
I use DataTable in a Django project context pass to my template : Heures.objects.all() my problem concern heu_dat field that is display as 1 pm where 13:00:36.227396 is stored in my database I would like to display heu_dat like 13:00:36 (french format) models.py class Heures(models.Model): _safedelete_policy = SOFT_DELETE_CASCADE heu_ide = models.AutoField(primary_key=True) date = models.ForeignKey(Jours, on_delete = models.CASCADE, null=True) user = models.ForeignKey(Profile, on_delete = models.CASCADE, null=True) heu_dat = models.TimeField("Heure du pointage", null=True, blank=True,auto_now_add=True) heu_cod = models.IntegerField("Code employé", null=True, blank=True) heu_com = models.CharField("Commentaires", max_length = 150, null=True, blank=True) -
Can I use C# (Blazor) as front end instead of Javascript, while keeping my backend in Django?
I have learned Django for my back end development, the course I'm taking teaches Javascript for front end, but I heard about a platform Blazor that uses C# to replace Javascript, I'm interested in this cause I already know C# as it was my first language and am quite fond of the syntax, if possible where should I start Thanks -
Should I use One-to-Many to Many-to-Many fields?
I have an opera model: class Opera(MPTTModel): name = models.CharField(max_length=8000, null=True, blank=True) librettist = models.ForeignKey(Person, verbose_name=_('librettist'), null=True, blank=True, related_name='person', on_delete=models.PROTECT) The structure of the Opera is a tree structure: Opera (Top level) |--> Overture |--> Aria #1 |--> Aria #2 Each opera or aria has a cast of characters: class Cast(models.Model): character_name = models.CharField(max_length=100, null=True, blank=True) voice_type = models.ForeignKey(Instrument, null=True, blank=True, on_delete=models.CASCADE) There is also a mapping table to map Cast to the Opera model: class WorkCast(models.Model): opera = models.ForeignKey(Opera, verbose_name=_('opera'), related_name='workcast', null=True, blank=True, on_delete=models.PROTECT) cast = models.ForeignKey(Cast, verbose_name=_('cast'), related_name='workcast', null=True, blank=True, on_delete=models.PROTECT) An opera (top level) has the entire cast mapped to it. Aria #1 or Aria #2 will have a subset of cast map to it. When I am in the admin menu, I want to be able to select the opera model and link multiple cast member to it. Does this mean that WorkCast model needs to have Many-to-many field to cast or Foreign Key to cast? It seems like I have to force a many-to-many relationship in order to use the inline feature in admin.py? -
Django order many to many relationship
I have been playing around with Django's many to many field with the following models: class ProjectLanguage(models.Model): title = models.CharField(max_length=15) def __str__(self): return self.title class Project(models.Model): title = models.CharField(max_length=30) img = models.CharField(max_length=50) main_text = models.TextField(default="main project description ...", null=True, blank=True) languages = models.ManyToManyField(ProjectLanguage) def __str__(self): return self.title I want to get a list of projects ordered by their ProjectLanguage title. How do I achieve this with Django ? Thanks Mark -
Python/Django Model with 2 or more foreign keys of the same name
I'm getting an error which states that my group model has more than one Foreign key to Person personid = models.ForeignKey(Person, db_column='PersonId', related_name='Persons', on_delete=models.CASCADE, blank=True, null=True ) createdby = models.ForeignKey(Person, db_column='createdBy', related_name='createdPerson', on_delete=models.SET_NULL, max_length=36, blank=True, null=True,) archivedby = models.ForeignKey(Person, db_column='archivedBy', related_name='archivedPerson', on_delete=models.SET_NULL, max_length=36, blank=True, null=True,) I have done some research to resolve this issue and all of the solutions lead me to using the related_name attribute for each model item, which I did. I'm still getting this error. What am I missing? Any suggestions? -
How to display only the first occurrence of an item in a set on a Django template?
I am learning Django, so this might not be the best way to do what I want. What I am trying to do here is to display an item that has been selected multiple times in a cart, only once (and the number of times it has been selected next to it) I have been all day trying to find a way but the closest thing I managed to do is, inside the views, to produce two sets: single_items, and multiple_items. I have no problems displaying an item which has been selected only once, but when it comes to items selected multiple times I can only display them n times with the number of occurrences next to it, as shown in the picture Although I would rather do all the calculation with python code (in views.py) a solution with Django template language will do to me. Please consider that I need to pass the item ID in the url in order to make the remove link to work. here is views.py from django.shortcuts import render, redirect from .models import Cart, Item, CartItem from django.db.models import Sum # Create your views here. def home(request): items = Item.objects.all() carts = Cart.objects.all() length … -
How can I annotate a django-mptt TreeQuerySet from aggregate values of children?
Suppose I have the following django-mptt tree: Root node Node 1 Node 2 Node 3 Node 3.1 Node 3.2 ... Every node has the same fields with numerical values (e.g. area, value etc). Can I use a TreeQuerySet to aggregate values (Sum, Count, Avg etc.) of a node with values from its children and its own values? Or should I look into annotating instead of aggregating? Any help would be appreciated. -
Django form validation not working for all the fields
new in the field and struggling with a form validation in practice. I have created a form which i use as data input for a search in the DB. Form validation is only being triggered for the first field while the others seems not to be taken in consideration, bellow the code: Form description: class SearchForm(forms.Form): cnp_nbr = forms.IntegerField(label='CNP', widget=forms.TextInput(attrs={'class': 'form-control' }), required=False) first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': 'form-control'}), required=False) last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': 'form-control'}), required=False) class Meta(): model = Clients fields = ('cnp_nbr','first_name','last_name') def clean(self): # most used!!! all_clean_data = super().clean() cnp_nbr = all_clean_data['cnp_nbr'] first_name = all_clean_data['first_name'] last_name = all_clean_data['last_name'] if cnp_nbr is None or (first_name is None and last_name is None): raise forms.ValidationError("Enter f1 or f2&f3") super().clean() Views: class ClientsSearch(generic.FormView): form_class = forms.SearchForm template_name = "administration/clients_search.html" success_url = reverse_lazy('administration:searchresults') def form_valid(self, form): self.request.session['cnp_nbr'] = form.cleaned_data['cnp_nbr'] self.request.session['first_name'] = form.cleaned_data['first_name'] self.request.session['last_name'] = form.cleaned_data['last_name'] return super().form_valid(form) class SearchResults (generic.ListView): model = models.Clients template_name='administration/search_results.html' context_object_name = 'all_search_results' def get_queryset(self): return self.model.objects.filter( Q(cnp_nbr__exact=self.request.session['cnp_nbr']) | Q(first_name__exact=self.request.session['first_name']) & Q(last_name__exact=self.request.session['last_name']) ) HTML for search form: <form method="POST" > {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary" id="search_submit" name = "search_submit" type="submit" > Search</button> </form> Validation is working only for cnp_nbr, i even tested them …