首页 新闻 会员 周边 捐助

django部署项目 报错

-1
悬赏园豆:50 [已解决问题] 解决于 2017-12-09 14:00

在线等急急急

下面是我的错误信息

 1 [root@localhost FLchatterbot]# python3 manage.py migrate
 2 Traceback (most recent call last):
 3   File "manage.py", line 22, in <module>
 4     execute_from_command_line(sys.argv)
 5   File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
 6     utility.execute()
 7   File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute
 8     self.fetch_command(subcommand).run_from_argv(self.argv)
 9   File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
10     self.execute(*args, **cmd_options)
11   File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute
12     self.check()
13   File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
14     include_deployment_checks=include_deployment_checks,
15   File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks
16     issues.extend(super()._run_checks(**kwargs))
17   File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
18     return checks.run_checks(**kwargs)
19   File "/usr/local/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
20     new_errors = check(app_configs=app_configs)
21   File "/usr/local/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config
22     return check_resolver(resolver)
23   File "/usr/local/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver
24     return check_method()
25   File "/usr/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check
26     for pattern in self.url_patterns:
27   File "/usr/local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
28     res = instance.__dict__[self.name] = self.func(instance)
29   File "/usr/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns
30     patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
31   File "/usr/local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
32     res = instance.__dict__[self.name] = self.func(instance)
33   File "/usr/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module
34     return import_module(self.urlconf_name)
35   File "/usr/local/lib/python3.5/importlib/__init__.py", line 126, in import_module
36     return _bootstrap._gcd_import(name[level:], package, level)
37   File "<frozen importlib._bootstrap>", line 986, in _gcd_import
38   File "<frozen importlib._bootstrap>", line 969, in _find_and_load
39   File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
40   File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
41   File "<frozen importlib._bootstrap_external>", line 662, in exec_module
42   File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
43   File "/root/Desktop/chatterbot/FLchatterbot/FLchatterbot/urls.py", line 28, in <module>
44     url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')),
45   File "/usr/local/lib/python3.5/site-packages/django/urls/conf.py", line 39, in include
46     'Specifying a namespace in include() without providing an app_name '
47 django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead
错误信息

下面是我的urls.py

"""FLchatterbot URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/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
from django.conf.urls import url, include
from chatterbot.ext.django_chatterbot import urls as chatterbot_urls
from bot import views 


urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.ChatterBotAppView.as_view(), name='main'),
    url(r'^admin/', admin.site.urls, name='admin'),
    url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')),


]
urls.py

下面是我的settings.py

  1 """
  2 Django settings for FLchatterbot project.
  3 
  4 Generated by 'django-admin startproject' using Django 1.11.7.
  5 
  6 For more information on this file, see
  7 https://docs.djangoproject.com/en/1.11/topics/settings/
  8 
  9 For the full list of settings and their values, see
 10 https://docs.djangoproject.com/en/1.11/ref/settings/
 11 """
 12 
 13 import os
 14 
 15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
 16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 17 
 18 
 19 # Quick-start development settings - unsuitable for production
 20 # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
 21 
 22 # SECURITY WARNING: keep the secret key used in production secret!
 23 SECRET_KEY = 'r$f@_ut^gf0*t!rjw+4_yh=33($p7#zp4%@oaaio9s$o3lv)1u'
 24 
 25 # SECURITY WARNING: don't run with debug turned on in production!
 26 DEBUG = True
 27 
 28 ALLOWED_HOSTS = ['*']
 29 
 30 
 31 # Application definition
 32 
 33 INSTALLED_APPS = [
 34     'django.contrib.admin',
 35     'django.contrib.auth',
 36     'django.contrib.contenttypes',
 37     'django.contrib.sessions',
 38     'django.contrib.messages',
 39     'django.contrib.staticfiles',
 40     'bot',
 41     'gunicorn',
 42 ]
 43 
 44 CHATTERBOT = {
 45     'name':'FLbot',
 46     'storage_adapter':'mongodbn.MongoDatabaseAdapter',
 47     'logic_adapters':[
 48         #{
 49         #    "import_path": "chatterbot.logic.BestMatch",
 50         #    "statement_comparison_function": "chatterbot.comparisons.levenshtein_distance",
 51         #    "response_selection_method": "chatterbot.response_selection.get_first_response"
 52         #},
 53         {
 54             'import_path': 'logic.MyLogicAdapter'
 55         },
 56         #{
 57         #    'import_path': 'chatterbot.logic.LowConfidenceAdapter',
 58         #    'threshold': 0.65,
 59         #    'default_response': '我还不知道=?='
 60         #},
 61         'chatterbot.logic.MathematicalEvaluation',
 62     ],
 63     'database':'chatterbot-1w',
 64     'database_uri':"mongodb://192.168.2.128:27017/",
 65     'read_only':True,
 66     'django_app_name':"FLchatterbot",
 67 }
 68 
 69 MIDDLEWARE = [
 70     'django.middleware.security.SecurityMiddleware',
 71     'django.contrib.sessions.middleware.SessionMiddleware',
 72     'django.middleware.common.CommonMiddleware',
 73     #'django.middleware.csrf.CsrfViewMiddleware',
 74     'django.contrib.auth.middleware.AuthenticationMiddleware',
 75     'django.contrib.messages.middleware.MessageMiddleware',
 76     'django.middleware.clickjacking.XFrameOptionsMiddleware',
 77 ]
 78 
 79 ROOT_URLCONF = 'FLchatterbot.urls'
 80 
 81 
 82 TEMPLATES = [
 83     {
 84         'BACKEND': 'django.template.backends.django.DjangoTemplates',
 85         'DIRS': [],
 86         'APP_DIRS': True,
 87         'OPTIONS': {
 88             'context_processors': [
 89                 'django.template.context_processors.debug',
 90                 'django.template.context_processors.request',
 91                 'django.contrib.auth.context_processors.auth',
 92                 'django.contrib.messages.context_processors.messages',
 93             ],
 94         },
 95     },
 96 ]
 97 
 98 WSGI_APPLICATION = 'FLchatterbot.wsgi.application'
 99 
100 
101 # Database
102 # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
103 
104 DATABASES = {
105     'default': {
106         'ENGINE': 'django.db.backends.sqlite3',
107         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
108     }
109 }
110 
111 
112 # Password validation
113 # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
114 
115 AUTH_PASSWORD_VALIDATORS = [
116     {
117         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
118     },
119     {
120         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
121     },
122     {
123         'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
124     },
125     {
126         'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
127     },
128 ]
129 
130 
131 # Internationalization
132 # https://docs.djangoproject.com/en/1.11/topics/i18n/
133 
134 LANGUAGE_CODE = 'en-us'
135 
136 TIME_ZONE = 'UTC'
137 
138 USE_I18N = True
139 
140 USE_L10N = True
141 
142 USE_TZ = True
143 
144 
145 # Static files (CSS, JavaScript, Images)
146 # https://docs.djangoproject.com/en/1.11/howto/static-files/
147 
148 STATIC_URL = '/static/'
149 STATICFILES_DIRS = (
150     os.path.join(
151         os.path.dirname(__file__),
152         'static',
153     ),
154 )
setting.py

下面是源码"/usr/local/lib/python3.5/site-packages/django/urls/conf.py"

"""Functions for use in URLsconfs."""
from functools import partial
from importlib import import_module

from django.core.exceptions import ImproperlyConfigured

from .resolvers import (
    LocalePrefixPattern, RegexPattern, RoutePattern, URLPattern, URLResolver,
)


def include(arg, namespace=None):
    app_name = None
    if isinstance(arg, tuple):
        # Callable returning a namespace hint.
        try:
            urlconf_module, app_name = arg
        except ValueError:
            if namespace:
                raise ImproperlyConfigured(
                    'Cannot override the namespace for a dynamic module that '
                    'provides a namespace.'
                )
            raise ImproperlyConfigured(
                'Passing a %d-tuple to include() is not supported. Pass a '
                '2-tuple containing the list of patterns and app_name, and '
                'provide the namespace argument to include() instead.' % len(arg)
            )
    else:
        # No namespace hint - use manually provided namespace.
        urlconf_module = arg

    if isinstance(urlconf_module, str):
        urlconf_module = import_module(urlconf_module)
    patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
    app_name = getattr(urlconf_module, 'app_name', app_name)
    if namespace and not app_name:
        raise ImproperlyConfigured(
            'Specifying a namespace in include() without providing an app_name '
            'is not supported. Set the app_name attribute in the included '
            'module, or pass a 2-tuple containing the list of patterns and '
            'app_name instead.',
        )
    namespace = namespace or app_name
    # Make sure the patterns can be iterated through (without this, some
    # testcases will break).
    if isinstance(patterns, (list, tuple)):
        for url_pattern in patterns:
            pattern = getattr(url_pattern, 'pattern', None)
            if isinstance(pattern, LocalePrefixPattern):
                raise ImproperlyConfigured(
                    'Using i18n_patterns in an included URLconf is not allowed.'
                )
    return (urlconf_module, app_name, namespace)


def _path(route, view, kwargs=None, name=None, Pattern=None):
    if isinstance(view, (list, tuple)):
        # For include(...) processing.
        pattern = Pattern(route, is_endpoint=False)
        urlconf_module, app_name, namespace = view
        return URLResolver(
            pattern,
            urlconf_module,
            kwargs,
            app_name=app_name,
            namespace=namespace,
        )
    elif callable(view):
        pattern = Pattern(route, name=name, is_endpoint=True)
        return URLPattern(pattern, view, kwargs, name)
    else:
        raise TypeError('view must be a callable or a list/tuple in the case of include().')


path = partial(_path, Pattern=RoutePattern)
re_path = partial(_path, Pattern=RegexPattern)
源码
DanBrown的主页 DanBrown | 小虾三级 | 园豆:1321
提问于:2017-12-05 09:00
< >
分享
最佳答案
3

用的是django2.0吧,应该是前天才出来的,我今天也碰到这个问题了。

报错信息:

Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

根据报错信息,app_name应该是 chatterbot_urls 里的属性(attribute),在app目录下的urls.py文件中直接定义这个变量app_name,并赋值为你的app名称即可。

你上传的这个urls.py应该是项目目录中的。以下是我的app目录下的urls.py的内容:

from django.conf.urls import url

from . import views

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

app_name = 'pizzerias'
收获园豆:50
dev-liu | 菜鸟二级 |园豆:254 | 2017-12-07 21:59

我把这试了一下

 1 """FLchatterbot URL Configuration
 2 
 3 The `urlpatterns` list routes URLs to views. For more information please see:
 4     https://docs.djangoproject.com/en/2.0/topics/http/urls/
 5 Examples:
 6 Function views
 7     1. Add an import:  from my_app import views
 8     2. Add a URL to urlpatterns:  path('', views.home, name='home')
 9 Class-based views
10     1. Add an import:  from other_app.views import Home
11     2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
12 Including another URLconf
13     1. Import the include() function: from django.urls import include, path
14     2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
15 """
16 from django.contrib import admin
17 from django.urls import path
18 from django.conf.urls import url, include
19 #from chatterbot.ext.django_chatterbot import urls as chatterbot_urls
20 from bot import views
21 from myapi import urls as chatterbot_urls
22 urlpatterns = [
23     path('admin/', admin.site.urls),
24     url(r'^$', views.ChatterBotAppView.as_view(), name='main'),
25     url(r'^admin/', admin.site.urls, name='admin'),
26     #url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')),
27     url(r'^api/chatterbot/', include(chatterbot_urls)),
28 ]
29 app_name = 'chatterbot'
urls

执行信息

 1 root@localhost FLchatterbot]# python3 manage.py migrate django_chatterbotSystem check identified some issues:
 2 
 3 WARNINGS:
 4 ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace
 5 Operations to perform:
 6   Apply all migrations: django_chatterbot
 7 Running migrations:
 8   Applying django_chatterbot.0001_initial... OK
 9   Applying django_chatterbot.0002_statement_extra_data... OK
10   Applying django_chatterbot.0003_change_occurrence_default... OK
11   Applying django_chatterbot.0004_rename_in_response_to... OK
12   Applying django_chatterbot.0005_statement_created_at... OK
13   Applying django_chatterbot.0006_create_conversation... OK
14   Applying django_chatterbot.0007_response_created_at... OK
15   Applying django_chatterbot.0008_update_conversations... OK
16   Applying django_chatterbot.0009_tags... OK
17   Applying django_chatterbot.0010_statement_text... OK
18   Applying django_chatterbot.0011_blank_extra_data... OK
执行信息

如果我用url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')),不加app_name

就报那个include错误(加上APP_name)也包相同的

 1 [root@localhost FLchatterbot]# python3 manage.py migrate django_chatterbot
 2 Traceback (most recent call last):
 3   File "manage.py", line 15, in <module>
 4     execute_from_command_line(sys.argv)
 5   File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
 6     utility.execute()
 7   File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute
 8     self.fetch_command(subcommand).run_from_argv(self.argv)
 9   File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
10     self.execute(*args, **cmd_options)
11   File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute
12     self.check()
13   File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
14     include_deployment_checks=include_deployment_checks,
15   File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks
16     issues.extend(super()._run_checks(**kwargs))
17   File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
18     return checks.run_checks(**kwargs)
19   File "/usr/local/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
20     new_errors = check(app_configs=app_configs)
21   File "/usr/local/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config
22     return check_resolver(resolver)
23   File "/usr/local/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver
24     return check_method()
25   File "/usr/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check
26     for pattern in self.url_patterns:
27   File "/usr/local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
28     res = instance.__dict__[self.name] = self.func(instance)
29   File "/usr/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns
30     patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
31   File "/usr/local/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
32     res = instance.__dict__[self.name] = self.func(instance)
33   File "/usr/local/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module
34     return import_module(self.urlconf_name)
35   File "/usr/local/lib/python3.5/importlib/__init__.py", line 126, in import_module
36     return _bootstrap._gcd_import(name[level:], package, level)
37   File "<frozen importlib._bootstrap>", line 986, in _gcd_import
38   File "<frozen importlib._bootstrap>", line 969, in _find_and_load
39   File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
40   File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
41   File "<frozen importlib._bootstrap_external>", line 662, in exec_module
42   File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
43   File "/home/chatterbot/FLchatterbot/FLchatterbot/urls.py", line 26, in <module>
44     url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')),
45   File "/usr/local/lib/python3.5/site-packages/django/urls/conf.py", line 39, in include
46     'Specifying a namespace in include() without providing an app_name '
47 django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
错误信息

然后我又 分别 测试,在 url(r'^api/chatterbot/', include(chatterbot_urls)),(添加和不添加app_name = 'chatterbot')发现运行结果都为

 1 """FLchatterbot URL Configuration
 2 
 3 The `urlpatterns` list routes URLs to views. For more information please see:
 4     https://docs.djangoproject.com/en/2.0/topics/http/urls/
 5 Examples:
 6 Function views
 7     1. Add an import:  from my_app import views
 8     2. Add a URL to urlpatterns:  path('', views.home, name='home')
 9 Class-based views
10     1. Add an import:  from other_app.views import Home
11     2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
12 Including another URLconf
13     1. Import the include() function: from django.urls import include, path
14     2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
15 """
16 from django.contrib import admin
17 from django.urls import path
18 from django.conf.urls import url, include
19 #from chatterbot.ext.django_chatterbot import urls as chatterbot_urls
20 from bot import views
21 from myapi import urls as chatterbot_urls
22 urlpatterns = [
23     path('admin/', admin.site.urls),
24     url(r'^$', views.ChatterBotAppView.as_view(), name='main'),
25     url(r'^admin/', admin.site.urls, name='admin'),
26     #url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')),
27     url(r'^api/chatterbot/', include(chatterbot_urls)),
28 ]
29 app_name = 'chatterbot'
测试2
 1 [root@localhost FLchatterbot]# python3 manage.py migrate django_chatterbot
 2 System check identified some issues:
 3 
 4 WARNINGS:
 5 ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace
 6 Operations to perform:
 7   Apply all migrations: django_chatterbot
 8 Running migrations:
 9   No migrations to apply.
10 [root@localhost FLchatterbot]# python3 manage.py migrate django_chatterbot
11 System check identified some issues:
12 
13 WARNINGS:
14 ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace
15 Operations to perform:
16   Apply all migrations: django_chatterbot
17 Running migrations:
18   No migrations to apply.
19 You have new mail in /var/spool/mail/root
运行结果
DanBrown | 园豆:1321 (小虾三级) | 2017-12-08 09:20

@DanBrown:不指定namespace(命名空间)的话,是不会报这个错了,但是后面使用html模板可能还会出问题,建议还是加上namespace。

你的这个url文件是在哪个目录下的,怎么感觉还是在项目目录中呢?目录结构方便贴一下不?

app_name这个变量是要在你后面建的app目录下的urls.py中的。

你看这是我的目录结构:

mysite/
  manage.py
  proj_pizzeria/
    __init__.py
    settings.py
    urls.py
    wsgi.py
  app_pizzeria/
    __init__.py
    admin.py
    apps.py
    forms.py
    models.py
    tests.py
    urls.py  #app_name should be defined in this file.
    views.py

proj_pizzeria/ 是项目目录,app_pizzeria/ 是app目录,app目录下面标红的文件才是定义app_name的文件(跟models.py在同一目录下)。

dev-liu | 园豆:254 (菜鸟二级) | 2017-12-11 23:42

@Pizzerias: 

FLchatterbot 我实在这个文件下的urls.py改的 应该是修改错了我在下面再贴一下这个文件下的目录(标记1)
        
__pycache__
        
bot
        
文件: db.sqlite3
    
文件: manage.py
    
文件: mongodbn.py
    
myapi
        
文件: mylogic.py
    
文件: nohup.out
    
文件: views.py

标记1下的目录(FLchatterbot)

文件: __init__.py
        
__pycache__
        
文件: settings.py
    
文件: settings.py~
    
static
        
文件: urls.py
    
文件: wsgi.py

下面我在贴出bot下的目录

文件: __init__.py
        
__pycache__
        
文件: admin.py
    
文件: apps.py
    
migrations
        
文件: models.py
    
static
        
templates
        
文件: tests.py
    
文件: views.py
    

我发现我bot文件夹下没有urls.py是要加上一个吗?

这里面应该怎么加呢?

DanBrown | 园豆:1321 (小虾三级) | 2017-12-12 08:35

@DanBrown: 是的,startapp创建app后,目录默认是没有url文件的,是需要新建一个,这个urls.py是用来定义app中生成的URL模式及对应的视图函数的。

项目的urls.py(你之前上传的)用来定义app的URL。

我的项目目录下的urls.py文件内容:

from django.conf.urls import url, include
from django.contrib import admin


urlpatterns = [ url(r'^admin/', admin.site.urls), #默认的admin URL url(r'^users/', include('users.urls', namespace='users')), #users app's URL url(r'', include('app_pisseria.urls', namespace='pisseria')), # pisseria app's URL ]

之前我创建了两个app,一个是users,一个是pisseria,需要分别在这里定义app对应的URL及namespace命名空间。

 

users app目录下的urls.py内容:

from django.conf.urls import url
from django.contrib.auth.views import login

from . import views


urlpatterns = [ url(r'^login/$', login, {'template_name': 'users/login.html'}, name='login'), url(r'^logout/$', views.logout_view, name='logout'), url(r'^register/$', views.register, name='register'), ]

app_name = 'users'

这里主要是定义app具体的URL模式,app_name也是在这里定义的。

所以两个urls文件的作用不一样。

 

如果你对整个项目的基本搭建流程还不是特别熟悉的话,建议参考一下官方文档里的tutorials.里面有具体的例子,跟着做一遍就差不多了。

 

dev-liu | 园豆:254 (菜鸟二级) | 2017-12-13 00:34

我在自学Python,打例程中,总是会遇到这样那样的问题,都是通过百度解决啦,我真的很感谢这些好伙伴。

今天遇到的错误提示就是在这儿找到答案的,并且解决了。所以,非常感谢,同时也马上注册进来把解决方案放在这儿,以便于其他伙伴参考。

书籍:《Python编程:从入门到实践》(Eric Matthes)

例子:项目3“Web应用程序”第18.3,在运行python3 manage.py runserver时候出现的

解决方法:

在learning_logs文件夹(注意不是learning_log那个文件夹下面的)下面的urls.py中,把书上的案例另外加上一行,最后变成楼主贴出来的,再运行就可以了。

 

 

 

JasonPython | 园豆:200 (初学一级) | 2018-01-07 20:24
其他回答(3)
0

所以这个问题是解决了吗?我想了很久没看懂是哪里出错了

sanjay0609 | 园豆:202 (菜鸟二级) | 2017-12-17 00:18

解决了,一开始我用的2.0版本,换到了1.11.7就好了,因该是我用Django2.0没有在app_name指定url(但是我没试)

支持(0) 反对(0) DanBrown | 园豆:1321 (小虾三级) | 2017-12-17 07:59

@DanBrown: 我也解决了,用的2.0版本!哈哈😄想了两天

支持(0) 反对(0) sanjay0609 | 园豆:202 (菜鸟二级) | 2017-12-17 11:20

@sanjay0609: 你怎么解决的是在app目录下的urls.py内容吗?

支持(0) 反对(0) DanBrown | 园豆:1321 (小虾三级) | 2017-12-17 11:21

@DanBrown: app_name 要加在应用程序的urls.py里,你有用到视图的模版吗,用到的话,要在setting里的模版的TEMPLATE里加上 os.path.jion(BASE_DIR, "你自己的模版名")

支持(1) 反对(0) sanjay0609 | 园豆:202 (菜鸟二级) | 2017-12-17 22:06

@sanjay0609: 请教一下怎么解决啊

支持(0) 反对(0) 小勿 | 园豆:200 (初学一级) | 2017-12-20 17:11
0

感谢,有帮助

沧海红心_田帅 | 园豆:202 (菜鸟二级) | 2018-01-05 19:36
0

url(r'^admin/', admin.site.urls), 换成这种不抱错了 admin 出不来

_York | 园豆:38 (初学一级) | 2018-01-12 09:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册