Django creating object from POST
I have a question regarding Djanog views
here is a sample code
def example register ( request ) :
if request.method == ’POST ’ :
username = request.POST.get ( ’ username ’ )
password = request.POST.get (开发者_C百科 ’ password ’ )
email = request.POST.get (’email’)
user = User.objects .create_user ( username
, email
, password )
user . save ()
return HttpResponseRedirect (
’/ example /login / ’)
In the above example we are taking the values one by one i.e username, password etc. If I have many such fields, then how can I do it in one single line, i was thinking to use dict's but can not find a way. Any help is appreciated. Thank you.
you should be using forms[1] and model-forms [2] to collect such data from the request.
[1] http://docs.djangoproject.com/en/dev/topics/forms/
[2] http://docs.djangoproject.com/en/dev/topics/forms/modelforms/
Why would you ever do it like that anyway?
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
Probably not the most elegenat way, but it should describe well enough, how to use form and then authenticate someone & log him in.
精彩评论