How correctly add permissions to User model of Django? - python

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"

Related

OperationalError at / no such table: users_user

I had a model Profile which was an extension to my User model which was the ForeignKey of my Post model, but I changed it to an AbstractUser and now if I try migrating or running and refreshing the page the server I get an error.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
bio = models.TextField(max_length=500,null=True)
from django.db import models
from django.conf import settings
from django.urls import reverse
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=100)
content = models.TextField()
def get_absolute_url(self):
return reverse('post-details', kwargs={'pk': self.pk})
settings.py
INSTALLED_APPS = [
...
'posts',
'users',
]
AUTH_USER_MODEL = 'users.User'
error message after I try migrating
Apply all migrations: admin, auth, contenttypes, posts, sessions, users
Traceback (most recent call last):
File "/home/user/Projects/DNF/Project/manage.py", line 22, in <module>
main()
File "/home/user/Projects/DNF/Project/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 448, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/django/core/management/commands/migrate.py", line 295, in handle
pre_migrate_apps = pre_migrate_state.apps
File "/usr/local/lib/python3.10/dist-packages/django/utils/functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/state.py", line 566, in apps
return StateApps(self.real_apps, self.models)
File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/state.py", line 637, in __init__
raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field posts.Post.author was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
The field users.Profile.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'.
I easily solved it by deleting all the migration files in the migrations folder except the init.py file. And also delete db.sqlite3. Now run the following commands : python manage.py makemigrations and then python manage.py migrate. Now you'll have to create the super user once again, so for this just type the following commmand : python manage.py createsuperuser. Then it will prompt for username, email and password, so enter your credentials and all will continue to work properly once again I hope that this will be helpful.
try to directly reference the User model, not through settings
change the foreign key field to this:
author = models.ForeignKey("users.User", on_delete=models.CASCADE, null=True)
To have a reference to the User model, you should not do through settings directly instead you can use get_user_model() function. This function will return the currently active User model of project( the custom User model if one is specified, or User otherwise).
So change the foreign key field of your Post model like below:
from django.db import models
from django.conf import settings
from django.urls import reverse
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
...
Reference: get_user_model() [Django-doc]

AttributeError: 'postComments' object has no attribute 'model

I have made a new model postComments for my blogging website and now I am facing the above issue:
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
# Create your models here.
class post(models.Model):
SrNo = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
content = models.TextField()
author = models.CharField(max_length=50)
slug = models.SlugField(max_length=200)
timeStamp = models.DateTimeField(blank=True)
def __str__(self):
return self.title + " by " + self.author
class postComments(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(post, on_delete=models.CASCADE)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
timestamp = models.DateTimeField(default=now)
after writing the above '''postComments``` model the log window is showing me this error:
error log
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = checks.run_checks(
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\contrib\admin\checks.py", line 54, in check_admin_app
errors.extend(site.check(app_configs))
File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\contrib\admin\sites.py", line 84, in check
if modeladmin.model._meta.app_config in app_configs:
AttributeError: 'postComments' object has no attribute 'model'
admin.py:
from django.contrib import admin
from blog.models import post, postComments
# Register your models here.
admin.site.register((post), (postComments))
urls.py(blog app):
from django.urls import path, include
from blog import views
urlpatterns = [
path('', views.blogHome, name='home'),
path('<str:slug>', views.blogPost, name='blogpost'),
# here blog_name is string variable which will take the input after /blog/anyblogname
# and after this the page will display: this is 'anyblogname'
]
before adding this new model, the website was working just fine.
The correct way to register models is one per register call
from django.contrib import admin
from blog.models import post, postComments
# Register your models here.
admin.site.register(post)
admin.site.register(postComments)

Dependency on app with no migrations: %s" % key[0]) in the Django

I need create custom user. I'm using a user model with AbstractUser:
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.html import escape, mark_safe
class User(AbstractUser):
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
settings.py:
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'crispy_forms',
'backend.classroom',
]
I believe that problem is in the following line:
AUTH_USER_MODEL = 'classroom.User'
error:
File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 82, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__
self.build_graph()
File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/loader.py", line 226, in build_graph
self.add_external_dependencies(key, migration)
File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/loader.py", line 191, in add_external_dependencies
parent = self.check_key(parent, key[0])
File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/loader.py", line 173, in check_key
raise ValueError("Dependency on app with no migrations: %s" % key[0])
ValueError: Dependency on app with no migrations: classroom
obs: The app classrom app is in the backend folder. I tried the following code too:
AUTH_USER_MODEL = 'backend.classroom.User'
Try creating the initial migration for the classroom app before declaring it as AUTH_USER_MODEL, as anything that would ordinarily depend on auth.User now depends on classroom.User.
$ python manage.py makemigrations classroom
Your error is on the app install i think?
You are having classroom as app right? and the backend the project? if so then the correct
configuration
so the install app should be
INSTALLED_APPS = [
django.contrib.auth,
django.contrib.contenttypes,
django.contrib.sessions,
django.contrib.messages,
django.contrib.staticfiles,
django.contrib.humanize,
crispy_forms
classroom,
]
AUTH_USER_MODEL = classroom.User #classroom is app while User is the model

django : LookupError: App ' doesn't have a 'models' model

I'm working through https://bixly.com/blog/awesome-forms-django-crispy-forms/ , trying to set up a bootstrap 3 form using django crispy forms.
in app1/models.py, I have set up my form:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser
from django import forms
class User(AbstractUser):
# Address
contact_name = models.CharField(max_length=50)
contact_address = models.CharField(max_length=50)
contact_email = models.CharField(max_length=50)
contact_phone = models.CharField(max_length=50)
......
Please note I have not created any db tables yet. I don't need them at this stage. I'm just trying to get the forms working. When I run this I get:
Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x02B63EF0>
Traceback (most recent call last):
File "C:\lib\site-packages\django\utils\autoreload.py", line 222, in wrapper
fn(*args, **kwargs)
File "C:\lib\site-packages\django\core\management\commands\runserver.py", line 105, in inner_run
self.validate(display_num_errors=True)
File "C:\lib\site-packages\django\core\management\base.py", line 362, in validate
return self.check(app_configs=app_configs, display_num_errors=display_num_errors)
File "C:\lib\site-packages\django\core\management\base.py", line 371, in check
all_issues = checks.run_checks(app_configs=app_configs, tags=tags)
File "C:\lib\site-packages\django\core\checks\registry.py", line 59, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\lib\site-packages\django\contrib\auth\checks.py", line 12, in check_user_model
cls = apps.get_model(settings.AUTH_USER_MODEL)
File "C:\lib\site-packages\django\apps\registry.py", line 202, in get_model
return self.get_app_config(app_label).get_model(model_name.lower())
File "C:\lib\site-packages\django\apps\config.py", line 166, in get_model
"App '%s' doesn't have a '%s' model." % (self.label, model_name))
LookupError: App 'app1' doesn't have a 'models' model.
How can I fix this?
The AUTH_USER_MODEL settings should be of the form <app name>.<model>. Your model name is User, not model, so your setting should be:
AUTH_USER_MODEL = 'app1.User'
You should also remove the following User import from your models.py. You only have to import AbstractUser.
from django.contrib.auth.models import User

single file Django, DRF project

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.

Categories