[英]django-allauth login_redirect page with username as slug
我正在使用 Django 3.2 和 django-allauth 0.44
我在settings.py
中设置了我的 LOGIN_REDIRECT_URL,如下所示:
LOGIN_REDIRECT_URL = '个人资料页面'
在urls.py
中,我定义了以下路线:
path('accounts/profile/slug:username', AccountProfileView.as_view(), name='profile-page'),
当我登录时,(不出所料),我收到以下错误消息:
NoReverseMatch at /accounts/login/ Reverse for 'profile-page' with no arguments not found. 尝试了 1 种模式:['accounts/profile/(?P[-a-zA-Z0-9_]+)$']
如何将登录用户的用户名的参数传递(或指定)到路由?
如果您的视图需要执行不是很简单的重定向,则需要重写get_success_url
方法,考虑到您使用 django-allauth,您将需要重写allauth.account.views.LoginView
并为其编写自己的 url 模式以便使用您的覆盖视图。 首先覆盖视图:
from django.urls import reverse
from allauth.account.views import LoginView as AllauthLoginView
from allauth.account.utils import get_next_redirect_url
class LoginView(AllauthLoginView):
def form_valid(self, form):
self.user = form.user # Get the forms user
return super().form_valid(form)
def get_success_url(self):
ret = (
get_next_redirect_url(self.request, self.redirect_field_name)
or reverse('profile-page', kwargs={'username': self.user.username})
)
return ret
接下来,无论您在哪里定义 allauth 的 url,只需在它之前添加您自己的 url :
from path_to.view_above import LoginView # Change this import properly
urlpatterns = [
...
path('accounts/login/', LoginView.as_view(), name="account_login"),
path('accounts/', include('allauth.urls')),
...
]
使用 allauth 的另一种替代解决方案是使用自定义ACCOUNT_ADAPTER
并覆盖它的get_login_redirect_url
因为LoginView
将在内部调用它以防万一没有next
参数。 为此,首先从allauth.account.adapter.DefaultAccountAdapter
继承:
from django.urls import reverse
from allauth.account.adapter import DefaultAccountAdapter
class MyAccountAdapter(DefaultAccountAdapter):
def get_login_redirect_url(self, request):
return reverse('profile-page', kwargs={'username': request.user.username})
接下来在settings.py
中设置ACCOUNT_ADAPTER
:
ACCOUNT_ADAPTER = "path.to.MyAccountAdapter"
LOGIN_REDIRECT_URL
应该指向用户成功登录您的网站后登陆的页面,除非他通过尝试访问任何需要授权的页面而被重定向到登录页面。
如果你想将用户重定向到一个特定的页面,在这个例子中到他自己的个人资料页面,你可以创建一个中间 URL 将用户重定向到他自己的个人资料页面,当访问时。 它可以像这样完成:
使用基于类的视图:
class CurrentUserProfileRedirectView(LoginRequiredMixin, RedirectView):
def get_redirect_url(self, *args, **kwargs):
return reverse('profile-page', kwargs={'username': request.user.username})
或使用基于函数的视图:
@login_required
def current_user_profile(request):
return redirect('profile-page', username=request.user.username)
接下来,将此重定向视图注册为常规视图,不需要任何参数,并将LOGIN_REDIRECT_URL
设置为此视图的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.