gpt4 book ai didi

django - 重定向到另一个 View 函数

转载 作者:行者123 更新时间:2023-12-02 09:12:55 26 4
gpt4 key购买 nike

当用户登录时,我想将他们简单地重定向到索引,而不是在网址中包含“/login/”。

我有两个 View 函数,一个用于登录和索引。

索引 View

def index(request):

context = {

}
return render(request, 'index.html', context)

登录 View

def login(request):

username = request.POST.get('username', '')
password = request.POST.get('password', '')

user = auth.authenticate(username=username, password=password)

if user is not None:
auth.login(request, user)
else:
print('Wrong user')

return redirect('index') #<------ Something like that(?)

网址模式

urlpatterns = [
url(r'^$', views.index, name='index'),

url(r'^login/$', views.login, name='login'),
]

控制台错误:

Correct user
Internal Server Error: /Crowd/login/
Traceback (most recent call last):
File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 66, in login
return redirect('index')
File "C:\Anaconda3\Lib\site-packages\django\shortcuts.py", line 116, in redirect
return redirect_class(resolve_url(to, *args, **kwargs))
File "C:\Anaconda3\Lib\site-packages\django\shortcuts.py", line 204, in resolve_url
return urlresolvers.reverse(to, args=args, kwargs=kwargs)
File "C:\Anaconda3\Lib\site-packages\django\core\urlresolvers.py", line 600, in reverse
return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "C:\Anaconda3\Lib\site-packages\django\core\urlresolvers.py", line 508, in _reverse_with_prefix
(lookup_view_s, args, kwargs, len(patterns), patterns))
django.core.urlresolvers.NoReverseMatch: Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
[14/Sep/2016 19:46:12] "POST /Crowd/login/ HTTP/1.1" 500 88875

最佳答案

# views.py
def login(...):
# ...
return redirect('home')

和:

# urls.py
urlpatterns = [
url(r'^$', 'views.index', name='home'),
# ...
]

关于django - 重定向到另一个 View 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39496549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com