<p>为了实现权限,必须在创建新用户时以编程方式完成。
在工作流中</p>
<ul>
<li>新用户收到一封带有唯一链接的激活电子邮件</li>
<li>点击使他能够访问该网站,并要求他立即更改密码</li>
<li>验证实现权限(在本例中为组)</li>
</ul>
<p>这是代码</p>
<pre><code>from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from django.shortcuts import redirect, render
from django.contrib.auth.models import Group
@login_required
def change_password(request):
if request.method == "POST":
form = PasswordChangeForm(user=request.user, data=request.POST)
if form.is_valid():
user = form.save()
# Attributes to a user a group depending on his status.
user.groups.add(Group.objects.get(name=user.status_type))
update_session_auth_hash(request, user) # Important!
messages.success(request, 'Your PWD has been changed')
return redirect('change_password')
else:
messages.error(request, 'Please Correct the Error')
else:
form = PasswordChangeForm(request.user)
return render(request, 'accounts/change_password.html', {'form': form})
</code></pre>