Django18初体验


960 浏览 5 years, 4 months

11.14 视图中的表单

版权声明: 转载请注明出处 http://www.codingsoho.com/

https://docs.djangoproject.com/en/1.8/ref/forms/

from .forms import SignUpForm
from .models import SignUp

# Create your views here.
def home(request):
    title = 'Welcome'
    form = SignUpForm(request.POST or None)
    context = {
        "title": title,
        "form": form
    }
    if form.is_valid():
        #form.save()
        #print request.POST['email'] #not recommended, raw data without validation
        instance = form.save(commit=False)
#
        full_name = form.cleaned_data.get("full_name")
        if not full_name:
            full_name = "New full name"
        instance.full_name = full_name
        # if not instance.full_name:
        #   instance.full_name = "Justin"
        instance.save()
        context = {
            "title": "Thank you"
        }
    return render(request, "home.html", context)

form = SignUpForm(request.POST or None)这句话中记得加 or None,否则的话SignUpForm会一直执行Validation
即使只是网址GET访问,也会出现下列validation错误

调用form.is_valid,form会执行form类里面的那些validation函数
form.save(commit=False)并不会真正的保存数据 ,instance.save()才会真正保存

This save() method accepts an optional commit keyword argument, which accepts either True or False. If you call save() with commit=False, then it will return an object that hasn’t yet been saved to the database. In this case, it’s up to you to call save() on the resulting model instance.

home.html

<h1>{{title}}</h1>
{{user}}
{{request.user}}
<form method="POST" action=''> {% csrf_token%}
{{form.as_p}}
<input type="submit" value="sign up">
</form>

action指定了提交之后的重定向地址,可以用”.”
as_p = as paragraph

GET vs POST

Home函数里添加下列打印

    print request
    print request.POST

在shell里面查看打印输出
如果只是执行网址访问http://127.0.0.1:8000/

<WSGIRequest: GET '/'>
<QueryDict: {}>

如果按”sign up”提交

<WSGIRequest: POST '/'>
<QueryDict: {u'csrfmiddlewaretoken': [u'xcdCoiISxk5yS4GSbVHENmjWwnhvj7kk'], u'email': [u'bin@gmail.edu'], u'full_name': [u'bin']}>