这里是Django的新手。我正在设置注册页面,我想确保当前登录的用户无法创建新帐户。
到目前为止,我有一个这样的表格:
class RegisterView(FormView):
template_name = 'users/register_user.html'
success_url = 'thank_you'
def get(self, request):
if request.user.is_authenticated():
# If a user is logged in, redirect them to a page informing them of such
return render(request, 'users/already_logged_in.html')
else:
# would like to direct the user to the normal registration page
def post(self, request):
user_form = UserCreateForm(request.POST)
if user_form.is_valid():
username = user_form.clean_username()
password = user_form.clean_password2()
user_form.save()
user = authenticate(username=username,
password=password)
login(request, user)
return render(request, 'home.html')
return render(request, 'register_user.html', {'form': user_form})
我怀疑我可能不得不使用mixins(我也对它们的含义感到困惑)所以如果它们是解决方案的一部分请稍微扩展一下。
在“其他”之后我应该包括什么才能让它通过通常的注册页面?
提前感谢您的帮助。
答案 0 :(得分:1)
只返回父FormView将返回的内容
def get(self, request):
if request.user.is_authenticated():
# If a user is logged in, redirect them to a page informing them of such
return render(request, 'users/already_logged_in.html')
else:
return super(RegisterView, self).get(request)
您需要在视图中设置form_class,而不是在帖子中设置方法,请查看django文档,了解如何使用FormView https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-editing/#formview