继承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等)

最新文章

  1. css小技巧
  2. Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端
  3. 高效的INSERT INTO SELECT和SELECT INTO
  4. 每个软件都自己把操作系统的host配置项加到内存中供频繁调用
  5. HttpServletRequest学习
  6. 从svn检出的项目如何编译
  7. C++面向对象编程初步
  8. Android 无法Bind Service
  9. asp.net如何删除文件夹及文件内容操作
  10. mongoDB &amp; Nodejs 访问mongoDB (二)
  11. 博弈论(Game Theory) - 04 - 纳什均衡
  12. 【移动开发】binder阻塞/非阻塞与单向/双向的问题
  13. Python—day18 dandom、shutil、shelve、系统标准流、logging
  14. C#设计模式(17)——观察者模式
  15. Linux修改挂载目录名称
  16. python练习题-day13
  17. 不同AI学科之间的联系
  18. Django之crm
  19. ASP.NET MVC加载用户控件后并获取其内控件值或赋值
  20. ES6的Promise对象

热门文章

  1. JSON 常用数据转换
  2. matplotlib之设置极坐标起点的位置
  3. Makefile 自动变量之 $(@D),$(@F)
  4. ORACLE修改列名与列类型
  5. springmvc-servlet.xml
  6. hive 字符集问题 报错 Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(message:For direct MetaStore DB connections,
  7. linux怎么发邮件
  8. 【Python】分享使用的插件文件链接(实时更新)
  9. AWT从概念产生到完成实现只用了一个月
  10. ubuntu 自动清理/tmp目录