美文网首页django-Form使用
django的Form一 未完善(接二)

django的Form一 未完善(接二)

作者: 赖三石 | 来源:发表于2017-07-20 22:21 被阅读0次

    urls.py

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^fm/', views.fm, name='fm'),
    ]
    

    views.py

    from django.shortcuts import render, redirect, HttpResponse
    
    # ###################form#############################
    from django import forms
    
    class FM(forms.Form):
    # username,password,email必须与template的form 中name属性字段一致
        username = forms.CharField(error_messages={'required': '用户名不能为空'})
        password = forms.CharField(
            max_length=12,
            min_length=6,
            error_messages={'required': '密码不能为空', 'min_length': '密码小于6', 'max_length': '密码大于12'}
        )
        email = forms.EmailField(error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'})
    
    def fm(request):
        if request.method == 'POST':
            obj = FM(request.POST)
            if obj.is_valid():
    # 这里obj.cleaned_data是一个字典,如果存数据,例如:
    # models.xxx.objects.create(**obj.cleaned_data) 注册就完成了.
                # print obj.cleaned_data
                return redirect('/xxx/') 
            else:
                print obj.errors
        else:
            obj = FM()
        return render(request, 'fm.html', {'obj': obj})
    

    template

    <!DOCTYPE html>
    <html lang="en" xmlns="http://www.w3.org/1999/html">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
    <form action="/fm/" method="post">
        {% csrf_token %}
    写法一
    <p><input type="text" placeholder="username" name="username">{{ obj.errors.username.0 }}</p>
    <p><input type="text" placeholder="password" name="password">{{ obj.errors.password.0 }}</p>
    <p><input type="text" placeholder="email" name="email">{{ obj.errors.email.0 }}</p>
    <input type="submit" value="submit">
    
    写法二
    <p>{{ obj.username }} {{ obj.errors.username.0 }}</p>
    <p>{{ obj.password }} {{ obj.errors.password.0 }}</p>
    <p>{{ obj.email }} {{ obj.errors.email.0 }}</p>
    <input type="submit" value="submit">
    
    写法三
     <p>{{ obj.as_p }}</p>
     <input type="submit" value="submit">
    或者
    <table>{{ obj.as_table }}</table>
    <input type="submit" value="submit">
    或者
     <p>{{ obj.as_ul }}</p>
     <input type="submit" value="submit">
    
    </form>
    </body>
    </html>
    

    相关文章

      网友评论

        本文标题:django的Form一 未完善(接二)

        本文链接:https://www.haomeiwen.com/subject/sgojkxtx.html