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.
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.
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. ** **
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