django 表单系统 之 forms.ModelForm

继承forms.ModelForm类实现django的表单系统

有时,我们在前端定义的<form>表单和后端定义的model结构基本上是一样的,那么我们可以直接在后端定义model后,定义一个modelform,实例化,传到前端后用{{ form }}标签直接生成html表单

参考:

http://blog.csdn.net/alex_chen_16/article/details/50830543

https://www.cnblogs.com/sss4/p/7112546.html

官方文档:

http://python.usyiyi.cn/translate/django_182/topics/forms/modelforms.html

1、首先定义好model类:

models.py文件中:

class autotaggingtaskinfo(models.Model):
    taskid=models.IntegerField()#auto tagging task id
    username=models.CharField(max_length=200)# not null
    picnums=models.IntegerField()# the number of the pictures in the task
    priority=models.IntegerField()# the priority of the task (bigger first)
    status=models.IntegerField()# the status of the task (0-pause, 1-running, 2-error, 3-finished)
    labels=models.CharField(max_length=200)# the labels that will tag on pictures, separated by comma (e.g. "gender,age,position")
    remark=models.CharField(null=True,max_length=200)

2、然后继承ModelForm实现表单类:

form.py文件中:

class AutotaggingFrom(forms.ModelForm):
    class Meta: # 内部类名必须为Meta
        model=autotaggingtaskinfo #model字段填要用来构造表单的model类的名字
        exclude=['username','status'] #exclude字段指定model类中不显示到前端表单中的字段名(也可以用 include字段指定model类中要显示到前端表单中的字段名,include=['taskid','picnums',priority','labels','remark'])

 

3、然后在view中创建ModelForm实例并传到前端

views.py中:

@login_required
def taggingView(request):
    form = AutotaggingFrom(request.POST or None) # 创建ModelForm实例
    if (form.is_valid()):#如果是POST请求提交上来的有内容的表单,则将表单内容存入数据库
        form.save()
    return render(request, 'auto_tagging.html',locals()) # 将form对象传到前端显示表单

 

4、在前端html中用{{ form }}调用表单

auto_tagging.html中:

<form align="center">
    {{ form.as_p }}
    <input type="submit" value="tijiao">
</form>

form.as_p表示以p标签形式显示表单(还可以用form.as_table等)

 

 

 

原文地址:https://www.cnblogs.com/zealousness/p/8757177.html