The execution environment is as follows. Python3 -- Python 3.9.0 Django -- 3.1.3
This time, when I was creating a web application with Django, I was having trouble getting the value from the Form, so I will write it in a memo. Also, I'm just starting to learn Django and all the code is inefficient, but I'd appreciate it if you could point out anything.
The situation is to get the value of the object selected in Form and set the checkbox of that object to True. Specifically, we implemented the implementation of selecting a pre-registered schedule in Form, setting that schedule as "this month's schedule", and displaying it.
The model of Schedule is shown below.
models.py
class Schedule(models.Model):
"""Schedule"""
holdmonth = models.CharField('Date', help_text="○ year ○ month", unique=True)
theme = models.TextField('theme', max_length=50)
now = models.BooleanField('Select current theme',default=False)
Let the schedule with the field now of this model be True be "Schedule of the Month". I created the following Form and View to select the schedule I want to set.
forms.py
class ScheduleSelectForm(forms.Form):
choice = forms.ModelChoiceField(models.Schedule.objects, label='Date', empty_label='Please select')
view.py
def schedule_select(request):
if request.method == "POST":
form = ScheduleSelectForm(request.POST)
if form.is_valid():
selected_schedule = form.cleaned_data.get('choice')
data = Schedule.objects.all().filter(holdmonth=selected_schedule).last()
#Uncheck other themes
if Schedule.objects.all().filter(now=True).exists():
before_now = Schedule.objects.all().filter(now=True).last()
before_now.now = False
before_now.save(update_fields=['now'])
else:
pass
data.now = True
data.save(update_fields=['now'])
params = {'message': 'Classroom schedule', 'data': data}
return render(request, 'MySite/admin_page.html', params)
else:
form = ScheduleSelectForm()
context = {'form':form}
return render(request, 'MySite/schedule_select.html', context)
Selected in Form
selected_schedule = form.cleaned_data.get('choice')
By doing, you can get the value selected in Form. With ○○ .is_valid (), validate whether there is an error in the value entered in the form, and then validate it. ○○ .cleaned_data ('field name') seems to format and return the validated data according to the type. I didn't understand these and couldn't get the value selected in Form, but now I can handle the value from Form freely with the above method.
Recommended Posts