使用django generic CreateView我可以创建一个新的用户帐户,但是如何在注册后使用这种技术自动登录该用户?
urls.py
...
url( r'^signup/$', SignUpView.as_view(), name = 'user_signup' ),
...
Run Code Online (Sandbox Code Playgroud)
views.py
class SignUpView ( CreateView ) :
form_class = AccountCreationForm
template_name = 'accounts/signup.html'
success_url = reverse_lazy( 'home' )
Run Code Online (Sandbox Code Playgroud)
forms.py
class AccountCreationForm ( forms.ModelForm ) :
def __init__( self, *args, **kwargs ) :
super( AccountCreationForm, self ).__init__( *args, **kwargs )
for field in self.fields :
self.fields[field].widget.attrs['class'] = 'form-control'
password1 = forms.CharField( label = 'Password', widget = forms.PasswordInput )
password2 = forms.CharField( label = 'Password confirmation', widget = forms.PasswordInput …Run Code Online (Sandbox Code Playgroud) 我有一个问题,我成功注册用户 - 但是,我希望用户登录注册.这是代表我的注册视图的代码.有关用户未自动登录的原因的任何想法?
笔记:
在settings.py我有:
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
Run Code Online (Sandbox Code Playgroud)谢谢!
def register(request):
user_creation_form = UserCreationForm(request.POST or None)
if request.method == 'POST' and user_creation_form.is_valid():
u_name = user_creation_form.cleaned_data.get('username')
u_pass = user_creation_form.cleaned_data.get('password2')
user_creation_form.save()
print u_name # Prints correct username
print u_pass # Prints correct password
user = authenticate(username=u_name,
password=u_pass)
print 'User: ', user # Prints correct user
login(request, user) # Seems to do nothing
return HttpResponseRedirect('/book/') # User is not logged in on this page
c = RequestContext(request, {'form': user_creation_form})
return render_to_response('register.html', …Run Code Online (Sandbox Code Playgroud) python authentication django django-views django-authentication
我是 django 的新手,我试图找出为什么通过我的帐户表单创建新帐户不会对密码进行哈希处理(我假设密码没有进行哈希处理,因为在创建帐户时我无法使用密码登录,并且此消息显示在通过表单创建的帐户的 django 管理的密码字段下:)Invalid password format or unknown hashing algorithm。我可以在 django 管理中成功创建不存在此未哈希密码问题的新帐户。
视图.py:
@unauthenticated_user
def create_account(request):
form = AccountForm()
if request.method == 'POST':
form = AccountForm(request.POST)
# should hash the password, check username/email doesnt already exist, etc
if form.is_valid():
user = form.save()
return redirect('/login')
else:
messages.info(request, "Count not create account.")
context = {'form': form}
return render(request, 'accounts/create_account.html', context)
Run Code Online (Sandbox Code Playgroud)
模型.py:
class Account(AbstractUser):
def __str__(self) -> str:
return self.first_name
pass
Run Code Online (Sandbox Code Playgroud)
创建帐户表格:
<form action="{% url 'create_account' %}" method="POST">
{% csrf_token …Run Code Online (Sandbox Code Playgroud)