所以我在我的Django项目中创建了几个应用程序,我有一个名为main_app的主要应用程序.

其他应用程序被称为配置文件应用程序、设置应用程序、消息应用程序.

The issue:

我遇到的问题是,每当我try 使用应用程序名称空间和URL名称(例如,profilepage_app:"配置文件-重定向")从main_app中的配置文件_应用程序运行特定的查看函数时,我收到一个404错误,指出"Page Not Found".

I have done the following:

  • 注册所有应用程序.
  • 已在我的设置URL中链接urls.py文件.
  • 我试图在main_app内创建一个测试视图函数,它可以很好地工作,但同样的函数不能在profile_app中工作.
  • 创建了另一个测试应用程序,以查看我是否仍然存在相同的问题(我确实有).

所以问题是,我试图在浏览器中显示的所有应用程序(Main_app除外)的任何链接都会生成"Page Not Found"-错误.

My questions:

  1. 这一切为什么要发生?
  2. 我如何解决此问题?
  3. 这与我的设置文件有关吗?

The error:

My view:

from django.conf import settings
from django.shortcuts import render, redirect
from django.views.generic import View

from profile_app.forms import *
from profile_app.models import *
from messages_app.models import Message

user = settings.AUTH_USER_MODEL
# Create your views here.

## Redirect to user profile from the navbar

class ProfilePageView(View):
    model = ProfilepageMember
    template_name = "profile_app/profilepage.html"
    
    def get(self, request, user_name):
        user_related_data = ProfilepageMember.objects.filter(member__username = user_name)
        context = {"user_related_data": user_related_data}
        return render(request, self.template_name, context)

My URLS:

"""
URL configuration for bodyswap_project project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("auth_app.urls")),
    path("", include("main_app.urls")),
    path("", include("profile_app.urls")),
    path("", include("messages_app.urls")),
    path("", include("settings_app.urls")),
]


Settings:

"""
"""
Django settings for body project.

Generated by 'django-admin startproject' using Django 4.2.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path
import os
from dotenv import load_dotenv
load_dotenv()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG")

ALLOWED_HOSTS = []

# HTTPS settings

# Set this to True in production to avoid transmitting the CSRF cookie over HTTP accidentally.
CSRF_COOKIE_SECURE = False
# Set this to True in production to avoid transmitting the CSRF cookie over HTTP accidentally.
SESSION_COOKIE_SECURE = False
# Change to True in production
SECURE_SSL_REDIRECT = False

# HSTS settings

# SECURE_HSTS_SECONDS = 31536000  # 1 year
# SECURE_HSTS_PRELOAD = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = False

# Email settings for the contact form
# Used only during development

EMAIL_HOST = os.getenv("EMAIL_HOST")
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
EMAIL_PORT = os.getenv("EMAIL_PORT")

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Installed apps
    'main_app.apps.MainAppConfig',
    'auth_app.apps.AuthAppConfig',
    'profile_app.apps.ProfileAppConfig',
    'settings_app.apps.SettingsAppConfig',
    'messages_app.apps.MessagesAppConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'body.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'body.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

STATICFILES_DIRS = [
    BASE_DIR / "static"
]


# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# This is set when creating a custom user model.
AUTH_USER_MODEL = 'main_app.Member'


我感谢所有人的帮助.

推荐答案

这一切为什么要发生?

您在URL中包含了profilepage/urls.py模块,但很可能在after中包含了static个路径.

我如何解决此问题?

您通常在root urls.py after所有其他路径上定义静态路径和媒体路径,以便只有在所有其他路径匹配失败时才使用它,因此:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path

urlpatterns = (
    [
        path('admin/', admin.site.urls),
        path('', include('auth_app.urls')),      # 🖘 no static/media urls
        path('', include('main_app.urls')),      # 🖘 no static/media urls
        path('', include('profile_app.urls')),   # 🖘 no static/media urls
        path('', include('messages_app.urls')),  # 🖘 no static/media urls
        path('', include('settings_app.urls')),  # 🖘 no static/media URLs
    ]
    + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
)

因此,重要的是,auth_app.urlsmain_app.urlsprofile_app.urlsmessages_app.urlssettings_app.urls DO not包含静态/媒体路径.严格地说,这也不是问题,只要这些通配符不是匹配任何路径的"通配符",但正如您所发现的,情况很容易就是这样.

这与我的设置文件有关吗?

No:URL的顺序很重要:Django将从上到下匹配这些URL,匹配的第一个模式将"触发".因此,如果您有一个与any路径匹配的路径模式,它将始终触发,因此Django将永远不会查找链中更远的任何路径.

直接派生View类的子类化通常是not所必需的.在这种情况下,您的视图看起来像DetailView [Django-doc].通过使用DetailView而不是简单的View,您通常不必实现许多样板代码.

from django.shortcuts import get_object_or_404
from django.views.generic import DetailView


class ProfilePageView(DetailView):
    model = ProfilepageMember
    template_name = 'profile_app/profilepage.html'
    context_object_name = 'user_related_data'

    def get_object(self, *args, **kwargs):
        return get_object_or_404(ProfilepageMember, member__username=user_name)

Django相关问答推荐

对象Django API中的对象

错误``Forbidden (403) CSRF 验证失败.请求中止.``` 当try 登录管理员时

Django ORM:子查询上的文本聚合器

如果一个应用程序有多个具有相同字段的模型,那么保持 DRY 的最佳实践是什么?

Django 独立脚本

如何使用 jQuery 建立 Django 网站

将 **kwargs 传递给 Django 表单

可插拔应用程序的Django默认设置约定?

获取 Django 中的缓存键列表

在 django 模板中遇到 user.is_authenticated 问题

django npm 和 node 包架构

使用 Python / Django 的 Google API 示例的 Oauth

jinja2模板引擎中的这个-是做什么的?

在python中查找对对象的所有引用

Django 模板和变量属性

Django:如何编写查询以使用多列进行排序,通过模板显示

如何以编程方式对 Django 中的用户进行身份验证?

如何在 django 中捕获UNIQUE constraint failed404

具有 2 种语言的 Django 站点

APIView 类和视图集类之间的区别?