single file Django, DRF project - python

I am trying to bastardise Django and Django REST Framework into a single module so see if it can work. So far, I have the following code:
###############################################################################
# SETTINGS
###############################################################################
import os
from django.apps import apps
from django.conf import settings
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if not settings.configured:
settings.configure(
DEBUG=True,
SECRET_KEY='thisisthesecretkey',
ROOT_URLCONF=__name__,
STATIC_URL='/static/',
STATICFILES_DIRS=(
os.path.join(BASE_DIR, "static"),
),
MIGRATION_MODULES = {'__main__': 'migrations'},
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
),
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'tinydb',
}
},
INSTALLED_APPS = (
'__main__',
'rest_framework',
'django.contrib.staticfiles',
),
)
apps.populate(settings.INSTALLED_APPS)
###############################################################################
# MODELS
###############################################################################
from django.db import models
class Book(models.Model):
ISBN = models.AutoField(primary_key=True)
author = models.CharField(max_length=100)
title = models.CharField(max_length=200)
description = models.CharField(max_length=500)
###############################################################################
# SERIALIZERS
###############################################################################
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
###############################################################################
# VIEWS
###############################################################################
class BooksView():
queryset = Book.objects.all()
serializer_class = BookSerializer
###############################################################################
# URLCONF
###############################################################################
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'books', BooksView)
urlpatterns = (
url(r'^$', include(router.urls)),
)
###############################################################################
# MANAGE
###############################################################################
import sys
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Right now, the server runs and I see the API browser. However, when I try to create an object, I get the following trace:
>>> from __main__ import Book
>>> Book.objects.create(author='a1', title='t1', description='d1')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/query.py", line 348, in create
obj.save(force_insert=True, using=self.db)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/base.py", line 734, in save
force_update=force_update, update_fields=update_fields)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/base.py", line 762, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/base.py", line 846, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/base.py", line 885, in _do_insert
using=using, raw=raw)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/query.py", line 920, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 974, in execute_sql
cursor.execute(sql, params)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/utils/six.py", line 658, in reraise
raise value.with_traceback(tb)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: __main___book
makemigrations returns:
lwm$ python api.py makemigrations
No changes detected
I can run a migration:
lwm$ python api.py migrate
Operations to perform:
Synchronize unmigrated apps: __main__, staticfiles, rest_framework
Apply all migrations: (none)
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
No migrations to apply.
So. I think, since I don't have my Book model in a seperate app, there is no database table being created for it. Other than manually creating the tables, for example, using the db_table Meta field, I still wanted to get all the goodness of the ORM doing things for me.
Any ideas?

Try removing __main__ from the list of installed apps. Unless you actually have an app named __main__ (which you probably shouldn't, given that double underscores means something in python), that's not supposed to be there.

This is a slightly different code, but it works. I'm using Python 3.6 \o/ and Django 1.10. Keep in mind, if you're currently in a folder named bar and if you save this script as foo.py, you should make your migrations with this command: python foo.py makemigrations bar.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
""" greetings """
import os
import sys
from django.conf import settings
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# use base_dir as import root
sys.path[0] = os.path.dirname(BASE_DIR)
# the current folder name will also be our app
APP_LABEL = os.path.basename(BASE_DIR)
settings.configure(
DEBUG=os.environ.get('DEBUG', 'on') == 'on',
SECRET_KEY=os.environ.get('SECRET_KEY', os.urandom(32)),
ALLOWED_HOSTS=os.environ.get('ALLOWED_HOSTS', 'localhost').split(','),
ROOT_URLCONF=__name__,
MIDDLEWARE=[
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
],
INSTALLED_APPS=[
APP_LABEL,
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
],
STATIC_URL='/static/',
STATICFILES_DIRS=[
os.path.join(BASE_DIR, "static"),
],
STATIC_ROOT=os.path.join(BASE_DIR, "static_root"),
MEDIA_ROOT=os.path.join(BASE_DIR, "media"),
MEDIA_URL='/media/',
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates"),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
],
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
},
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAdminUser',
],
'PAGE_SIZE': 10
}
)
import django
django.setup() # responsible for populating the application registry.
from django.db import models
from django.contrib import admin
from django.db import models
# Create your models here.
class Author(models.Model):
name = models.CharField(max_length=200)
class Meta:
app_label = APP_LABEL
class Book(models.Model):
author = models.ForeignKey(Author, related_name='books')
title = models.CharField(max_length=400)
class Meta:
app_label = APP_LABEL
admin.site.register(Book)
admin.site.register(Author)
admin.autodiscover()
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
from rest_framework import viewsets
class BooksViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
from django.conf.urls import url, include
from rest_framework import routers
from django.http import HttpResponse
from django.contrib import admin
router = routers.DefaultRouter()
router.register(r'books', BooksViewSet)
def index(request):
""" index """
return HttpResponse("Hello")
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', index, name='homepage'),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls',\
namespace='rest_framework'))
]
from django.core.wsgi import get_wsgi_application
def return_application():
return get_wsgi_application()
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
else:
return_application()
I hope it helps.

Related

ImportError: cannot import name 'passUser' from 'userUpdate.models'

Hello everyone I am trying to build a website with django that gets info from the form and makes api calls using those parameters.
I am very newby on django and I build a model for this but i cannot import this model it says
-------->>>>>>python manage.py runserver
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
autoreload.raise_last_exception()
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception
raise _exception[1]
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\apps\config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\berat.berkol\anaconda3\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\berat.berkol\SystemConsole\userUpdate\models.py", line 3, in <module>
from . import views
File "C:\Users\berat.berkol\SystemConsole\userUpdate\views.py", line 13, in <module>
from userUpdate.forms import userPassResetForm
File "C:\Users\berat.berkol\SystemConsole\userUpdate\forms.py", line 2, in <module>
from userUpdate.models import passUser
ImportError: cannot import name 'passUser' from 'userUpdate.models' (C:\Users\berat.berkol\SystemConsole\userUpdate\models.py)
on Windows cmd. I tried this without making a model but if I don't use models i can't render the form to the template.
Here is my home.html
<div class="u-form u-form-1">
<form action="{% url 'userPassreset' %}" method="post" class="u-clearfix u-form-spacing-15 u-form-vertical u-inner-form" style="padding: 15px;" source="custom" name="send">
{% csrf_token %}
<div class="u-form-group u-form-name u-form-group-1">
{{form.as_p}}
{{form.username}}
</div>
<div class="u-align-right u-form-group u-form-submit u-form-group-6">
<input type="submit" value="Sadece Mesaj Gönder" class="u-active-white u-border-0 u-border-radius-10 u-btn u-btn-round u-btn-submit u-button-style u-palette-2-base u-btn-1" name="sendmessage">
</div>
</form>
</div>
urls.py (App)
from django.urls import path, re_path
from django.contrib.auth.views import LoginView
from . import views
app_name='userUpdate'
urlpatterns = [
path('', views.userUpdate, name='home'),
path('login/',
LoginView.as_view(
template_name='login.html'),
name="login"),
path('userPassreset',views.passResetView.as_view(),name='userPassreset'),]
urls.py (Project)
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from django.contrib.auth.views import LoginView
from django.views.generic.base import TemplateView
app_name='userUpdate'
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',include('django.contrib.auth.urls')),
path('', TemplateView.as_view(template_name='home.html'), name='home'),]
models.py
from django.db import models
from django.contrib.auth.models import User
from . import views
class passUser(models.Model):
username = models.CharField(blank=False,max_length=100)
password = models.CharField(blank=False,max_length=100)
number = models.CharField(blank=False,max_length=100)
message = models.CharField(blank=True,max_length=300)
class Meta:
verbose_name = "passUser"
forms.py
from django import forms
from userUpdate.models import passUser
class userPassResetForm(forms.ModelForm):
class Meta:
model = passUser
fields = "__all__"
views.py
from django.shortcuts import render
from datetime import timedelta
from django.utils import timezone
from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.urls import reverse
import requests
from userUpdate.forms import userPassResetForm
from django.views import View
#csrf_protect
class passResetView(View):
def get(self,request):
form=userPassResetForm()
return render('home.html')
def post(self,request):
passResetuser=self.model.objects.get(pk=2)
form=userPassResetForm(request.POST,instance=passResetuser)
if form.is_valid():
username=form.cleaned_data('username')
password=form.cleaned_data('password')
number=form.cleaned_data('number')
message=form.cleaned_data('message')
context={'form':form}
return render(request,'home.html',context)
settings.py
import os
from django.urls import reverse_lazy
from django.contrib.messages import constants as message_constants
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
reverse_lazy("accounts:list")
LOGIN_URL = reverse_lazy('registration/login')
LOGIN_REDIRECT_URL = reverse_lazy('home')
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
DEBUG = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
ALLOWED_HOSTS = []
# Application definition
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
INSTALLED_APPS = [
'userUpdate.apps.UserupdateConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'SystemConsole.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
"DIRS": [os.path.join(BASE_DIR, "templates")],
'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',
],
},
},
]
WSGI_APPLICATION = 'SystemConsole.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/SystemConsole/static'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
SITE_ID = 1
apps.py
from django.apps import AppConfig
class UserupdateConfig(AppConfig):
name = 'userUpdate'
Thank you for your help for now.
And Here is the directory tree :
It's solved by dropping "from . import views" from models. Thanks to #blondelg in comments

How to solve django error: raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)

I am using Django 3+...
I am trying to render a template of the blog on my page, but I am receiving a error:
Internal Server Error: /postsblog
Traceback (most recent call last):
File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
response = response.render()
File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\template\response.py", line 105, in render
self.content = self.rendered_content
File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\template\response.py", line 81, in rendered_content
template = self.resolve_template(self.template_name)
File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\template\response.py", line 63, in resolve_template
return select_template(template, using=self.using)
File "D:\Projetos Dev\gpprofessional\.venv\lib\site-packages\django\template\loader.py", line 47, in select_template
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: posts/blog.html, posts/post_list.html
[13/May/2020 22:57:09] "GET /postsblog HTTP/1.1" 500 93437
This error occurs when I try to access the blog URL.
I have some apps in my project like app base, app posts, app blog, and app categorias
My directory file to be looks like the image:
My files in app base:
urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('posts', include('posts.urls')),
path('summernote/', include('django_summernote.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.edit import UpdateView
def home(request):
return render(request, 'home.html')
My files in app posts:
urls
from django.urls import path
from . import views
urlpatterns = [
path('blog', views.PostIndex.as_view(), name='post_blog'),
path('categoria/<str:categoria>', views.PostCategoria.as_view(), name='post_categoria'),
path('busca/', views.PostBusca.as_view(), name='post_busca'),
path('post/<int:pk>', views.PostDetalhes.as_view(), name='post_detalhes'),
]
views
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.edit import UpdateView
from .models import Post
class PostIndex(ListView):
model = Post
template_name = 'posts/blog.html'
class PostBusca(PostIndex):
pass
class PostCategoria(PostIndex):
pass
class PostDetalhes(UpdateView):
pass
My file settings in TEMPLATES and INSTALLED_APPS configuration it's looks like:
TEMPLATES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
},
},
]
ISTALLED_APPS
INSTALLED_APPS = [
'posts',
'categorias',
'comentarios',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'collectfast',
'django.contrib.staticfiles',
'base',
'blog',
]
I tried to use the only folder for all templates but had the error. I think that the error to be in the URL base file, but I don't how to solve it. I made some searches on google but without success...
You don't need to add app in front on template name considering template loader goes through templates in all apps, so in your case
template_name = 'blog.html'

django.core.exceptions.ImproperlyConfigured: The included URLconf 'api.urls' does not appear to have any patterns in it

Having a hard time understanding why I am receiving this error. If I just leave the api/user/ path it works fine but when I try to add api/user/date_counter/ path I get this error. Using Django 3. Any help would be appreciated.
Pseudo-graphics like below is based on how maven shows the output of dependency:tree command.
In my experience it has been easy to read and type. It naturally matches tree-like file structure:
Backend
|
+-- api
| |
| +-- urls.py
| |
| +-- settings.py
|
+-- date_counter
| |
| +-- urls.py
|
+-- user
| |
| +-- urls.py
date_counter/urls.py
from django.urls import path
from date_counter import views
app_name = 'date_counter'
urlpatterns = [
path('date_counter/', views.DateCounterViewSet.as_view(), name='date_counter'),
]
date_counter/views.py
from django.shortcuts import render
from date_counter.models import Date_Counter
from date_counter.serializers import DateCounterSerializer
class DateCounterViewSet(viewsets.ModelViewSet):
queryset = Date_Counter.objects.all()
serializer_class = DateCounterSerializer
date_counter/serializers.py
from date_counter.models import Date_Counter
from rest_framework import serializers
class DateCounterSerializer(serializers.ModelSerializer):
class meta:
model = Date_Counter
fields = ['user', 'date', 'count']
date_counter/models.py
from django.db import models
from user.models import User
class Date_Counter(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now=True)
count = models.IntegerField(default=0)
api/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/user/', include('user.urls')),
path('api/user/date_counter/', include('date_counter.urls')),
]
user/urls.py
from django.urls import path
from knox.views import LogoutView
from user import views
app_name = 'user'
urlpatterns = [
path('register/', views.RegisterUserView.as_view(), name='register'),
path('login/', views.LoginUserView.as_view(), name='login'),
path('user/', views.UserView.as_view(), name='user'),
path('logout/', LogoutView.as_view(), name='knox_logout'),
path('registersuperuser/', views.RegisterSuperUserView.as_view(), name='register_super_user'),
path('all/', views.AllUsersView.as_view(), name='all'),
]
api/settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'secret'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'knox',
'user',
'date_counter',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',),
}
ROOT_URLCONF = 'api.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'api.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'user.User'
Stack Trace
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 590, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check
include_deployment_checks=include_deployment_checks,
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in check
for pattern in self.url_patterns:
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/francisco_navarro/.local/share/virtualenvs/pomodoro_tracker-2HYScThJ/lib/python3.6/site-packages/django/urls/resolvers.py", line 597, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'api.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
I think the problem is how you registering your ViewSet to urlpatterns. Try like this:
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('date_counter', views.DateCounterViewSet)
urlpatterns = [
path('', include(router.urls)),
]
More information can be found in documentation.
Found the issue, the date_counter/views.py file was missing an import from django rest framework, from rest_framework import viewsets.

How correctly add permissions to User model of Django?

I am tring to add custom permissions to User model (django.contrib.auth.models).
To __init__.py file of my users app I add:
from django.db.models.signals import pre_migrate
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import Permission
from django.conf import settings
from django.dispatch import receiver
#receiver(pre_migrate, sender=auth_models)
def add_user_permissions(sender, **kwargs):
content_type = ContentType.objects.get_for_model(settings.AUTH_USER_MODEL)
Permission.objects.get_or_create(codename='view_user', name=' Can view users', content_type=content_type)
Permission.objects.get_or_create(codename='change_user_password', name=' Can change user password', content_type=content_type)
settings.py:
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.forms',
'django_select2', # "django-select2" application
'custom_app', # "custom_app" application
'custom_app_2', # "custom_app_2" application
'modeltranslation', # "django-modeltranslation" application
'users', # "users" application
]
ERROR:
Traceback (most recent call last):
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception
six.reraise(*_exception)
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/config.py", line 94, in create
module = import_module(entry)
File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Applications/Projects/web/dashboard.kase.kz/users/__init__.py", line 5, in <module>
from django.contrib.contenttypes.models import ContentType
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 139, in <module>
class ContentType(models.Model):
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config
self.check_apps_ready()
File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Question: How to fix this error?
Finally I found solution from documentation.
1) You need to create empty migration with next command:
python manage.py makemigrations --empty users
users - name of the app
2) Command create 0001_initial.py file where you need to put next code:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
User = apps.get_model('auth', 'User')
Permission = apps.get_model('auth', 'Permission')
ContentType = apps.get_model('contenttypes', 'ContentType')
content_type = ContentType.objects.get_for_model(User)
db_alias = schema_editor.connection.alias
Permission.objects.using(db_alias).bulk_create([
Permission(codename='view_user', name=' Can view users', content_type=content_type),
Permission(codename='change_user_password', name=' Can change user password', content_type=content_type)
])
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.RunPython(forwards_func),
]
Please try adding this code at the top of the init.py file:
import django
django.setup()
copy all code in your init.py to a new created file called signals.py and change your __init__.py to :
default_app_config = 'user.apps.UserConfig'
signals.py
from django.db.models.signals import pre_migrate
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import AuthConfig
from django.contrib.auth.models import Permission
from django.conf import settings
from django.dispatch import receiver
#receiver(pre_migrate, sender=AuthConfig)
def add_user_permissions(sender, **kwargs):
content_type = ContentType.objects.get_for_model(settings.AUTH_USER_MODEL)
Permission.objects.get_or_create(codename='view_user', name=' Can view users', content_type=content_type)
Permission.objects.get_or_create(codename='change_user_password', name=' Can change user password', content_type=content_type)
then in user/apps.py:
from django.apps import AppConfig
class UserConfig(AppConfig):
name = 'user'
verbose_name = 'User'
def ready(self):
import user.signals
your error is occer because __init__.py will call User in models.py,but User model will be register after __init__.py run over,so you need call your signal when your User model is ready.
You want to add some perms related with User so:
class MyUser(User):
class Meta:
permissions = (
("view_user", "view_user"),
("change_user_password", "change_user_password"),
)
and in settings.py
AUTH_USER_MODEL = "user.MyUser"

Django 1.8 LookupError : Model not registered AUTH_USER_MODEL

Django 1.8 and Python 3.4
I'm using a custom User model called UploaderClient in my app called authenticateclients . When I run check or makemigrations or migrate I get a LookupError: Model 'authenticateclients.UploaderClient' not registered. error. Please help.
In settings.py I have defined AUTH_USER_MODEL as authenticateclients.UploaderClient
authenticateclients/models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
# Create your models here.
class UploaderClientManager(BaseUserManager):
def create_user(self, accountname, password=None, **kwargs):
if not accountname:
raise ValueError('Users must have a valid accountname.')
if not kwargs.get('email'):
raise ValueError('Users must have a valid email.')
if not kwargs.get('company_name'):
raise ValueError('Users must have a valid company name.')
account = self.model(
accountname=self.normalize_accountname(accountname),email=kwargs.get('email'), company_name=kwargs.get('company_name')
)
account.set_password(password)
account.save()
return account
def create_superuser(self, accountname, password, **kwargs):
account = self.create_user(accountname, password, **kwargs)
account.is_admin = True
account.save()
return account
class UploaderClient(AbstractBaseUser):
email = models.EmailField()
accountname = models.CharField(max_length=100, unique=True)
company_name = models.CharField(max_length=100)
vuforiadb_name = models.CharField(max_length=100, blank=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UploaderClientManager()
USERNAME_FIELD = 'accountname'
REQUIRED_FIELDS = ['email','company_name']
def __unicode__(self):
return self.accountname
def get_company_name(self):
return self.company_name
def get_vuforiadb_name(self):
return self.vuforiadb_name
settings.py
"""
Django settings for ARPixelSite project.
Generated by 'django-admin startproject' using Django 1.8.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# -*- coding: utf-8 -*-
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
gettext = lambda s: s
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#-$h5gh5%s$70hd=ii55it!+4#a*u8b(c8aqumqkx#*m8%v89l'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'djangocms_admin_style', # for the admin skin. You **must** add 'djangocms_admin_style' in the list **before** 'django.contrib.admin'.
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'cms', # django CMS itself
'treebeard', # utilities for implementing a tree
'menus', # helper for model independent hierarchical website navigation
#'south', # Only needed for Django < 1.7
'sekizai', # for javascript and css management
'djangocms_file',
'djangocms_flash',
'djangocms_googlemap',
'djangocms_inherit',
'djangocms_picture',
'djangocms_teaser',
'djangocms_video',
'djangocms_link',
'djangocms_snippet',
'rest_framework',
'clientupload',
'authenticateclients',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.language.LanguageCookieMiddleware',
)
ROOT_URLCONF = 'ARPixelSite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'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',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'sekizai.context_processors.sekizai',
'cms.context_processors.cms_settings',
],
},
},
]
WSGI_APPLICATION = 'ARPixelSite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ARPixelDB',
'USER': 'djangouser',
'PASSWORD': 'djangouser',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
)
}
"""
TEMPLATE_DIRS = (
# The docs say it should be absolute path: BASE_DIR is precisely one.
# Life is wonderful!
os.path.join(BASE_DIR, "templates"),
)
"""
CMS_TEMPLATES = (
('template_1.html', 'Template One'),
('template_2.html', 'Template Two'),
)
LANGUAGES = [
('en', 'English'),
]
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = 1
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
CMS_PAGE_MEDIA_PATH = os.path.join(MEDIA_ROOT, "cms_page_media")
AUTH_USER_MODEL = 'authenticateclients.UploaderClient'
When I run check or makemigrations or migrate I get
/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/importlib/_bootstrap.py:321: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9.
return f(*args, **kwds)
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/cms/models/__init__.py", line 4, in <module>
from .permissionmodels import * # nopyflakes
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/cms/models/permissionmodels.py", line 29, in <module>
User = apps.get_registered_model(user_app_name, user_model_name)
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/django/apps/registry.py", line 266, in get_registered_model
"Model '%s.%s' not registered." % (app_label, model_name))
LookupError: Model 'authenticateclients.UploaderClient' not registered.
So what I did is comment the line
AUTH_USER_MODEL = 'authenticateclients.UploaderClient'
and run makemigrations and migrate.
The migrations were applied.
Then on uncommenting the above line and trying check or makemigrations or migrate I'm still getting the same error.
Please help with the error.
If it is not possible to fix, can I proceed with my Project by commenting out the line or will the authentication not work if I leave out the line..
For this specific problem, part of the problem is already pointed out by #danihp. You need to put the app with your custom model before "cms" in your INSTALLED_APPS.
INSTALLED_APPS = {
'your_custom_app',
'...',
'cms',
}
Looking into your error stack trace it seems an issue getting permission:
File "/home/dip7777/Desktop/ARPixelEnv/lib/python3.4/site-packages/cms/models/permissionmodels.py", line 29, in
User = apps.get_registered_model(user_app_name, user_model_name)
django docs Customizing authentication in Django explains that:
If you don’t include the PermissionsMixin, you must ensure you don’t invoke the permissions methods on ModelBackend. ModelBackend assumes that certain fields are available on your user model. If your User model doesn’t provide those fields, you will receive database errors when you check permissions.
Then, for your scenario, it seems an easy way to avoid error is to inherit from PermissionsMixin.
This is an abstract model you can include in the class hierarchy for your User model, giving you all the methods and database fields necessary to support Django’s permission model.
For your code:
class UploaderClient(AbstractBaseUser, PermissionsMixin):
...
This question is the first result for LookupError: Model '' not registered., so I'm adding this here:
For those who were installing some applications in a development environment with a sqlite3 db, you can simply delete the default project.db file (if you don't have anything to lose).

Categories