这是我目前用于注册的内容:
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
messages.info(request, "Thanks for registering. Please login to continue.")
return HttpResponseRedirect("/dashboard/")
else:
form = UserCreationForm()
return render_to_response("accounts/register.html", {
'form': form,
}, context_instance=RequestContext(request))
创建帐户后是否可以不要求用户手动登录,而只是自动登录?感谢。
编辑:我尝试过login()函数但没有成功。我认为问题是没有设置AUTHENTICATION_BACKENDS。
答案 0 :(得分:91)
使用authenticate()
和login()
函数:
from django.contrib.auth import authenticate, login
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
messages.info(request, "Thanks for registering. You are now logged in.")
new_user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
)
login(request, new_user)
return HttpResponseRedirect("/dashboard/")
答案 1 :(得分:6)
基于类的视图这里是为我工作的代码(最初是Django 1.7,更新为2.1)
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.views.generic import FormView
class SignUp(FormView):
template_name = 'signup.html'
form_class = UserCreateForm
success_url='/account'
def form_valid(self, form):
#save the new user first
form.save()
#get the username and password
username = self.request.POST['username']
password = self.request.POST['password1']
#authenticate user then login
user = authenticate(username=username, password=password)
login(self.request, user)
return HttpResponseRedirect(self.get_success_url)
答案 2 :(得分:0)
您可以将Django的UserCreationForm子类化,并覆盖它的save方法以在commit = True时将其登录。
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
class CustomUserCreationForm(UserCreationForm):
"""
A ModelForm for creating a User and logging
them in after commiting a save of the form.
"""
def __init__(self, request, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request = request
class Meta(UserCreationForm.Meta):
pass
def save(self, commit=True):
user = super().save(commit=commit)
if commit:
auth_user = authenticate(
username=self.cleaned_data['username'],
password=self.cleaned_data['password1']
)
login(self.request, auth_user)
return user
您只需要确保在实例化表单时传递请求对象。您可以通过重写视图的get_form_kwargs方法来做到这一点。
def get_form_kwargs(self):
form_kwargs = super().get_form_kwargs(self)
form_kwargs['request'] = self.request
return form_kwargs
或者,请确保在实例化form_class时执行CustomUserCreationForm(data=request.POST, request=self.request)
。