Django从POST创建对象

时间:2010-10-29 12:34:40

标签: python django http

我有关于Djanog观看的问题

这是一个示例代码

def example register ( request ) :
if request.method == ’POST ’ :
username = request.POST.get ( ’ username ’ )
password = request.POST.get ( ’ password ’ )
email = request.POST.get (’email’)
user = User.objects .create_user ( username
, email
, password )
user . save ()
return HttpResponseRedirect (
’/ example /login / ’)

在上面的例子中,我们逐个取值,即用户名,密码等。如果我有很多这样的字段,那我怎么能在一行中完成,我想用dict但是找不到办法。任何帮助表示赞赏。谢谢。

2 个答案:

答案 0 :(得分:5)

您应该使用表单[1]和模型表单[2]从请求中收集此类数据。

[1] http://docs.djangoproject.com/en/dev/topics/forms/

[2] http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

答案 1 :(得分:0)

为什么你会这样做呢?

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
and then handle it like that:
form = UserCreationForm(request.POST)
if form.is_valid():
    username = form.cleaned_data['username']
    password = form.cleaned_data['password1']
    email = form.cleaned_data['email']
    newuser = User.objects.create_user(username, email, password)
    user = authenticate(username=username, password=password)
    login (request, user)
    return HttpResponseRedirect('/some/page/which/is/not/logginpage')#cause user is already logged in

可能不是最直接的方式,但它应该描述得足够好,如何使用表格然后验证某人&登录他。