django rest framework DefaultRouter error - django

I wrote a program to learn django rest framework, but the program I wrote is not executed correctly. I have been looking for it for a long time. I can't find the error. I need someone to help me check the problem from another perspective. Thank you.
models.py
from django.db import models
class Subsystem(models.Model):
name = models.CharField(max_length=36)
class Menu(models.Model):
subsystem = models.ForeignKey(Subsystem, on_delete=models.CASCADE)
name = models.CharField(max_length=36)
serializers.py
from rest_framework.serializers import ModelSerializer
from subsystem.models import Subsystem, Menu
class SubsystemSerializer(ModelSerializer):
class Meta:
model = Subsystem
fields = ('name', )
class MenuSerializer(ModelSerializer):
class Meta:
model = Menu
fields = ('name', 'subsystem')
views.py
from rest_framework.viewsets import ModelViewSet
from subsystem.models import Subsystem, Menu
from subsystem.api.serializers import SubsystemSerializer, MenuSerializer
class SubsystemViewSet(ModelViewSet):
queryset = Subsystem.objects.all()
serializer_class = SubsystemSerializer(queryset)
class MenuViewSet(ModelViewSet):
queryset = Menu.objects.all()
serializer_class = MenuSerializer
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from subsystem.api.views import SubsystemViewSet
router = DefaultRouter()
router.registry(r'subsystems', SubsystemViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
I started trying to run python manage.py runserver but it can't run
error:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x06125FA8>
Traceback (most recent call last):
File "D:\env\python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "D:\env\python\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
self.check(display_num_errors=True)
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "D:\env\python\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "D:\env\python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\sc\oa\oaapi\oaapi\urls.py", line 18, in <module>
router.registry(r'subsystems', SubsystemViewSet)
TypeError: 'list' object is not callable
I modified views.py
class SubsystemViewSet(ModelViewSet):
queryset = Subsystem.objects.all()
serializer_class = SubsystemSerializer
But the error still exists
detail:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x065F5FA8>
Traceback (most recent call last):
File "D:\env\python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "D:\env\python\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
self.check(display_num_errors=True)
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "D:\env\python\lib\site-packages\django\core\management\base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "D:\env\python\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\env\python\lib\site-packages\django\utils\functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\env\python\lib\site-packages\django\urls\resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "D:\env\python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\sc\oa\oaapi\oaapi\urls.py", line 18, in <module>
router.registry(r'subsystems', SubsystemViewSet)
TypeError: 'list' object is not callable

ViewSet's serializer_class should be class itself, not it's instance. You should use serializer_class = SubsystemSerializer instead of serializer_class = SubsystemSerializer(queryset).Rewrite SubsystemViewSet to this:
class SubsystemViewSet(ModelViewSet):
queryset = Subsystem.objects.all()
serializer_class = SubsystemSerializer
Also it should be register instead of registry:
router.register(r'subsystems', SubsystemViewSet)
You can find example of routers usage here.

Related

Return just the last object in Django REST Framework

I'm new to asking on StackOverflow and to Django so I'm sorry if I made any mistakes.
So far, I have a basic API with Django and REST Framework. I want to return just the last object that was added to the database, which could be done with the highest ID.
This is the models.py:
from django.db import models
class Humidity(models.Model):
value = models.FloatField()
class Temperature(models.Model):
value = models.FloatField()
isFarenheit = models.BooleanField()
I don't have any time fields, but I can add them if necessary.
This is the serializers.py:
class HumiditySerializer(serializers.ModelSerializer):
class Meta:
model = Humidity
fields = ('id', 'value')
class TemperatureSerializer(serializers.ModelSerializer):
class Meta:
model = Temperature
fields = ('id', 'value', 'isFarenheit')
And this is the views.py:
from django.shortcuts import render
from rest_framework import viewsets, permissions
from .models import Humidity, Temperature
from .serializers import HumiditySerializer, TemperatureSerializer
class HumidityView(viewsets.ModelViewSet):
queryset = Humidity.objects.order_by('-id')[0]
serializer_class = HumiditySerializer
class TemperatureView(viewsets.ModelViewSet):
queryset = Temperature.objects.order_by('-id')[0]
serializer_class = TemperatureSerializer
This is the traceback of the error:
Traceback (most recent call last):
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 398, in check
for pattern in self.url_patterns:
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
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 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\iotSensors\urls.py", line 21, in <module>
path('', include('api.urls')),
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module
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 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\usuario\Desktop\Subcarpetas\iot-sensors\iot-sensors-backend\iot-sensors-backend\iotSensors\api\urls.py", line 6, in <module>
router.register('humidity', views.HumidityView)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 75, in register
basename = self.get_default_basename(viewset)
File "C:\Users\usuario\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\routers.py", line 162, in get_default_basename
return queryset.model._meta.object_name.lower()
AttributeError: 'Humidity' object has no attribute 'model'
This error is only thrown when I change in the views.py from Humidity.objects.all() to Humidity.objects.order_by('-id')[0] and the same with temperature.
How do I return the last object saved?
Since you don't have time or date fields in your model, you may retrieve the latest object only through id.
Humidity.objects.all().order_by('-id')[:1]
-id retrieves the objects in the reverse order.
Since QueryDict object of django is lazily loaded, this will only retrieve the latest value.
You can use the last function to retrieve the latest object
Humidity.objects.all().latest()
or just retrieve the object with the latest id by
Humidity.objects.latest('id')
# To get last object or record
Humidity.objects.last()

How to fix 'Specifying a namespace in include() without providing an app_name '

I am facing with the problem of setting the app_name attribute in the included module.
Despite the fact that I have seen similar answers on how to fix it, I did not find something working for me.
Here is my urls.py
from django.conf.urls import url,include
from django.contrib import admin
from intranet import views,forms
from django.contrib.auth import views as auth_views
from django.conf import settings
from rest_framework import routers
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import reverse
router = routers.DefaultRouter()
router.register(r'pharmakeia', views.PharmakeiaViewSet,base_name='pharmakeia')
router.register(r'doctors', views.DoctorsViewSet,base_name='doctors')
router.register(r'new-pharmakeia', views.VriskoViewSet,base_name='new-pharmakeia')
router.register(r'new-all-pharmakeia', views.VriskoAllViewSet,base_name='new-all-pharmakeia')
views.json_data,base_name='test_pharmakeia')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest/', include(router.urls, namespace='rest')),
url(r'^api-auth/', include(rest_framework.urls, namespace='rest_framework')),
Then I changed the script:
I tried to declare an app_name variable
app_name="intranet"
and then I tried to fix the urls containing the include function
url(r'^rest/', include((router.urls,app_name), namespace='rest')),
url(r'^api-auth/', include(('rest_framework.urls',app_name), namespace='rest_framework')),
I face a new problem
"ModuleNotFoundError: No module named 'router' despite the fact that I have already defined rooter**
Here is my output from command line
self._target(*self._args, **self._kwargs)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 584, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 577, in urlconf_module
return import_module(self.urlconf_name)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/importlib/__init__.py", line 127, in import_module
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 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/www/wwwroot/geolocator/geolocator/urls.py", line 40, in <module>
url(r'^rest/', include(router.urls, namespace='rest')),
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/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.
^C(geolocator_venv) [root#76 geolocator]# clear
(geolocator_venv) [root#76 geolocator]# python manage.py runserver 76.neurosynthesis.com:19999
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/root/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/root/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 584, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 577, in urlconf_module
return import_module(self.urlconf_name)
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/importlib/__init__.py", line 127, in import_module
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 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/www/wwwroot/geolocator/geolocator/urls.py", line 40, in <module>
url(r'^rest/', include(router.urls, namespace='rest')),
File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/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.
Any idea how to fix this?

ImportError: cannot import name 'URLPattern'

I am using django 1.11 and django rest version 3.
and i used drf-nested routers . for makin path like /abc/{id}/xyz/where abc and xyz are two views from AbcViewSet and XyzViewSet.
urls.py
from rest_framework_nested import routers
router = routers.SimpleRouter()
router.register(r'abc',AbcViewset)
abc_router = routers.NestedSimpleRouter(router,r'abc', lookup='abc')
abc_router.register(r'xyz', XyzViewset, base_name='abc-xyz')
urlpatterns = [
url(r'', include(router.urls)),
]
And I got the following traceback. I dont know what is happening with the code and what the error exactly is?
Performing system checks...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fb79f505a60>
Traceback (most recent call last):
File "/home/johan/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/home/johan/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "/home//.local/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "/home/johan/.local/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "/home/johan/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/johan/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "/home/johan/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/home/johan/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "/home/johan/.local/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/johan/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/johan/.local/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/johan/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/johan/Documents/Abc/backend/abc/urls.py", line 24, in <module>
from rest_framework.documentation import include_docs_urls
File "/home/johan/.local/lib/python3.6/site-packages/rest_framework/documentation.py", line 6, in <module>
from rest_framework.schemas import SchemaGenerator, get_schema_view
File "/home/johan/.local/lib/python3.6/site-packages/rest_framework/schemas/__init__.py", line 25, in <module>
from .generators import SchemaGenerator
File "/home/johan/.local/lib/python3.6/site-packages/rest_framework/schemas/generators.py", line 18, in <module>
from rest_framework.compat import (
ImportError: cannot import name 'URLPattern'
How can this error be resolved?

NameError: account not defined

I'm trying to create a simple registration form using django1.11.5
I created a project called mysite using the command:
django-admin.py startproject mysite .
And I have created an app called account using the code:
python manage.py startapp account
In the urls.py file of the folder mysite I specified the urlto be accessed as follows:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^account/',include(account.urls)),
url(r'^admin/', admin.site.urls),
]
However when I'm trying to migrate or runserver I'm getting the following error.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000273BFBDFC80>
Traceback (most recent call last):
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\management\base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\management\base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\urls\resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Welcome\django\myvenv\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Welcome\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\Welcome\django\mysite\urls.py", line 19, in <module>
url(r'^account/',include(account.urls)),
NameError: name 'account' is not defined
So can someone please help. I'm new at this
When you 'include' urls, the reference to the app containing the urls should be a string like so:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
...
url(r'^account/', include('account.urls')),
...
]
You are trying to import the actual app, but that is not necessary in this case.
Does that make sense?

approaching attribute in django auth.user model extension

#models.py
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
birthday = models.DateField(blank=True, null=True)
I extended the django.contrib.auth.views.models.User with additional infomations such as birthday etc.
The problem is that I can't access birthday with request.user.profile in the views.py.
I had to use extra widget to make the app more intuitive.
I did it like this :
#forms.py
class ProfileEditForm(forms.ModelForm):
birthday = forms.DateField(widget=extras.SelectDateWidget)
class Meta:
model = Profile
fields = ('photo', 'phone_num', 'nationality', 'gender')
#views.py
#login_required
def edit(request):
if request.method == 'POST':
user_form = UserEditForm(instance = request.user,
data = request.POST)
profile_form = ProfileEditForm(instance = request.user.profile,
data = request.POST,
files = request.FILES)
if user_form.is_valid() and profile_form.is_valid():
request.user.profile.birthday = user_form.cleaned_data['birthday']
user_form.save()
profile_form.save()
else:
user_form = UserEditForm(instance=request.user)
profile_form = ProfileEditForm(
instance = request.user.profile
)
return render(request,
'views/edit_profile.html',
{'user_form' : user_form,
'profile_form' : profile_form})
The full traceback:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fac3cbfa488>
Traceback (most recent call last):
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/bravepeach/urls.py", line 23, in <module>
url(r'', include('webapp.urls')),
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/conf/urls/__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/webapp/urls.py", line 2, in <module>
from . import views
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/webapp/views.py", line 4, in <module>
from .forms import UserRegistrationForm, UserEditForm, ProfileEditForm
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/webapp/forms.py", line 37, in <module>
class UserEditForm(forms.ModelForm):
File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/forms/models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (birthday) specified for User
As #Alasdair mentioned, you need to correct your UserEditForm class. Coming back to custom widget you can do
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('photo', 'phone_num', 'nationality', 'gender', 'birthday')
widgets = {
'birthday': extras.SelectDateWidget,
}