How to use ModelForm in Django?
In Django, ModelForm is used to create forms based on a model. Here are the basic steps for using ModelForm:
- Create a form class that inherits from django.forms.ModelForm and specify the model attribute as the model to base it on.
from django import forms
from myapp.models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__' # 或者指定需要的字段
- Use ModelForm in the view to handle form data.
from myapp.forms import MyModelForm
def my_view(request):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
form.save()
# 处理表单提交成功后的逻辑
else:
form = MyModelForm()
return render(request, 'my_template.html', {'form': form})
- Using ModelForm form fields in a template:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">提交</button>
</form>
By following the above steps, you can use ModelForm in Django to create model-based forms, handling form data validation and saving.