简体   繁体   English

为什么 Django 不会将应用名称生成到 href 路径中?

[英]Why Django does not generate app name into href paths?

I hope someone could maybe help me, please: I am quite new to Django and currently trying to implement a simple login/logout for a test page.我希望有人可以帮助我,拜托:我对 Django 很陌生,目前正在尝试为测试页面实现简单的登录/注销。 However, for some reasons, the Django does not generate the name of application in the href (so where it should be xxxx/main/register, it is only xxx/register).但是,由于某些原因,Django 并没有在 href 中生成应用程序的名称(所以应该是 xxxx/main/register,只有 xxx/register)。 But when I put the app name manually in the href in Pycharm, it generates it two times (so it becomes xxx/main/main/register).但是当我手动将应用程序名称放入 Pycharm 的 href 中时,它会生成两次(因此它变成了 xxx/main/main/register)。

So for this:所以为此:

<a href="/logout/">Logout</a>

I got this url: http://127.0.0.1:8000/logout/我得到了这个 url: http://127.0.0.1:8000/logout/

If I write this:如果我写这个:

<a href="main/logout/">Logout</a>

I got this url: http://127.0.0.1:8000/main/main/logout/我得到了这个 url: http://127.0.0.1:8000/main/main/logout/

But I need to get this: http://127.0.0.1:8000/main/logout/但我需要得到这个: http://127.0.0.1:8000/main/logout/

It worked before, but from one minute to another, it suddenly stopped directing to the good path.它以前有效,但从一分钟到另一分钟,它突然停止指向正确的路径。 And django does the same thing with every links in my site. django 对我网站中的每个链接都做同样的事情。

main/urls.py:主/urls.py:

from django.urls import path
from . import views

app_name = 'main'  # here for namespacing of urls.

urlpatterns = [
    path("", views.homepage, name="homepage"),
    path("register/", views.register, name="register" ),
    path("logout/", views.logout_request, name="logout"),
]

main/views.py:主/views.py:

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Tutorial
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import logout, authenticate, login
from django.contrib import messages

def homepage(request):
    return render(request = request,
                  template_name='main/home.html',
                  context = {"tutorials":Tutorial.objects.all})

def register(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f"New account created: {username}")
            login(request, user)
            return redirect("main:homepage")
        else:
            for msg in form.error_messages:
                messages.error(request, f"{msg}: {form.error_messages[msg]}")
    else:
        form = UserCreationForm
    return render(request = request,
              template_name='main/register.html',
              context={"form":form})

def logout_request(request):
    logout(request)
    messages.info(request, "Logged out successfully!")
    return redirect("main:homepage")

mysite/urls.py:我的网站/urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('main/', include('main.urls')),
    path('admin/', admin.site.urls),
    path('tinymce/', include('tinymce.urls')),
]

You should use the url name in the template.您应该在模板中使用 url 名称。 It should solve the problem.它应该可以解决问题。 Like this: <a href="{% url 'logout' %}">Logout</a>像这样: <a href="{% url 'logout' %}">Logout</a>

Or with namespacing: <a href="{% url 'main:logout' %}">Logout</a>或者使用命名空间: <a href="{% url 'main:logout' %}">Logout</a>

<a href="{% url 'logout' %}">

Use the name in href tag that will work.在 href 标记中使用名称将起作用。

The behaviour you observe has nothing to do with Django, it's a basic html feature: in the first case you're using an absolute path (=> starting with a slash) for your href, in the second one you're using a relative path (NOT starting with a slash) so it's resolved relatively to the current url path whatever it is.您观察到的行为与 Django无关,它是基本的 html 功能:在第一种情况下,您使用绝对路径(=> 以斜杠开头)作为您的 href,在第二种情况下,您使用相对路径(不以斜杠开头),因此它相对于当前的 url 路径进行解析,无论它是什么。 You'd have the very same issue with plain static HTML.对于普通的 static HTML,您也会遇到同样的问题。

This being said, in Django, you should never hardcode urls, but use the {% url <name> %} template tag (or the django.utils.reverse() function in Python code) instead, so you can change your urls in the urls.py files without breaking anything. This being said, in Django, you should never hardcode urls, but use the {% url <name> %} template tag (or the django.utils.reverse() function in Python code) instead, so you can change your urls in urls.py 文件没有破坏任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM