Answer the question
In order to leave comments, you need to log in
How to filter a request on multiple fields from a form in Django?
There is a table with contacts in which it is necessary to return elements according to the data from the filter form. There are several filters, one for each field of the model. I can't figure out how to pass data from forms through a GET request to a filter in order to send the correct list of objects to the template. Can someone tell me how to implement such filtering.
contacts.html
<form class="d-flex" method="get" action="{% url 'contacts' %}">
{% csrf_token %}
{{ subjectFilter.subject }}
{{ typeFilter.type }}
{{ infoFilter.info }}
{{ dateFilter.date }}
<button type="submit" class="btn btn-outline-success">Искать</button>
</form>
class ContactListView(View):
def get(self, request):
contacts = Contact.objects.all()
addContact = AddContactForm
editContact = EditContactForm
addType = AddTypeForm
addSubject = AddSubjectForm
typeFilter = TypeFilter
subjectFilter = SubjectFilter
infoFilter = InfoFilter
dateFilter = DateFilter
return render(request, 'contacts.html', {
'contacts': contacts,
'addContact': addContact,
'addType': addType,
'addSubject': addSubject,
'editContact': editContact,
'typeFilter': typeFilter,
'subjectFilter': subjectFilter,
'infoFilter': infoFilter,
'dateFilter': dateFilter
})
def post(self, request):
if request.method == 'POST':
form = AddContactForm(request.POST)
if form.is_valid():
# сохранение формы
contact = Contact() # новый объект
contact.type = form.cleaned_data['type']
contact.subject = form.cleaned_data['subject']
contact.info = form.cleaned_data['info']
contact.date = datetime.date.today()
contact.KEY = contact.id
contact.save()
return HttpResponseRedirect('/contacts/')
class Type(models.Model):
name = models.CharField('Название', max_length=50)
def __str__(self):
return self.name
class Subject(models.Model):
name = models.CharField('Имя', max_length=50)
def __str__(self):
return self.name
class Contact(models.Model):
KEY = models.IntegerField('Идентификатор', default=None, null=True, blank=True)
info = models.CharField('Инфо', max_length=100)
date = models.DateField(default=datetime.date.today(), verbose_name='Дата добавления')
type = models.ForeignKey(Type, verbose_name='Тип', on_delete=models.CASCADE, default=None)
subject = models.ForeignKey(Subject, verbose_name='Человек', on_delete=models.CASCADE, default=None)
def __str__(self):
return self.info
Answer the question
In order to leave comments, you need to log in
1. Why is there a form for each filter, can it still lead to one?
2. AddContactForm is the same ModelForm, so work with it correctly, and not through cleaned_data
3. Either create a dictionary from filters and do it objects.filter(**словарь)
dynamically using a Q-object.
PS and read the rules of the site, about spam tags
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question