模拟窗口类ModelForm的应用
2024-09-05 12:58:30
模拟窗口类ModelForm的应用
模拟窗口是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 = '设置密码'
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)
对用的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>
最后,附上结果图
最新文章
- .net正则表达式大全(.net 的 System.Text.RegularExpressions.Regex.Match()方法使用)
- mysql登录报错“Access denied for user &#39;root&#39;@&#39;localhost&#39; (using password: YES”的处理方法
- 使用virt-manager创建和管理虚拟机
- JFrame 实现全屏透明背景
- hdu 4704 Sum
- 【BZOJ3309】DZY Loves Math
- hibernate MTM 联合主键
- LinkedList使用方法
- List接口特有功能
- 页面注册系统--使用forms表单结合ajax
- VS 代码片段集
- mysql常用优化参数
- objc.io 待看文章
- jQuery做字符串分隔
- Pandas python
- scala try monad
- 需求改进&;系统设计
- 《构建之法》第四&;十七章读书笔记
- 无法在Word中打开MathType怎么办
- 转载-找圆算法((HoughCircles)总结与优化-霍夫变换