[Django] How to give input values in advance with ModelForm

What is Model Form?

A ModelForm is a pre-made instance that you can call with django.forms.Modelform. By creating a Form class that inherits this instance, you can refer to the table defined in Models.py as it is. In other words, it is used when you want to register or update the database by inputting a form from the user.

Where do you use this technique?

For example, for a data model that has "title, current time, creator" in the fields, when implementing form input from the user, the task of telling the user the current time and creator will lower the UX. This can be achieved by giving an initial value to the form and hiding the corresponding field when you want to give information that the user does not need to bother with or automatically.

First of all, how to set hiding on the template

forms.py


from django import forms
from .models import Event


class EventCreateForm(forms.ModelForm):

    class Meta:
        model = Event
        fields = ('eventtitle','eventdate','location','agenda','author')
        widgets={'author':forms.HiddenInput()
        }

To briefly explain to those who do not know ModelForm, basically various conditions are passed in the Meta class. In the model variable, specify the Event class of models.py by instantiating it. In the fields variable, specify the fields to be included in the form as a list type.

The widgets variable allows you to specify various options such as changing the input display of the field in html and specifying an error message.

** This time, first, the author field is set to Hidden Input in this widgets to hide it. ** **

Add form information in views.py

views.py


from django.contrib.auth.models import User
from .forms import EventCreateForm

def createeventfunc(request):
    if request.method == 'POST':
        form =EventCreateForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('Transition destination')
        return render(request,'createevent.html',{'form':form})
    #At the time of Get method, execute below
    #default_Set the value to the author field in data
    else:
        default_data = {'author':User.objects.get(pk=request.user.pk)}
        form = EventCreateForm(default_data)
        return render(request,'createevent.html',{'form':form})

The default value is given as an argument when creating a form object. In the above example, when url and createeventfunc () are called by Get method, form object is created with author: logged-in user id (pk) as default data. And we are rendering that form object. When submit is pressed in the form (assuming it is a POST submission), the above if statement is executed. All you have to do is form.save () to complete the registration in the database.

Recommended Posts

[Django] How to give input values in advance with ModelForm
How to check ORM behavior in one file with django
How to reflect CSS in Django
How to get started with Django
How to authenticate with Django Part 2
How to authenticate with Django Part 3
How to do arithmetic with Django template
How to delete expired sessions in Django
How to work with BigQuery in Python
How to handle consecutive values in MySQL
How to do Server-Sent Events in Django
How to convert DateTimeField format in Django
How to store CSV data in Amazon Kinesis Streams with standard input
How to deal with garbled characters in json of Django REST Framework
How to deal with memory leaks in matplotlib.pyplot
[REAPER] How to play with Reascript in Python
How to implement Rails helper-like functionality in Django
How to develop a cart app with Django
How to reflect ImageField in Django + Docker (pillow)
How to run some script regularly in Django
How to deal with run-time errors in subprocess.call
How to implement "named_scope" of RubyOnRails with Django
How to use tkinter with python in pyenv
How to create a Rest Api in Django
How to hide user input in PySimple GUI
How to convert / restore a string with [] in python
How to get multiple model objects randomly in Django
Explain in detail how to make sounds with python
How to deal with pyenv initialization failure in fish 3.1.0
How to do zero-padding in one line with OpenCV
How to run tests in bulk with Python unittest
How to load files in Google Drive with Google Colaboratory
How to access with cache when reading_json in pandas
How to use bootstrap in Django generic class view
How to extract null values and non-null values with pandas
How to right click using keyboard input in RPA?
How to upload files in Django generic class view
How to use Decorator in Django and how to make it
How to reference static files in a Django project
[Python] How to output the list values in order
How to deal with Executing transaction: failed in Anaconda
How to use fixture in Django to populate sample data associated with a user model
How to write custom validations in the Django REST Framework
How to embed multiple embeds in one message with Discord.py
[Go language] How to get terminal input in real time
How to use Laravel-like ORM / query builder Orator in Django
How to extract any appointment in Google Calendar with Python
How to update user information when logging in to Django RemoteUserMiddleware
How to register the same data multiple times with one input on the Django management screen
How to manipulate the DOM in an iframe with Selenium
How to resolve CSRF Protection when using AngularJS with Django
How to cast with Theano
How to generate a query using the IN operator in Django
How to get all the keys and values in the dictionary
[AWS] How to deal with "Invalid codepoint" error in CloudSearch
How to Alter with SQLAlchemy?
I can't log in to the admin page with Django3
For beginners, how to deal with common errors in keras
How to separate strings with','
How to RDP with Fedora31
In Django, how to abbreviate the long displayed string as ....