Django Form 实时从数据库中获取数据的操作方法

yipeiwu_com5年前Python基础

Django Form 实时从数据库中获取数据 ,具体内容如下所示:

修改 models.py 添加

class UserType(models.Model):
 caption = models.CharField(max_length=32)

执行命令,生成数据库

python manage.py makemigrations
python manage.py migrate

修改 forms.py 添加

from app01 import models
class DBForm(DForms.Form):
 host = fields.CharField()
 host_type = fields.IntegerField(
  widget=widgets.Select(choices=[])
 )
 def __init__(self, *args, **kwargs):
  super(DBForm, self).__init__(*args, **kwargs)
  self.fields['host_type'].widget.choices = models.UserType.objects.all().values_list('id', 'caption') # 自定义构造方法,实时从数据库中获取数据

PS:Django从表单中获取数据

提交了表单后,我们需要从获取表单中的数据

#views.py
def index(request):
 if request.method == "GET":
  nameform = NameModelForm()
  return render(request, "form/index.html",locals())
 if request.method == "POST":
  nameform = NameModelForm(request.POST)
  if nameform.is_valid():
   firstname = nameform.cleaned_data["firstname"] 
   secondname = nameform.cleaned_data["secondname"]
   a = Name(firstname = firstname,secondname = secondname)
   a.save()
   print(firstname+secondname)
   return HttpResponse("提交成功")
  else:
   error_msg = nameform.errors.as_json()
   print(error_msg)
   return HttpResponse(error_msg)

首先引入了自定义的表单类

如果request.method == “GET”

然后实例化表单类,render返回

如果request.method == “POST”

就先实例化接受了POST消息的表单类

如果表单类的数据是可获取的

我们使用一个变量接收nameform.cleaned.cleaned_data[“firstname”],就是从表单的firstname字段获取的信息。然后提交给数据库。这样就完成了一次提交记录表单的操作。

总结

以上所述是小编给大家介绍的Django Form 实时从数据库中获取数据的操作方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

python之wxPython应用实例

python之wxPython应用实例

本文实例讲述了python之wxPython的使用方法,分享给大家供大家参考。具体方法如下: 先来看看效果,这里加载一张图片: 代码如下: #!/usr/bin/env pytho...

python实现合并多个list及合并多个django QuerySet的方法示例

本文实例讲述了python实现合并多个list及合并多个django QuerySet的方法。分享给大家供大家参考,具体如下: 在用python或者django写一些小工具应用的时候,有...

Django中在xadmin中集成DjangoUeditor过程详解

Django中在xadmin中集成DjangoUeditor过程详解

环境 python版本:3.6 django:1.10.8 1.下载xadmin https://github.com/sshwsfc/xadmin 下载DjangoUeditor ht...

Python threading多线程编程实例

Python 的多线程有两种实现方法: 函数,线程类 1.函数 调用 thread 模块中的 start_new_thread() 函数来创建线程,以线程函数的形式告诉线程该做什么 复制...

Python中使用socket发送HTTP请求数据接收不完整问题解决方法

由于工作的需求,需要用python做一个类似网络爬虫的采集器。虽然Python的urllib模块提供更加方便简洁操作,但是涉及到一些底层的需求,如手动设定User-Agent,Refer...