使用AuthenticationForm FormView将用户名添加到URL中



我来自拉拉维尔(Laravel),新来的是django。登录后,我正在尝试将用户名添加到URL。几次之前已经提出了这一点,但是我尚未使解决方案起作用(它们涉及在通用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文件中,我希望success_urlargs成为刚刚验证的用户的用户名。这应该在LoginForm类中完成吗?我还看到您可以转到中间URL,然后获取用户数据,但这似乎是一个可怕的额外步骤。我想将其保持在基本FormViewAuthenticationForm的距离之近,因为我还不了解更多的深入自定义。非常感谢!

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

覆盖get_success_url而不是:

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

最新更新