发布时间: 2023-5-24 文章作者: myluzh 分类名称: Python 朗读文章
from django.forms import Form class MyForm(Form): user = forms.CharField(widget=forms.Input) pwd = form.CharFiled(widget=forms.Input) email = form.CharFiled(widget=forms.Input) def user_add(request): if request.method == "GET": form = MyForm() return render(request, 'user_add.html', {"form": form})user_add.html
<form method="post"> <!--以前的写法写input,比较麻烦--> <input type="text" class="form-control" placeholder="用户名" name="user"> <!--使用Form组件后现在的写法--> {{ form.user }} {{ form.pwd }} {{ form.email }} <!--或者直接for循环循环输出也是可以的--> {% for field in form%} {{ field }} {% endfor %} </form>
class UserInfo(models.Model): """员工表""" name = models.CharField(verbose_name="名称", max_length=16) password = models.CharField(verbose_name="密码", max_length=64) age = models.IntegerField(verbose_name="年龄") wallet = models.DecimalField(verbose_name="钱包余额",max_digits=10, decimal_places=2, default=0) create_time = models.TimeField(verbose_name="创建时间", ) depart = models.ForeignKey(verbose_name="部门", to="Department",to_field="id", on_delete=models.SET_NULL,null=True, blank=True, ) gender_choices = ( (0, "未知"), (1, "男"), (2, "女"), ) gender = models.SmallIntegerField(verbose_name="性别",choices=gender_choices)views.py
# 首先导入ModelForm from django.forms import ModelForm """ 在视图函数中定义一个类,比如就叫MyForm,这个类要继承ModelForm。 在这个类中再写一个原类Meta(规定写法,并注意首字母是大写的) """ class MyForm(ModelForm): class Meta: # 对应APP应用中的Model中的类 model = day16.models.UserInfo # Model中的类里面声明的字段,也可以直接使用fields="__all__"列出所有字段 fields = ["name", "password", "age"] def user_add(request): if request.method == "GET": form = MyForm() return render(request, 'user_add.html', {"form": form})user_add.html
标签: django
发表评论