I am newbie to django.I m using python 2.6 with django 1.3v I am trying to create a simple blog application.When I access the http://127.0.0.1:8000/admin/ I’m getting the error No module named urls.I gave this
url(r'^admin/', include('django.contrib.admin.urls')) in urls.py.
urls.py
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include('django.contrib.admin.urls')),
)
settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite.blog',
#Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentatio n:
'django.contrib.admindocs',
)
models.py
from django.db import models
from django.contrib import admin
class BlogPost(models.Model):
title=models.CharField(max_length=150)
body=models.TextField()
timestamp=models.DateTimeField()
admin.site.register(BlogPost)
Error:
ImportError at /admin/
No module named urls
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.3
Exception Type: ImportError
Exception Value:
No module named urls
Exception Location: /usr/local/lib/python2.6/dist-packages/django/utils/importlib.py in import_module, line 35
Python Executable: /usr/bin/python
Python Version: 2.6.6
Python Path:
['/home/bharathi/development/python/mysite',
'/usr/lib/python2.6',
'/usr/lib/python2.6/plat-linux2',
'/usr/lib/python2.6/lib-tk',
'/usr/lib/python2.6/lib-old',
'/usr/lib/python2.6/lib-dynload',
'/usr/local/lib/python2.6/dist-packages',
'/usr/lib/python2.6/dist-packages',
'/usr/lib/pymodules/python2.6',
'/usr/lib/pymodules/python2.6/gtk-2.0']
Any pointers?
|
TheDoctor666 0 / 0 / 0 Регистрация: 20.09.2016 Сообщений: 11 |
||||
|
1 |
||||
|
03.02.2017, 21:07. Показов 7372. Ответов 10 Метки нет (Все метки)
Доброго времени суток В папке моего проекта файл urls.py содержит следущий код:
где, page название созданного приложения. Файл urls в page создал когда запускаю сервер пишет ошибку: Как быть, подскажите?
__________________
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
03.02.2017, 21:07 |
|
Ответы с готовыми решениями: Django-cron выдает ошибку при запуске cron из терминала Помогите разобраться пожалуйста, нужно срочно запустить cron Установила… При переносе сайта на Django на другой хостинг пишет ошибку че-то там хостеры сделали… СМА Hansa PG5510A412 s/n 04454930213108 после нескольких минут выдает ошибку, выдает ошибку Программа которая выдает платформу компьютера выдает ошибку interface uses 10 |
|
__py__ in code we trust 133 / 162 / 12 Регистрация: 29.02.2016 Сообщений: 883 |
||||
|
04.02.2017, 10:14 |
2 |
|||
|
Туториал с офиц сайта?
goods заменить на page и модифицировать надо корректно. Как у меня. У меня всё работает. Левые туториалы выкинуть все. Добавлено через 25 секунд Добавлено через 3 минуты Добавлено через 44 секунды
0 |
|
2738 / 2341 / 620 Регистрация: 19.03.2012 Сообщений: 8,832 |
|
|
04.02.2017, 10:47 |
3 |
|
Зачем ему регистрироваться где-то если ошибка очевидна + то, что ты пишешь запрещено правилами форума.
rl(r’^goods/’, page.urls), Естественно будет ошибка, ты же не импортнул page, конечно питон орать будет на тебя.
NameError: name ‘page’ is not defined Все очень очевидно
0 |
|
TheDoctor666 0 / 0 / 0 Регистрация: 20.09.2016 Сообщений: 11 |
||||
|
04.02.2017, 11:02 [ТС] |
4 |
|||
|
__py__, пользуюсь книгой, но она под старую версию джанго, много кода приходилось переискивать самому, а тут вообще ничего не могу понять, уже три дня застрял на месте Добавлено через 1 минуту
ничего не импортировал, да и пробовал не помогает
0 |
|
alex925 2738 / 2341 / 620 Регистрация: 19.03.2012 Сообщений: 8,832 |
||||
|
04.02.2017, 11:41 |
5 |
|||
|
TheDoctor666, сколько пересмотрел примеров в интернете никто кроме Не верю, сам видел кучу правильных примеров, в том числе и на оф сайте. from pages include urls А это что за монстор вообще? Должно быть, что-то вроде этого
И из views берутся все твои вьюхи. https://docs.djangoproject.com… utorial01/
0 |
|
__py__ in code we trust 133 / 162 / 12 Регистрация: 29.02.2016 Сообщений: 883 |
||||
|
04.02.2017, 12:12 |
6 |
|||
|
пробовал как у вас, пишет всё в точности надо как здесь < только аргументы заменить в скобках > всё работает.
Добавлено через 4 минуты
пользуюсь книгой, но она под старую версию джанго, офиц туториал есть, зачем старый запорожец, к которому даже деталей не найти если сломается? Добавлено через 7 минут Добавлено через 7 минут
Должно быть, что-то вроде этого Отсюда у многих новичков путаница, путают 2 одинаково названных файла url.py, один из которых в директории mysite лежит. Добавлено через 1 минуту
0 |
|
2738 / 2341 / 620 Регистрация: 19.03.2012 Сообщений: 8,832 |
|
|
04.02.2017, 12:19 |
7 |
|
__py__, это код с оф сайта, если честно мне джанга вообще побоку, не нравится она мне.
0 |
|
0 / 0 / 0 Регистрация: 20.09.2016 Сообщений: 11 |
|
|
05.02.2017, 01:57 [ТС] |
8 |
|
__py__ alex925
0 |
|
Ennjin |
|
05.02.2017, 08:16
|
|
Не по теме:
все заработало, но появились другие ошибки Забудте про джангу, изучайте фласк
0 |
|
in code we trust 133 / 162 / 12 Регистрация: 29.02.2016 Сообщений: 883 |
|
|
05.02.2017, 08:32 |
10 |
|
Забудте про джангу, изучайте фласк Flask переводится как фляга — это означает, что без бутылки не разберёшься
0 |
|
2738 / 2341 / 620 Регистрация: 19.03.2012 Сообщений: 8,832 |
|
|
05.02.2017, 11:40 |
11 |
|
Забудте про джангу, изучайте фласк flask крутой, но TheDoctor666 его объективно не потянет, тем более в сети хорошего туториала нет. А вообще согласен) TheDoctor666, ни каких вредных советов я тебе не давал. Я тебе указал на твою грубейшую ошибку и все. Для того, чтобы ее увидеть не нужно писать на джанге.
0 |
Syntax Error from django.contrib import admin
Hello everybody, i’m newbie in pythonanywhere, i follow the tutorial (https://www.pythonanywhere.com/wiki/DjangoTutorial) to start my project , but I can’t access http://anthraxp.pythonanywhere.com/admin/ il shows always:
It worked! Congratulations on your first Django-powered page.
Of course, you haven’t actually done any work yet. Here’s what to do next:
If you plan to use a database, edit the DATABASES setting in mysite/settings.py.
Start your first app by running python mysite/manage.py startapp [appname].
You’re seeing this message because you have DEBUG = True in your Django settings file and you haven’t configured any URLs. Get to work!
I am seeing this Error when saving urls.py Please Suggest me What to do. I am stuck, I have taken all steps carefully Please help me admins
deleted-user-117041
|
3
posts
|
Oct. 22, 2013, 9:41 a.m.
|
permalink
Where’s the syntax error? That looks like you have a working Django app.

glenn
|
8666
posts
|
PythonAnywhere staff
|
Oct. 22, 2013, 9:51 a.m.
|
permalink
When I am opening the file urls.py at line number 4 I seek a Cross mark.
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin #i am seeing error here
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'AskQuestion.views.home', name='home'),
#url(r'^AskQuestion/', include('AskQuestion.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
#url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
I am also not able to open admin area http://anthraxp.pythonanywhere.com/admin/
Shows this Message
It worked!
Congratulations on your first Django-powered page.
Of course, you haven’t actually done any work yet. Here’s what to do next:
If you plan to use a database, edit the DATABASES setting in AskQuestion/settings.py.
Start your first app by running python AskQuestion/manage.py startapp [appname].
You’re seeing this message because you have DEBUG = True in your Django settings file and you haven’t configured any URLs. Get to work!
I have done all the steps well from tutorial Till Defining your urls
edit by admin for formatting
deleted-user-117041
|
3
posts
|
Oct. 22, 2013, 9:57 a.m.
|
permalink
I noticed this when I edited your post to include the Python formatting: If your code block above is a direct copy of your urls.py, then you have indentation problems on the line of the error and the one that follows it. In Python, whitespace is important and you have a space at the start of those 2 lines.

glenn
|
8666
posts
|
PythonAnywhere staff
|
Oct. 22, 2013, 10:06 a.m.
|
permalink
Thank you for your support but now i am getting this error message while loading this domain: http://anthraxp.pythonanywhere.com/
ViewDoesNotExist at /
Could not import AskQuestion.views. Error was: No module named views
and long page of details load
But i have created a view in askquestions/myapp/views.py
Please tell what to do?
deleted-user-117041
|
3
posts
|
Oct. 22, 2013, 10:35 a.m.
|
permalink
I can see several possible sources of the problem:
1. The error mentions AskQuestion.views (with caps), but you give the path to the file as askquestions (lowercase and with an s)
2. Your path includes myapp in the path, but the view that could not be found does not
Check that the modules you import agree with the folder structure.

glenn
|
8666
posts
|
PythonAnywhere staff
|
Oct. 22, 2013, 2:56 p.m.
|
permalink
The top level import of django.contrib.admin.models.LogEntry in the module reversion.models causes a startup error in Django projects that don’t include django.contrib.admin in INSTALLED_APPS:
RuntimeError: Model class django.contrib.admin.models.LogEntry doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS.
Perhaps this import could moved into the Revision.get_comment() method?
—
Affects version 3.0.0
| from django.contrib.admin.models import LogEntry |
I don’t get that issue in my tests, or any of my production code.
Can I see your traceback?
…
On 7 August 2018 at 01:45, Wyatt ***@***.***> wrote:
The top level import of django.contrib.admin.models.LogEntry in the
module reversion.models causes a startup error in Django projects that
don’t include django.contrib.admin in INSTALLED_APPS:
RuntimeError: Model class django.contrib.admin.models.LogEntry doesn’t
declare an explicit app_label and isn’t in an application in INSTALLED_APPS.
Perhaps this import could moved into the Revision.get_comment() method?
—
Affects version 3.0.0
https://github.com/etianen/django-reversion/blob/
d4cb8aa
/reversion/models.py#L10
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#744>, or mute the
thread
<https://github.com/notifications/unsubscribe-auth/AAJFCGeUwZ0ATSwmqg6TJ0eMEFUV7_GIks5uOOMSgaJpZM4VxTjY>
.
I should have mentioned also that I’m using Django 2.0.8. Here’s the traceback from running manage.py test:
Traceback (most recent call last):
File «./manage.py», line 20, in
execute_from_command_line([sys.argv[0]] + remaining_args)
File «/project/virtualenv/lib/python3.5/site-packages/django/core/management/init.py», line 371, in execute_from_command_line
utility.execute()
File «/project/virtualenv/lib/python3.5/site-packages/django/core/management/init.py», line 347, in execute
django.setup()
File «/project/virtualenv/lib/python3.5/site-packages/django/init.py», line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File «/project/virtualenv/lib/python3.5/site-packages/django/apps/registry.py», line 112, in populate
app_config.import_models()
File «/project/virtualenv/lib/python3.5/site-packages/django/apps/config.py», line 198, in import_models
self.models_module = import_module(models_module_name)
File «/project/virtualenv/lib/python3.5/importlib/init.py», line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File «», line 985, in _gcd_import
File «», line 968, in _find_and_load
File «», line 957, in _find_and_load_unlocked
File «», line 673, in _load_unlocked
File «», line 697, in exec_module
File «», line 222, in _call_with_frames_removed
File «/project/virtualenv/lib/python3.5/site-packages/reversion/models.py», line 10, in
from django.contrib.admin.models import LogEntry
File «/project/virtualenv/lib/python3.5/site-packages/django/contrib/admin/models.py», line 33, in
class LogEntry(models.Model):
File «/project/virtualenv/lib/python3.5/site-packages/django/db/models/base.py», line 108, in new
«INSTALLED_APPS.» % (module, name)
RuntimeError: Model class django.contrib.admin.models.LogEntry doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS.
Oh, I just realized.
You need to add django.contrib.admin to your INSTALLED_APPS setting.
…
On 7 August 2018 at 19:43, Wyatt ***@***.***> wrote:
I should have mentioned also that I’m using Django 2.0.8. Here’s the
traceback from running manage.py test:
Traceback (most recent call last):
File «./manage.py», line 20, in
execute_from_command_line([sys.argv[0]] + remaining_args)
File «/project/virtualenv/lib/python3.5/site-packages/
django/core/management/*init*.py», line 371, in execute_from_command_line
utility.execute()
File «/project/virtualenv/lib/python3.5/site-packages/
django/core/management/*init*.py», line 347, in execute
django.setup()
File «/project/virtualenv/lib/python3.5/site-packages/django/*init*.py»,
line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File «/project/virtualenv/lib/python3.5/site-packages/django/apps/registry.py»,
line 112, in populate
app_config.import_models()
File «/project/virtualenv/lib/python3.5/site-packages/django/apps/config.py»,
line 198, in import_models
self.models_module = import_module(models_module_name)
File «/project/virtualenv/lib/python3.5/importlib/*init*.py», line 126,
in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File «», line 985, in _gcd_import
File «», line 968, in _find_and_load
File «», line 957, in _find_and_load_unlocked
File «», line 673, in _load_unlocked
File «», line 697, in exec_module
File «», line 222, in _call_with_frames_removed
File «/project/virtualenv/lib/python3.5/site-packages/reversion/models.py»,
line 10, in
from django.contrib.admin.models import LogEntry
File «/project/virtualenv/lib/python3.5/site-packages/
django/contrib/admin/models.py», line 33, in
class LogEntry(models.Model):
File «/project/virtualenv/lib/python3.5/site-packages/django/db/models/base.py»,
line 108, in *new*
«INSTALLED_APPS.» % (module, name)
RuntimeError: Model class django.contrib.admin.models.LogEntry doesn’t
declare an explicit app_label and isn’t in an application in INSTALLED_APPS.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#744 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AAJFCNt85DqOVKQ0JJtIpReMGAAdwqneks5uOd_igaJpZM4VxTjY>
.
That’s a possible solution, as I noted above, but not all projects use the Django admin and IMO shouldn’t be required to «install» it just to avoid this error.
Good point—moving the import would only work for cases where Revision.get_comment() is never used. This is a bit more complex but also more robust:
diff --git a/reversion/models.py b/reversion/models.py index bde6c5b..87f0a3e 100644 --- a/reversion/models.py +++ b/reversion/models.py @@ -1,13 +1,13 @@ from __future__ import unicode_literals from collections import defaultdict from itertools import chain, groupby +from django.apps import apps from django.contrib.contenttypes.models import ContentType try: from django.contrib.contenttypes.fields import GenericForeignKey except ImportError: # Django < 1.9 pragma: no cover from django.contrib.contenttypes.generic import GenericForeignKey from django.conf import settings -from django.contrib.admin.models import LogEntry from django.core import serializers from django.core.serializers.base import DeserializationError from django.core.exceptions import ObjectDoesNotExist @@ -21,6 +21,23 @@ from reversion.errors import RevertError from reversion.revisions import _get_options, _get_content_type, _follow_relations_recursive +# On Django >= 1.10, the Django admin change message is used as the +# revision comment, but only if the Django admin app is installed. +try: + admin_app = apps.get_app_config('admin') +except LookupError: + LogEntry = None +else: + # Additional check to ensure the installed admin app is actually + # Django's admin app and not a custom app that uses the "admin" + # label. + if admin_app.name == 'django.contrib.admin': + LogEntry = admin_app.get_model('LogEntry') + # Django < 1.10 LogEntry doesn't have a get_change_message method + if not hasattr(LogEntry, 'get_change_message'): + LogEntry = None + + def _safe_revert(versions): unreverted_versions = [] for version in versions: @@ -64,12 +81,10 @@ class Revision(models.Model): ) def get_comment(self): - try: + if LogEntry: return LogEntry(change_message=self.comment).get_change_message() - except AttributeError: - # Django < 1.10 - # LogEntry dont have `.get_change_message()` - return self.comment + # Django < 1.10 or Django admin not enabled + return self.comment def revert(self, delete=False): # Group the models by the database of the serialized model.
I just stumped on this with django 1.11.15
Instead of magic «try check version…» I suggest creating a REVERSION_INTEGRATE_WITH_DJANGO_ADMIN setting or alike. Is a pattern seen in other packages.
Going back to reversion 2.0.13 for now.
I got the same issue in my current project as I’m not using default Django Admin. Is the implementation mentioned above going to be released soon?
Now that the PR has been merged I think this issue can be closed 😃
здравствуйте, у меня немного, наверное,глупый вопрос, но всё же. Делаю сайт, всё работало хорошо, но когда выложил на хостинг, то вылазиет такая ошибка
Page not found (404)RequestUsing the URLconf defined in urls, Django tried these URL patterns, in this order:
^mysite/
^admin/doc/
^admin/(,*)The current URL, , didn't match any of these.
я думаю, что нужно как-то подправить файл urls.py:
from django.conf.urls.defaults import *# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()urlpatterns = patterns('',
# Example:
(r'^mysite/', include('mysite.blog.urls')),# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
(r'^admin/doc/', include('django.contrib.admindocs.urls')),# Uncomment the next line to enable the admin:
(r'^admin/(,*)', admin.site.root),)
просто не понимаю как и что здесь переделывать, ведь на локалке работало, подскажите, пожалуйста, в чем дело и что делать, заранее спасибо
Отредактировано (Ноя. 12, 2010 14:05:01)
A NoReverseMatch error is a common Django error and one that can often be fixed with just one line of code.
NoReverseMatch at /
Reverse for 'index' not found. 'index' is not a valid view function or pattern name.

The cause of the error is likely to be in your template (a HTML file), in urls.py or views.py.
The NoReverseMatch error happens when Django can’t find a path in urls.py that matches the provided name.
URLs can be referenced by name in templates, or in a view using the reverse, reverse_lazy, or redirect functions.
Solving the error is a matter of making sure the correct name and the correct arguments are supplied.
What is a URL name?
In urls.py, URL patterns take the following format:
path("filter/<str:status>", views.filter_tasks, name="filter")
This URL has a name of filter. Whenever you need to make reference to a URL, you can use the name instead of having to write out the whole URL.
Django will take the name and look it up in urls.py. If it finds a match, it will return the URL of the match. If it cannot find a match, it will raise a NoReverseMatch error.
Common Causes
1. Typo in urls.py or your template
This particular error has the name of the URL that couldn’t be matched:
NoReverseMatch at /
Reverse for 'index' not found. 'index' is not a valid view function or pattern name.
Go to urls.py file and confirm that there is a URL named index:
# todo/urls.py
from django.urls import path
from todo import views
urlpatterns = [
path("", views.index, name="index"),
]
2. You forgot to put quotations around the name
Consider this HTML snippet:
<a href="{% url filter Status.TODO 123%}">To Do</a>
This will give you the following error:
NoReverseMatch at /
Reverse for '' not found. '' is not a valid view function or pattern name.
You can fix this by putting single quotations around filter, the URL name.
<a href="{% url 'filter' Status.TODO 123%}">To Do</a>
3. You have provided too many or too few arguments
Consider this error:
NoReverseMatch at /
Reverse for 'filter' with arguments '(Task.StatusChoice.TODO, 123)' not found. 2 pattern(s) tried: ['filter/(?P<status>[^/]+)\Z', 'filter/(?P<status>[^/]+)\Z']
This is what I provided in my template:
<a href="{% url 'filter' Status.TODO 123%}">To Do</a>
And this is the URL pattern in urls.py:
path("filter/<str:status>", views.filter_tasks, name="filter")
Django has matched the name but my template provided 2 arguments; the URL path only expects one.
Because the number of arguments doesn’t match, Django cannot match the URL name, even though there is a URL pattern named “filter”.
The URL pattern in this example expects one argument. You can fix the error by removing the extra argument from the template.
4. Your app’s URLs haven’t been registered
Say you have checked your template and urls.py and there definitely isn’t a typo. The link in your template has the correct syntax and the correct number of arguments have been supplied.
The next step is to check the URLs for your app have been imported into the main urls.py.
Django projects are organised by apps. Your site directory (the folder that contains settings.py also has a file called urls.py that contains the index of URLs for the entire project. Each app can have its own urls.py file, but those URLs need to be imported into the main urls.py folder.
If you only have one app, then this won’t be the cause of your error. If you have one app and the URLs haven’t been imported into urls.py properly then you will get this screen instead of a NoReverseMatch error:

Check your site’s main urls.py file.
If you haven’t imported all the URLs for your app, then you will need to import include from django.urls and add a path to the URL patterns.
How to include your app’s URLs:
For example, my main urls.py file looks like this:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("sample.urls")),
path("", include("todo.urls")),
]
5. Error in “reverse”, “reverse_lazy” or “redirect”
NoReverseMatch errors don’t just happen in templates. They can happen anywhere in your code that tries to get a URL from a URL name. They are often used in views.py to redirect the user.
Three common functions that do this are:
- Reverse
- Reverse Lazy
- Redirect
The error could be in the name of the URL or the arguments supplied.
Consider this URL pattern:
path("filter/<str:status>", views.filter_tasks, name="filter")
It has a name of “filter” and accepts one argument- a string called “status”.
Because the URL pattern has parameters, reverse("filter") will return a NoReverseMatch error.
Instead, you must provide the “status” argument:
url = reverse("filter", args=["complete"])
The following is also acceptable if you prefer to name your arguments:
url = reverse("filter", kwargs={"status": "complete"})
Conclusion
NoReverseMatch errors occur when you are trying to get the URL from its name.
This error often occurs in templates, when you are trying to add a link to another page, or in views.py when you want to redirect a request to another view.
In both cases, it can be as simple as checking the name against urls.py. If the name matches, then check if the correct number of arguments have been supplied. Providing too many or too few arguments will trigger the error.
If that still hasn’t fixed the issue, then check that the URLs of you app have been included in your site’s main urls.py (the one in the same folder as settings.py). If the urls.py belonging to an app hasn’t been included, then Django won’t be able to find it.
Understand More
If you are new to Django, then you may find some examples helpful.
This article from my To Do list tutorial goes through setting up URLs for the first time.
This article from the same tutorial series, gives an example of how to implement URLs with multiple arguments.
Начал изучать Django. Установил, настроил, увидел «It works».
Операционка Debian. Python 2.7.5, Django 1.5.4.
Проект лежит в подкаталоге /app каталога виртуального хоста /var/www/libretag. Стартовая страница открывается по URL http://local-libretag.ru.
Пытаюсь открыть админку. Для этого сделал следующие настройки:
В файле settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/var/www/libretag/data/db/blog.db',
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
...
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
)
В файле urls.py:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'app.views.home', name='home'),
# url(r'^app/', include('app.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
В каталоге /app дал команду:
./manage.py startapp blog
В файле /blog/models.py прописал:
from django.db import models
from django.contrib import admin
class BlogPost(models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
timestamp = models.DateTimeField()
admin.site.register(BlogPost)
В завершение дал команду:
Пытаюсь войти в админку по URL:
http://local-libretag.ru/admin
Но в ответ вижу все ту же страницу «It works».
Вопрос. Что где еще надо крутануть чтобы войти в админку?
Introduction
This is an article to discuss about how to solve an error with the error exist in one of the django framework script. It shows upon executing the virtual webserver to display and execute the django application. The following is the command execution for showing the django application via virtual webserver :
user@hostname:~/python/my-django/users$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 30, 2019 - 20:47:50 Django version 2.2.3, using settings 'users.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
Finding the proper solution
The location of the above command execution is in the root folder or root directory of django project. Inside the project folder, there is another folder for containing the application script. Inside that folder, there is a script responsible for defining the route access page of the django application. The file name of that script is ‘urls.py’. Apparently, after editing the files, there is an error . The error is in the following output :
File "/home/user/python/my-django/users/users_list/urls.py", line 5, in <module> path('',views.home, name="home"), NameError: name 'views' is not defined
The cause of the error is in the following line of the script with the name ‘urls.py’ exist in the application folder :
path('',include(app.urls))
Below is the full and the complete content of the ‘urls.py’ inside the application folder :
from django.contrib import admin
from django.urls import path
from users_list import views
urlpatterns = [
path('',views.home, name="home"),
path('delete/',views.delete, name="delete"),
]
Actually, there is nothing wrong with the line as in the above urls.py script. Turns out, the main culprit is in the urls.py in the project folder. The actual mistakes is in the way for including the ‘urls.py’ file of the application inside the ‘urls.py’ of the project. The following snippet code from the ‘urls.py’ project folder is the wrong one :
path('',include(app.urls))
I write it as path(”,include(app.urls)) and it should be using ”. It is because it doesn’t have ”. It is because i don’t import views first it should be from app import views. So, the correction to solve the error above is just changing the line above in the ‘urls.py’ of the project folder into the following line :
path('',include('app.urls'))
The above script is just trying to include the ‘urls.py’ of the application into the ‘urls.py’ of the project. So whenever there is an attempt to access the url of the application, django can recognizes the pattern. But since the syntax for including the ‘urls.py’ of the application is wrong, the error occurs as it shows in the beginning part of this article. The discussion for solving the error also exist in the following link. For a better understanding of the structure of the project and also the application of the django script, the following is the tree structure of the directories :
user@hostname:~/python/my-django$ tree
.
└── users
├── db.sqlite3
...
├── manage.py
...
├── users
...
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── users_list
├── admin.py
├── apps.py
├── forms.py
├── __init__.py
├── migrations
│ ├── 0001_initial.py
│ ├── __init__.py
│ └── __pycache__
│ ├── 0001_initial.cpython-36.pyc
│ └── __init__.cpython-36.pyc
├── models.py
...
├── templates
│ ├── base.html
│ ├── edit.html
│ └── home.html
├── tests.py
├── urls.py
└── views.py
23 directories, 78 files
user@hostname:~/python/my-django$
The project folder is the ‘users’ folder and the application folder is the ‘users_list’ folder.

