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

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.

Related

ModuleNotFoundError: No module named 'router'

Hi i am getting this error please help me.
i am new on this field and i am getting this error.
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'first',
]
my views.py
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .serializers import MovieSerializer,RatingSerializers
from .models import Movie,Rating
# Create your views here.
class MovieViewSet(ModelViewSet):
queryset=Movie.objects.all()
serializer_class=(MovieSerializer,)
class RatingViewSet(ModelViewSet):
queryset=Rating.objects.all()
serializer_class=(RatingSerializers,)
my main urls.py is
"""rest_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.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,include
urlpatterns = [
path('admin/', admin.site.urls),
path('my_apis',include('first.urls')),
]
and serializers.py
from rest_framework import serializers
from .models import Movie,Rating
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model= Movie
fields=['title','description']
class RatingSerializers(serializers.ModelSerializer):
class meta:
model=Rating
fields='__all__'
models.py is
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator,MaxValueValidator
# Create your models here.
class Movie(models.Model):
title=models.CharField(max_length=20)
description =models.TextField(max_length=500)
def __str__(self):
return self.title
class Rating(models.Model):
movie=models.ForeignKey(Movie,on_delete=models.CASCADE)
user=models.ForeignKey(User,on_delete=models.CASCADE)
rating=models.PositiveIntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
class Meta:
unique_together=(('user','movie'))
index_together=(('user','movie'))
my urls.py (application)
from django.urls import path
from django.conf.urls import include
from rest_framework import routers
from .views import ModelViewSet,RatingViewSet
router=routers.DefaultRouter()
router.register('movies',ModelViewSet,basename='Movie')
router.register('rating',RatingViewSet,basename='Rating')
app_name='first'
urlpatterns = [
path('',include('router.urls')),
]
i am following a video tutorial
and getting that error
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'router'
please help me
ignore that this text is to avoid "it's look like post is mostly code,please add something "
urlpatterns = [
path('',include('router.urls')),
]
should be:
urlpatterns = router.urls
The include expression goes looking for a router module.
Use
path('', include(router.urls))
without quotes

ModuleNotFoundError: No module named 'employee.urls'

While I'm trying to add a urls configuration in my urls.py file, I'm getting an error like ModuleNotFoundError: No module named 'employee.urls' and OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''
urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('employee/',include("employee.urls"))
]
directory and file path
It's a convention to name all your url config files urls.py not url_<appname> unless you have a very special use-case.
But in either case, you must import the url file after your filename. So if you want to keep the filename as is, try this:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('employee/',include("employee.urls_employee"))

when i startapp "article", and python manage.py runserver, and I do not know why "module 'article.admin' has no attribute 'site" this error happen?

I start up an app named "article" but and configure an import like this: from article import * in the setting configure file, then when I run python manage.py runserver the error ocuur like this AttributeError: module 'article.admin' has no attribute 'site', when I comments from article import * with #, it will work on well, I do not know how from article import * raise the problem.
from article import *
atterns = [
path('admin/', admin.site.urls),
url(r'^article/',include('article.urls',namespace='article')),
]
The output:
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "D:\pythonTestfolder\xuegod\blogtest\blogtest\urls.py", line 25, in <module>
path('admin/', admin.site.urls),
AttributeError: module 'article.admin' has no attribute 'site'
You don't need to import from your article app here
especially all of its contents with *
include method will work with a string of app_name and it's urls.py file , as you have wright corectly
and after that if it is a newer version of django project you are using , try not to use
url method because it is going to be deprecated use re_path() instead , if you want to check for regex urls:
from django.urls import path, re_path, include
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^article/',include('article.urls',namespace='article')),
]

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.

Specifying a namespace in include() without providing an app_name

models.py
from django.conf.urls import include, url
app_name = "Review"
urlpatterns = [
url(r'^books/', include("Review.urls", namespace='reviews')),
]
Review\urls.py
from django.conf.urls import include, url
from django.contrib import admin
from .views import (
ReviewUpdate,
ReviewDelete,
)
urlpatterns = [
url(r'^reviews/(?P<pk>\d+)/edit/$', ReviewUpdate.as_view(), name='review_update'),
url(r'^reviews/(?P<pk>\d+)/delete/$', ReviewDelete.as_view(), name='review_delete'),
]
I am providing app_name before my urlpatterns. But it's giving me error while running my code. The errors are given below:
File "E:\workspace\python\web\Book_Review_App\Book\urls.py", line 13, in <module>
url(r'^books/', include("Review.urls", namespace='reviews')),
File "E:\workspace\python\web\Book_Review_App\venv\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.
Please help.
The app_name needs to be set in your app's urls.py not the main urls.py.
In review.urls.py add the following,
from django.conf.urls import include, url
from django.contrib import admin
from .views import ( ReviewUpdate, ReviewDelete, )
app_name = 'Review'
urlpatterns = [
url(r'^reviews/(?P<pk>\d+)/edit/$', ReviewUpdate.as_view(), name='review_update'),
url(r'^reviews/(?P<pk>\d+)/delete/$', ReviewDelete.as_view(), name='review_delete'),
]
and remove the app_name from the main urls
EDIT: for the admin issue that the op mentioned in the comments,
in the main urls.py
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
You need to define app_name in urls.py and pass urlconf_module in tuple . Here is example
app_name = "example"
from typing import NamedTuple
class NamedURL(NamedTuple):
urlconf_module: None
app_name: None
daily_urls = NamedURL(<your custom urls in list>, "example")
urlpatterns = [
...
re_path(r'^daily/', include(daily_urls, namespace='daily')),
]