[PYTHON] Get the value from the [Django] Form

Execution environment

The execution environment is as follows. Python3 -- Python 3.9.0 Django -- 3.1.3

About getting values ​​from Form in Django

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.

situation

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

Get the value from the [Django] Form
Get only the text from the Django form.
DJango Note: From the beginning (form processing)
[Django 2.2] Sort and get the value of the relation destination
[Django] Give Form a dynamic initial value from Model
Get the value while specifying the default value from dict in Python
[Beginner] Get from Django Query database
Get the address from the zip code
Get the query string (query string) in Django
Get the client's IP address in Django
Get the value of the middle layer of NN
Get the address from latitude and longitude
Get wordpress posts from the past week
[Python] Get the main color from the screenshot
Django Contact Form 2
Django Suggested Form
Get news from three major mobile companies using Django and the News API
Django Form Gleaning
Django contact form
Get the contents of git diff from python
DJango Memo: From the beginning (creating a view)
DJango Memo: From the beginning (Error screen settings)
[Django] Create a form that automatically fills in the address from the zip code
The wall of changing the Django service from Python 2.7 to Python 3
Get the value of a specific key in a list from the dictionary type in the list with Python
Get the GNOME version
[Python] Get the text of the law from the e-GOV Law API
Read the setting value from Google Spread Sheet gssetting
Django memo # 1 from scratch
Get the return code of the Python script from bat
[C language] [Linux] Get the value of environment variable
Set the form DateField to type = date in Django
DJango Note: From the beginning (creating a view from a template)
Get the value selected in Selenium Python VBA pull-down
[Django] Rename the project
Get the MIME Type
Get the output value of the command (as received by xargs)
DJango Note: From the beginning (simplification and splitting of URLConf)
Memo to get the value on the html-javascript side with jupyter
Get your heart rate from the fitbit API in Python!
The story of a Django model field disappearing from a class
How to do the initial setup from Django project creation
How to get the last (last) value in a list in Python
DJango Memo: From the beginning (more edits to the management screen)
I tried to get various information from the codeforces API
Relationship between Bound / Unbound and initial value of Django2 Form
Extract the value closest to a value from a Python list element
Get structural data from CHEMBLID
Django starting from scratch (part: 2)
Get started with Django! ~ Tutorial ⑤ ~
How to get the pixel value of the point from the satellite image by specifying the latitude and longitude
Let's search from the procession
Get the number of digits
Get started with Django! ~ Tutorial ④ ~
I tweeted from the terminal!
Get clipboard from Maya settings
Get started with Django! ~ Tutorial ⑥ ~
Use django model from interpreter
Template registration from Django Bootstrap
Maya | Get the workspace path
Python> dictionary> get ()> optional value