成功注册后Django重定向用户不起作用

时间:2019-11-26 04:11:11

标签: python django

我是django的新手,正在建立注册系统。用户成功注册后,它将重定向到相同的注册页面,而不是首页。

views.py

def register(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            saved_user = form.save()
            saved_user.set_password(password)
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect("home")
        else:
            for msg in form.error_messages:
                print(form.error_messages[msg])

            return render(request=request,
                      template_name="registration/register.html",
                      context={"form": form})

    form = UserCreationForm
    return render(request=request,
              template_name="registration/register.html",
              context={"form": form})

register.html

{% extends 'base.html' %}
{% block title %}Register{% endblock %}
{% block content %}
    <div style="text-align:center"><h2>Register</h2></div>
    <div style="text-align:center">
        <form method="post" action="{% url 'register' %}">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="Register">
        </form>
        <p>If you already have an account <a href="/login" target="blank"><strong>login</strong></a></p>
    </div>
{% endblock %}

urls.py

urlpatterns = [
    path('', HomePageView.as_view(), name='home'),
    path('register', views.register, name='register'),
]

3 个答案:

答案 0 :(得分:0)

您需要使用reverse才能在redirect()中使用url名称

from django.urls import reverse

return redirect(reverse("home"))

或者如果您不想撤消

return redirect("/")

答案 1 :(得分:0)

可能是因为您在user中将None作为user = authenticate(request, username=username, password=password)。因为您在设置密码后没有保存用户。所以下面的代码应该可以工作:

saved_user = form.save(commit=False)
saved_user.set_password(password)
saved_user.save()  # <-- Saving the Password in User
user = authenticate(request, username=username, password=password)

答案 2 :(得分:0)

尝试这对我有用:

 kdef register(request):
  if request.method == "POST":
    form = UserCreationForm(request.POST)
    if form.is_valid():
        user = form.save()
        password = self.request.POST.get('password', None)
        authenticated = authenticate(
            username=user.username,
            password=password
        )
        if authenticated:
            login(request, authenticated)
            return redirect("/")
else:
    form = UserCreationForm()
return render(request, 'register.html', {
    'form': form
})