Empty static prefix not permitted - django

I´m working with a tutorial on udemy. I´m at the part about setting up static files .
https://www.udemy.com/probar-django-construir-una-aplicacion-web-en-python/learn/v4/overview that´s the link.
on video 22 it shows how to configure static files.
I configured everything as in the tutorial. this is a little further than just typing code from docs, colins, upper case 'POST'. Again, my code is exactly as in the tutorial.
any comment about how to read the error message and only look at the useful
stuff with be of good help as well.
the video is in Spanish but, the pages and the code are in English.
can anybody tell me from looking at the error message or taking a look at
the tutorial to see what could be wrong.
Unhandled exception in thread started by <function wrapper at 0x034034B0>
Traceback (most recent call last):
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\core\management\commands\runserver.py", line 121, in
inner_run
self.check(display_num_errors=True)
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\core\management\base.py", line 385, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\core\management\base.py", line 372, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\core\checks\urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\core\checks\urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\urls\resolvers.py", line 310, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns",
self.urlconf_module)
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\urls\resolvers.py", line 303, in urlconf_module
return import_module(self.urlconf_name)
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\migel\Desktop\pd110\src\pd110\urls.py", line 32, in
<module>
urlpatterns + static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
File "C:\Users\migel\Desktop\pd110\lib\site-
packages\django\conf\urls\static.py", line 24, in static
raise ImproperlyConfigured("Empty static prefix not permitted")
django.core.exceptions.ImproperlyConfigured: Empty static prefix not
permitted
my url.py
"""pd110 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please
see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from boletin import views
#from boletin.views inicio
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^contact/$', views.contact, name='contact'),
url(r'^$', views.inicio, name='inicio'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
STATIC_URL = '/media/'
#/static/images/img1.jpg
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static_pro", "static"),
#'/var/www/static/',
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_env",
"static_root")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_env",
"media_root")

If you go to the source and glance at the function raising that error, it starts:
# django/conf/urls/static.py
def static(prefix, view=serve, **kwargs):
...
if not prefix:
raise ImproperlyConfigured("Empty static prefix not permitted")
So at some point in your code, you're passing a false-y (like an empty-string) as the first argument prefix. Looking at your urls.py, you have
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I would guess that either the STATIC_URL or MEDIA_URL is empty. It looks like you declared former, so probably the latter.

url.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
settings.py
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
#/static/imagenes/img1.jpg
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static_pro", "static"),
#'/var/www/static/',
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_env",
"static_root")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_env",
"media_root")

Hye!!! It seems like root media folder is not created, first create superuser and create the job,then the folder will be created automatically.
Then add media url "
+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)".
Hope! will work fine.

I had the same problem so I read through the static.py file and it requires a prefix... so I did something like this:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
And I was up and running again with no errors...

Related

Error Specifying a namespace in include() without providing an app_name

When I tried my project runserver, this error
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\apple\Desktop\web3start\tests\urls.py", line 8, in <module>
url(r'^', include('web3auth.urls', namespace='web3auth')),
File "C:\Users\apple\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\conf.py", line 39, in include
'Specifying a namespace in include() without providing an app_name '
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.
came out.
conf.py
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.',
urls.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.conf.urls import url, include
urlpatterns = [
url(r'^', include('web3auth.urls', namespace='web3auth')),
]
What should I do?? I need a specific code directly to write on!
As the error said, inside your web3auth/urls.py you need to set app_name attribute. For example:
# web3auth/urls.py
from django.urls import path
from . import views
app_name = 'web3auth'
urlpatterns = [
...
]
You can checkout the documentation as well.

Django_hosts integration produces 'NoReverseMatch at /en/api/' when attempting to access api

I'm in the process of integrating Django_hosts. I have the front end URLs and the admin URLs successfully integrated and working, but my REST API URLs are still inaccessible due to this error:
'NoReverseMatch at /en/api/'
The error is traced to Django/urls/base.py, but I'm not sure what is triggering it:
Traceback (most recent call last):
File "/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
File "/lib/python3.6/site-packages/django/shortcuts.py", line 148, in resolve_url
return reverse(to, args=args, kwargs=kwargs)
File "/lib/python3.6/site-packages/django/urls/base.py", line 86, in reverse
raise NoReverseMatch("%s is not a registered namespace" % key)
django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace
These are my hosts.py and api_urls.py files:
# hosts.py
host_patterns = patterns(
'',
host(r'www', settings.ROOT_URLCONF, name='www'),
host(r'admin', 'Project.admin_urls', name='admin'),
host(r'api', 'Project.api_urls', name='api'),
)
# api_urls.py
urlpatterns += i18n_patterns (
path('session_security/', include('session_security.urls')),
path('', include('Project.apps.api.urls'), name='api'),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Also, to kill two birds with one stone, when attempting to convert this url:
{% url 'profile' request.user.id %}
to this url:
{% host_url 'profile' host 'www' request.user.id %}
It fails throwing a NoReverseMatch error with no arguments, as if the arguments are ignored.
Any help from someone knowledgeable about this package or either of these issues would be appreciated.
Thanks.
Update
I resolved this error by including admin.site urls within the api_urls.py file:
# api_urls.py
urlpatterns += i18n_patterns (
path('session_security/', include('session_security.urls')),
path('', include('Project.apps.api.urls'), name='api'),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
path('', admin.site.urls, name='admin'), <--This is key, but not sure exactly why.
However, now I've run into something strange, which isn't exactly an error, but effectively acts as one for my use case. The API seems to no longer recognize request.user, so that even if a user is logged in, the API thinks he is AnonymousUser.
*Both API and Admin subdomains not recognizing logged in user. Seems to be something to do with SESSION cookie...

Django sending users to the wrong template location?

I'm working on Python Crash Course Chapter 19, where we are setting up a 'learning log' application. I'm stuck (on page 440) with a template reference error.
I have reworked this section of the book, in addition to taking all of the updates listed here: https://ehmatthes.github.io/pcc/chapter_19/README.html
but seem to keep getting what looks to be a template reference error. I noticed the template is referencing the 'learning_logs' directory when looking for the login.html, which is incorrect -- it should be looking in the 'learning_log' directory.
learning_log\users\urls.py
from django.contrib.auth import views as auth_views
from . import views
app_name = 'users'
urlpatterns = [
# Login page.
path('login/',
auth_views.LoginView.as_view(template_name='users/login.html'),
name='login'),
]
learning_logs\urls.py
"""learning_logs URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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'))
"""
"""Defines URL patterns for learning_logs."""
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# Home page.
path('', views.index, name='index'),
#Show all topics.
path('topics/', views.topics, name='topics'),
#Detail page for a single topic.
path('topics/<int:topic_id>/', views.topic, name='topic'),
#Page for adding a new topic.
path('new_topic/', views.new_topic, name='new_topic'),
#Page for adding a new entry.
path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),
#Page for editing an entry.
path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'),
]
learning_log\urls.py
"""learning_log URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('', include('learning_logs.urls')),
]
Here is the browser error:
TemplateDoesNotExist at /users/login/
users/login.html
Request Method:
GET
Request URL:
http://localhost:8000/users/login/
Django Version:
2.2.1
Exception Type:
TemplateDoesNotExist
Exception Value:
users/login.html
Exception Location:
C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py in select_template, line 47
Python Executable:
C:\Users\kevin\Documents\webapps\11_env\Scripts\python.exe
Python Version:
3.7.3
Python Path:
['C:\\Users\\kevin\\Documents\\webapps',
'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\kevin\\Documents\\webapps\\11_env',
'C:\\Users\\kevin\\Documents\\webapps\\11_env\\lib\\site-packages']
Server time:
Sun, 26 May 2019 22:14:26 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\admin\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\auth\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\learning_logs\templates\users\login.html (Source does not exist)
Here is the server error:
Traceback (most recent call last):
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
response = response.render()
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
self.content = self.rendered_content
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
template = self.resolve_template(self.template_name)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
return select_template(template, using=self.using)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: users/login.html
[26/May/2019 15:12:27] "GET /users/login/ HTTP/1.1" 500 79384
Not Found: /users/
[26/May/2019 15:12:39] "GET /users/ HTTP/1.1" 404 3224
Internal Server Error: /users/login/
Traceback (most recent call last):
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
response = response.render()
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
self.content = self.rendered_content
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
template = self.resolve_template(self.template_name)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
return select_template(template, using=self.using)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: users/login.html
[26/May/2019 15:12:43] "GET /users/login/ HTTP/1.1" 500 79384
Internal Server Error: /users/login/
Traceback (most recent call last):
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
response = response.render()
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
self.content = self.rendered_content
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
template = self.resolve_template(self.template_name)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
return select_template(template, using=self.using)
File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: users/login.html
double check your templates directory in settings and make sure slashes are forward slashes / not \
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',
],
},
},
Are you sure you haven't mistyped anything? I do that heaps and it always messes up my programs. Try checking where you've typed learning_logs or learning_log and see if you need to add or remove an s.
It appears that the book suggests you save the login.html file to the learning_log/users/templates folder, but it should be in the learning_logs folder. Once I moved the templates, that fixed my issue. Thank you both Nurhun and Lumiobyte!

Problem with django-RESTframework-Tutorial

I'm trying to get familiar with django-RESTframeworks, therefore I started the official tutorial, to create a Test-API.
https://www.django-rest-framework.org/tutorial/quickstart/#quickstart
When finally starting the API on my Windows via [CMD] "pyhon manage.py runserver", I get an error code on the command line, which you will see below.
I also want to add, that unfortunately, there is some ambiguity in the descriptions in the tutorial, at least from the viewpoint of a beginner, i.e. it's not always certain whether the corresponding code in the tutorial
needs to be added in a module or replace all or part of the code in the modules.
Therefore, I tried implementing the directions of the tutorial in various ways, always with the same end result.
I'm running the code in a virtual env, where i've installed Django 1.11., so there shouldn't be an issue with different Django versions.
C:\Users\Rolimar\projects\djREST_tut>workon djresttut
(djresttut) C:\Users\Rolimar\projects\djREST_tut>python manage.py runserver
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x0000000004CBF978>
Traceback (most recent call last):
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\management\base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\management\base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\urls\resolvers.py", line 256, in check
for pattern in self.url_patterns:
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\urls\resolvers.py", line 407, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Rolima\Envs\djresttut\lib\site-packages\django\urls\resolvers.py", line 400, in urlconf_module
return import_module(self.urlconf_name)
File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\Rolima\projects\djREST_tut\tutorial\urls.py", line 19, in <module>
from django.urls import include, path
ImportError: cannot import name include
And here my codes, I tried to copy from the tutorial:
"serializers.py"
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
"views.py"
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
"urls.py"
"""tutorial URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
in "settings.py", where I added 'rest_framework'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles'
'rest_framework',
]
and where I also added the following code in the very end:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
Most probably you are using django<2.0 but following tutorials which are written in django>2.0. From django 2.0, include has been moved to django.urls, before it resided in django.conf.urls(changelog reference). So you need to update your urls.py like this:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from tutorial.quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
You can't use path as well, because it was introduced in django 2 as well.
Or you can move to django>2.0, but in that case you have to remove from django.conf.urls import url and use from django.urls import url.

how to set path for django admin to make javascript and css of work on Windows XP and development server

I try to execute django (1.4) tutorial admin on windows. But there is not access to css and javascript.
I set in setty.py:
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = 'C:/Python27/Lib/site-packages/django/contrib/admin/'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
My urils:
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'^$', '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(admin.site.urls)),
)
It still doesn't work. Could you please tell how to solve this issue and what's the best way to solve it?
My proect is in c:\django-projects\mysite.
When I execute admin http://127.0.0.1:8000/admin/polls/poll/1/ I can see error of development server:
Traceback (most recent call last):
File "C:\Python27\lib\wsgiref\handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", l
ine 68, in __call__
return super(StaticFilesHandler, self).__call__(environ, start_response)
File "C:\Python27\lib\site-packages\django\core\handlers\wsgi.py", line 241, i
n __call__
response = self.get_response(request)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", l
ine 58, in get_response
return self.serve(request)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", l
ine 51, in serve
return serve(request, self.file_path(request.path), insecure=True)
File "C:\Python27\lib\site-packages\django\contrib\staticfiles\views.py", line
41, in serve
return static.serve(request, path, document_root=document_root, **kwargs)
File "C:\Python27\lib\site-packages\django\views\static.py", line 57, in serve
mimetype, encoding = mimetypes.guess_type(fullpath)
File "C:\Python27\lib\mimetypes.py", line 294, in guess_type
init()
File "C:\Python27\lib\mimetypes.py", line 355, in init
db.read_windows_registry()
File "C:\Python27\lib\mimetypes.py", line 259, in read_windows_registry
for ctype in enum_types(mimedb):
File "C:\Python27\lib\mimetypes.py", line 249, in enum_types
ctype = ctype.encode(default_encoding) # omit in 3.x!
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal
Here is from settings.py:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'polls'
)
In firebug I get 500 http return code for css and js files and path seems strange to me.
For example:
http://127.0.0.1:8000/static/admin/css/base.css
I tried to added in settings.py:
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'C:/Python27/Lib/site-packages/django/contrib/admin/static/admin', //here css and js and img folders for for admin
)
And changing urls.py to this one:
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# 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(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
But it still doesn't work.
Django documenation say here: https://docs.djangoproject.com/en/1.4/howto/deployment/wsgi/modwsgi/#serving-the-admin-files that: "The admin files live in (django/contrib/admin/static/admin) of the Django distribution.". But it still doesn't wok.