[PYTHON] Django's Model Form was amazing.

A form that sets the values of the form to the model. That is the model form

If it's a normal framework, When you register the model in the database, you will set the value in the field one by one.

SomeCreateProcess.py


#How to set normally
someModel.name = name
someModel.user = user
....

Django ModelForm solves that problem. Suguremono that automatically sets the value received from the request in the model and even registers it

Easy to implement. Just inherit ModeForm and put the metaclass inside.

modelsModelForm.py


from django import forms

from memFrame.models.SomeModel import SomeModel 

'''
Model form for Honya Honya
@author Prautla
'''
class PictUploadForm(forms.ModelForm):
    class Meta:
        model = SomeModel #Secure a pointer to the model
        fields = ['name', 'user' ....]   #Declare a field

Actually use

The rest is easy. Just pass the POST body of the request

SomeCreateProcess.py


someModelForm:SomeModelForm= SomeModelForm(request.POST, instance=SomeModel()) #in this case"instance="Is optional
someModelForm.save()

Pass the value not passed from POST to the instance argument You can set it freely by putting it in the model.

SomeCreateProcess.py


obj:SomeModel = SomeModel()
obj.mailAddress = "[email protected]"
obj.sex = "Man"

someModelForm:SomeModelForm= SomeModelForm(request.POST, instance=obj)
someModelForm.save()

Recommended Posts

Django's Model Form was amazing.
Benefits of refining Django's Model
Limit Views using Django's Permission model
[My note] Django's custom User model