Django:为什么 Urls 与实际不同?

Django: Why is the Urls is different than what it should actually be?

我是 Django 新手。我正在制作一个简单的登录自定义系统,当我按下登录按钮时,如果凭据正确,它会转到欢迎页面,但 URL 是 http://localhost:8000/login/ 我期待 http://localhost:8000/welcome/ 而不是

这是我的 view.py 登录代码

def login(request):
    if request.method == "POST" :
        username = request.POST['user']
        password = request.POST['psk']
        try:
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                auth.login(request, user)
                return render(request, 'welcome.html')
            else:
                messages.error(request, 'Username or password didn\'t match.')

        except auth.ObjectDoesNotExist:
            print("invalid user")

    return render(request, 'login.html')

帐户应用程序的 URLs.py 看起来像:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # url(r'^index/$', home),
    url(r'^login/$', login),
    url(r'^logout/$', logout),
    url(r'^', custreg),
    
]

请帮助我,如果您还需要其他任何内容来回答问题,请告诉我

您需要做 3 件事:

  1. view.py 中创建一个 welcome 函数,returns 渲染输出
def welcome(request):
    return render(request, 'welcome.html')
  1. yourapp/urls.py
  2. 里面添加以下几行
from django.urls import path

# add an entry to urlpatterns
urlpatterns=[
    path('welcome/', view.welcome, name='welcome'),
    # rest of the patterns
]
  1. login 函数,而不是返回 html 页面,将用户重定向到 welcome 端点。
# imports
from django.shortcuts import redirect, reverse

# inside your login function
if user is not None:
    auth.login(request, user)
    # return render(request, 'welcome.html')
    return redirect(reverse('welcome'))

更改后重新启动您的应用程序。