Answer the question
In order to leave comments, you need to log in
How to display Select form with condition in Django3?
I have a fill form where there is a Select that displays a field inherited from another model. Objects must have their relevance, that is, if the date is "less than" today, then the object should not be displayed in the select tag on the site. He takes everything out of me.
The question is how to make it display only actual events, that is, how to create a condition?
Main model
import datetime
from django.db import models
from TimeTable.models import TimeTable
class Application(models.Model):
name = models.CharField(max_length = 100, verbose_name = 'Имя', null = True)
surname = models.CharField(max_length = 100, verbose_name = 'Фамилия', null = True)
middlename = models.CharField(max_length = 100, verbose_name = 'Отчество', null = True)
number = models.CharField(max_length = 20, null = True)
event = models.ForeignKey(TimeTable, on_delete = models.PROTECT, verbose_name = 'Мероприятие')
comment = models.TextField(verbose_name = 'Комментарий', null = True, blank = True)
date = models.DateField(verbose_name = 'Дата', default = datetime.date.today)
def __str__(self):
return str(self.name) + ' ' + str(self.middlename)
class Meta:
verbose_name_plural = 'Заявки'
verbose_name = 'Заявка'
ordering = ['-date']
from django.db import models
class TimeTable(models.Model):
start = models.CharField(max_length = 100, verbose_name = 'Старт')
finish = models.CharField(max_length = 120, verbose_name = 'Финиш')
date = models.DateField(verbose_name = 'Дата')
time = models.TimeField(verbose_name = 'Время')
meeting_place = models.CharField(max_length = 120, verbose_name = 'Место сбора')
def __str__(self):
return str(self.start) + ' / ' + str(self.finish)
class Meta:
verbose_name_plural = 'Таблицы'
verbose_name = 'Таблица'
ordering = ['-date']
from django.shortcuts import render, HttpResponse, redirect
from .forms import ApplicationForm
def index(request):
error = ''
if request.method == 'POST':
form = ApplicationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
error = 'ERROR'
form = ApplicationForm()
context = {
'form' : form,
'error' : error
}
return render(request, 'Application/Application.html', context)
from django.forms import ModelForm, TextInput, Textarea, Select
from .models import Application
class ApplicationForm(ModelForm):
class Meta:
model = Application
fields = ['name', 'surname', 'middlename', 'number', 'event', 'comment']
widgets ={
'name' : TextInput(attrs = {
'class' : 'form-application',
'placeholder' : 'Имя'
}),
'surname' : TextInput(attrs = {
'class' : 'form-application',
'placeholder' : 'Фамилия'
}),
'middlename' : TextInput(attrs = {
'class' : 'form-application',
'placeholder' : 'Отчество'
}),
'number' : TextInput(attrs = {
'class' : 'form-application',
'placeholder' : 'Номер'
}),
'event' : Select(attrs = {
'class' : 'form-application',
'selected' : 'Выберите мероприятие'
}),
'comment' : Textarea(attrs = {
'class' : 'form-application',
'placeholder' : 'Комментарий (необязательно)'
}),
}
Answer the question
In order to leave comments, you need to log in
Thanks for the Django tip. How to display a ForeignKey field in a template with a certain condition?
You need to access the form and change the objects:
views.py:
from django.db.models import Q
from datetime import date, datetime
day_today = date.today()
time_now = datetime.now().time()
form = ApplicationForm()
# Фильтруем прошедшие ивенты (Конструкця с Q и палочкой позволяет подставить ИЛИ)
form.fields['event'].queryset = TimeTable.objects.filter((Q(date = day_today) & Q(time__gt = time_now)) | Q(date__gt = day_today))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question