使用AuthenticationForm FormView将URL添加到URL

时间:2017-12-15 16:27:01

标签: django django-forms django-views

我来自Laravel,刚来到Django。我正在尝试在登录后向网址添加用户名。这有几次被问过,但我还没有让解决方案工作(它们涉及将模型附加到通用FormView类)。这就是我所拥有的:

urls.py

path('login/', views.Login.as_view(), name='login'),

# Logged in user
path('home/<str:username>', views.UserIndex.as_view(), name='user_index'),

views.py

class Login(views.AnonymousRequiredMixin, views.FormValidMessageMixin, generic.FormView):
    authenticated_redirect_url = '/'
    form_class = LoginForm
    form_valid_message = "You have successfully logged in"
    template_name = 'pythonmodels/registration/login.html'
    success_url = reverse_lazy('pythonmodels:user_index', args=("Bill",))

    def form_valid(self, form):
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user = authenticate(username=username, password=password)

        if user is not None and user.is_active:
            login(self.request, user)
            return super(Login, self).form_valid(form)
        else:
            return self.form_invalid(form)

forms.py

class LoginForm(AuthenticationForm):
    def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.layout = Layout(
            'username',
            'password',
            ButtonHolder(
                Submit('login', 'Login', css_class='btn-primary')
            )
        )

views.py文件中,我希望args的{​​{1}}成为刚刚通过身份验证的用户的用户名。应该在success_url班级完成吗?我还看到你可以去一个中间网址,然后获取用户数据,但这似乎是一个可怕的额外步骤。我希望将其保持在靠近基座LoginFormFormView的位置,因为我还不了解更深入的自定义。非常感谢!

1 个答案:

答案 0 :(得分:1)

您无法在视图中设置success_url,因为在用户登录之前您不知道该参数。

改为覆盖get_success_url

def get_success_url(self):
    return reverse('pythonmodels:user_index', args=[self.request.user.username])