赞
踩
1.form组件
views.py
class MyForm(Form): #继承Django中的Form类
name = forms.CharField(widget=forms.Input) #widget=forms.Input引入组件
pwd = forms.CharField(widget=forms.Input)
def user_add(request):
if request.method == "GET":
form = MyForm() #引入form类
return render(request, 'user_add.html', {
"form": form}
user_add.html
<!--方法1--> <form method="post"> { { form.name }} { { form.pwd }} <!--<input type="text" name="name" >--> <input type="submit" value="提 交"> </form> <!--方法2:循环显示--> <form method="post"> {% for field in form %} { { field}} {% endfor %} <!--<input type="text" name="name" >--> <input type="submit" value="提 交"> </form>
2.ModelForm组件
views.py
class MyForm(ModelForm): #继承ModelForm类
xx = form.Charfield
class Meta:
model = UserInfo #在models.py中定义的表类
fields = ["name", "pwd", "age", xx] #需要显示的字段(来源于表头),和自定义字段xx
阶段1
views.py
from django import forms #引入
class UserModelForm(forms.ModelForm):
class Meta:
model = models.UserInfo
fields = ["name", "pwd", "age"] #UserInfo表中一部分字段
#exclude = ['level'] #配合"__all__"使用
#fields = "__all__" #取到所有字段
def user_model_form_add(request):
"""新增人员(ModelForm版本)"""
form = UserModelForm()
return render(request, 'user_model_form_add.html', {
'form': form})
user_model_form_add.html
<body>
<form method="post">
{% csrf_token %}
{
{form.name}} <!--无需input标签,即可生成效果-->
{
{form.pwd}}
{
{form.age}}
</body
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。