模拟窗口类ModelForm的应用

  1. 模拟窗口是Form的窗口中的fields是引用models类


class Mood(models.Model):
status =models.CharField(max_length=10,null=False) def __unicode__(self):
return self.status class Post(models.Model):
mood = models.ForeignKey('Mood',on_delete=models.CASCADE) #外键引用
nickname =models.CharField(max_length=10, default='不愿意透露自己的人')
message = models.TextField(null=False)
del_pass = models.CharField(max_length=10)
pub_time = models.DateTimeField(auto_now=True)
enabled = models.BooleanField(default=False) def __unicode__(self):
return u"%s" %(self.message) class PostForm(forms.ModelForm):#窗口类,要import forms
class Meta:
model= Post#用于指定用哪个model
fields= ['mood','nickname','message','del_pass']#用于指定用model中哪些变量 def __init__(self, *args, **kwarge):
super(PostForm, self).__init__(*args, **kwarge)
self.fields['mood'].label = '现在的心情'
self.fields['nickname'].label = '你的昵称'
self.fields['message'].label = '你的消息'
self.fields['del_pass'].label = '设置密码'
  1. view调用的函数

def posttest(request):
if request.method=='POST': #点击提交时的处理入口
post_form = PostForm(request.POST)
if post_form.is_valid:
message = "你的信息已存储"
post_form.save()
else:
message = "如果张贴,要每个字段多必须写"
template = get_template('one/posttest.html')
post_form = PostForm()
moods = Mood.objects.all()
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context) return HttpResponse(html)
  1. 对用的html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>post test</title>
</head>
<body>
{% if message %}
<h2>{{ message }}</h2>
{% endif %}
<form action="." method="post">
{% csrf_token %}
<!--#导入包,防止伪站点请求-->
<table>
{{ post_form.as_table }}
</table>
<input type="submit" value="张贴" >
<input type="reset" value="清除重设" >
</form>
</body>
</html>
  1. 最后,附上结果图

最新文章

  1. .net正则表达式大全(.net 的 System.Text.RegularExpressions.Regex.Match()方法使用)
  2. mysql登录报错“Access denied for user &#39;root&#39;@&#39;localhost&#39; (using password: YES”的处理方法
  3. 使用virt-manager创建和管理虚拟机
  4. JFrame 实现全屏透明背景
  5. hdu 4704 Sum
  6. 【BZOJ3309】DZY Loves Math
  7. hibernate MTM 联合主键
  8. LinkedList使用方法
  9. List接口特有功能
  10. 页面注册系统--使用forms表单结合ajax
  11. VS 代码片段集
  12. mysql常用优化参数
  13. objc.io 待看文章
  14. jQuery做字符串分隔
  15. Pandas python
  16. scala try monad
  17. 需求改进&amp;系统设计
  18. 《构建之法》第四&amp;十七章读书笔记
  19. 无法在Word中打开MathType怎么办
  20. 转载-找圆算法((HoughCircles)总结与优化-霍夫变换

热门文章

  1. String成员函数
  2. CSS基础学习-6.CSS属性_列表、表格
  3. 第七章 路由 82 名称案例-使用keyup事件实现
  4. cmd_memo
  5. ios 打包下
  6. es聚合学习笔记
  7. MySQL 将数据文件分布到不同的磁盘
  8. mysql解除锁表
  9. 题解 最长上升序列2 — LIS2
  10. 在jquery中,使用ajax上传文件和文本