django下一个url参数



我使用的是自定义登录视图和自定义登录页面。我正在努力解决的是我想要使用的下一个参数,所以如果url中有下一个值,那么用户将被重定向到上一页。

正如您在下面的代码中看到的,我使用的是django-crispy-formsdjango-axes

问题是,我能够成功地将用户重定向到主页,但我无法访问任何对登录用户可见的数据(登录用户的所有视图都受到限制(,如用户电子邮件和内容。此外,当我尝试点击任何超链接时,Django都会自动重定向到登录页面。

例如,当我尝试手动访问页面时,http://127.0.0.1:8000/articles它将我重定向到http://127.0.0.1:8000/accounts/login/?next=/articles/,这给了我

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/articles/

views.py

class UpdatedLoginView(LoginView):
form_class = LoginForm
template_name = 'user/login.html'
redirect_field_name='main/homepage.html'

def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
if 'next' in request.POST:
return redirect(request.POST.get('next'))
else:
return(redirect('homepage'))
else:
return render(request, self.redirect_field_name, {'form': form})
class ArticleListView(LoginRequiredMixin, ListView):
template_name = 'articles/ArticleListView.html'
model = Article
paginate_by = 6
queryset = Article.objects.filter(status=1)

def get_context_data(self, **kwargs):
context = super(ArticleListView, self).get_context_data(**kwargs)
return context

login.html

<form method="post" class="login-form background" novalidate>
{% csrf_token %}
{{ form|crispy }}
{% if request.GET.next %}
<input type="hidden" name="next" value="{{ request.GET.next }}"/>
{% endif %}
<button type="submit" class="text-center mx-auto login-btn">Login</button>
</form>

urls.py

urlpatterns = [
path('', views.UpdatedLoginView.as_view(), name='login'),
path('logout/', views.logout_view, name='logout'),
path('home/', views.HomePageView.as_view(), name='homepage'),
path('articles/', views.ArticleListView.as_view(), name='article_list'),
]

设置.py

#AUTHORIZATION
AXES_FAILURE_LIMIT = 4
AXES_ONLY_USER_FAILURES = True
AXES_ENABLE_ADMIN = True
LOGIN_REDIRECT_URL = 'homepage'
LOGOUT_REDIRECT_URL = 'login'

你能检查一下代码,让我知道我做错了什么吗?也许这与设置有关,但我不确定这里的问题是什么。是否需要将下一个参数传递给所有视图?如果是,最好的方法是什么?

在您的应用程序中,LOGIN_URL设置为默认值,即"accounts/login/";

但是"/accounts/login/";未与视图相关联,因此web服务器返回404(未找到(。

解决这个问题的一种方法是通过在urlpatters中添加以下行来包含标准登录视图:

path("accounts/", include("django.contrib.auth.urls")),

最新更新