标签:ble form ida length png go import div for cts
顾名思义,Model + Form == ModelForm。model和form的合体,所以有以下功能:
model有操作数据库的字段,form验证也有那几个字段,虽然耦合度降低,但是代码是有重复的。如果利用model里的字段,那是不是form里的字段就不用写了。
1、models.py文件
class UserType(models.Model):
caption = models.CharField(max_length=32)
class User(models.Model):
username = models.CharField(max_length=32)
email = models.EmailField(max_length=32)
#指定关系一对多,指定哪张表,指定哪个字段
user_type = models.ForeignKey(to=‘UserType‘,to_field=‘id‘)
2、forms.py文件
from django import forms
from django.forms import fields
class UserInfoForm(forms.Form):
username = fields.CharField(max_length=32)
email = fields.EmailField(max_length=32)
user_type = fields.ChoiceField(
choices=models.UserType.objects.values_list(‘id‘,‘caption‘)
)
# 下面的操作是让数据在网页上实时更新。
def __init__(self, *args, **kwargs):
super(UserInfoForm,self).__init__(*args, **kwargs)
self.fields[‘user_type‘].choices = models.UserType.objects.values_list(‘id‘,‘caption‘)
3、前端文件index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/index/" method="POST" novalidate="novalidate">
{% csrf_token %}
{{ obj.as_p }}
<input type="submit" value="提交">
</form>
<table>
<th>
<tr>用户名</tr>
<tr>邮箱</tr>
<tr>角色</tr>
</th>
{% for obj in new_obj %}
<tr>
<td>{{ obj.username }}</td>
<td>{{ obj.email }}</td>
<td>{{ obj.user_type.caption }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
4、效果
POST提交数据:

GET方式:

标签:ble form ida length png go import div for cts
原文地址:https://www.cnblogs.com/skyflask/p/9710809.html