zoukankan      html  css  js  c++  java
  • 模拟窗口类ModelForm的应用

    模拟窗口类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. 最后,附上结果图

  • 相关阅读:
    SCCM2012 R2实战系列之四:初始化配置
    SCCM 2012 R2实战系列之一:SQL安装
    hdu 1242(bfs)
    hdu 1728(bfs)
    hdu 1253(bfs)
    hdu 3661
    hdu 1072(bfs)
    AC模版
    hdu 1010(dfs)
    poj 3628(01_page, dfs)
  • 原文地址:https://www.cnblogs.com/guguobao/p/9323561.html
Copyright © 2011-2022 走看看