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

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

Related

Django: ValueError Table allauth_socialapp does not exist

I successfully followed this tutorial and everything seemed to be ok. I then created a Profile model and managed to create it's objects through POST requests and through the admin panel. I then created signals so the profile could be created as soon as the user registered. After some trial and error I finally made it and decided I'd flush the database. When I tried to do so and ran python manage.py flush I got this error:
raise ValueError("Table %s does not exist" % table_name)
ValueError: Table allauth_socialapp does not exist
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\arthu\Desktop\dev\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\arthu\Desktop\dev\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\arthu\Desktop\dev\env\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\arthu\Desktop\dev\env\lib\site-packages\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "C:\Users\arthu\Desktop\dev\env\lib\site-packages\django\core\management\commands\flush.py", line 49, in handle
allow_cascade=allow_cascade)
File "C:\Users\arthu\Desktop\dev\env\lib\site-packages\django\core\management\sql.py", line 16, in sql_flush
seqs = connection.introspection.sequence_list() if reset_sequences else ()
File "C:\Users\arthu\Desktop\dev\env\lib\site-packages\django\db\backends\base\introspection.py", line 118, in sequence_list
sequence_list.extend(self.get_sequences(cursor, model._meta.db_table, model._meta.local_fields))
File "C:\Users\arthu\Desktop\dev\env\lib\site-packages\django\db\backends\sqlite3\introspection.py", line 96, in get_sequences
pk_col = self.get_primary_key_column(cursor, table_name)
File "C:\Users\arthu\Desktop\dev\env\lib\site-packages\django\db\backends\sqlite3\introspection.py", line 196, in get_primary_key_column
raise ValueError("Table %s does not exist" % table_name)
ValueError: Table allauth_socialapp does not exist
I already tried doing python manage.py migrate for each of the installed apps but nothing seems to work and already tried removing the Profile model and the receiver it is using but that doesn't solve the problem. Also tried deleting the sqlite file and all the migrations but it didn't help.
My models.py file looks like this:
class Profile(models.Model):
GENDER_CHOICES = (
('Male', 'Male'),
('Female', 'Female')
)
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
interests = models.CharField(max_length=100, null=True)
gender = models.CharField(max_length=6, choices=GENDER_CHOICES, null=True)
def __str__(self):
return f"{self.user}'s Profile"
#receiver(user_signed_up)
def user_registered(sender, request, user, **kwargs):
print(f"Created profile for { user}")
Profile.objects.create(user=user)
"""Creates the Profile after user registers"""
and my settings.py file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
'core'
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
SITE_ID = 1
Can someone please help me with this? I have no idea what I'm supposed to do and couldn't really find the answer online.
Simply solved this by adding 'allauth.socialaccount' to my INSTALLED_APPS and doing the migrations. Everything works fine now.
Try python manage.py makemigrations AppName
If this didnt work you can delete migration folder and your database and try.

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 error in django-social-auth

I am newbie in Django. I am implementing the facebook authentication in my app. The Error that i am getting in my terminal output is like ;
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 324, in execute
django.setup()
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/usr/local/lib/python2.7/dist-packages/social_auth/models.py", line 4, in <module>
from django.utils.importlib import import_module
ImportError: No module named importlib
What i am doing wrong? IS my newly installed django-python-social installed correctly?
It seems like django-social-auth have already issues with django 1.8, so I don't wonder if it has problems with django 1.9. I will recommand to use django-allauth since it's the most used/rated package for social network, and it's easy to configure:
pip install django-allauth
settings.py config
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
....
"django.core.context_processors.request",
# allauth specific context processors
"allauth.account.context_processors.account",
"allauth.socialaccount.context_processors.socialaccount",
],
},
},]
AUTHENTICATION_BACKENDS = (
# Default backend
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
INSTALLED_APPS += (
# The Django sites framework is required
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
# Login Facebook provider
'allauth.socialaccount.providers.facebook',
)
SITE_ID = 1
in urls.py add:
urlpatterns = patterns('',
...
#Auth URLS
url(r'^accounts/', include('allauth.urls')),
)
Finally apply database migration
run server and go to the admin interface at
http://127.0.0.1:8000/admin/sites/site and create a Site for
the localhost, 127.0.0.1:8000, or your website domain for
production. It should have an id equal to the SITE_ID configured
before in the setting.
Configure your facebook app to get secret key, and then create a Social Application for Facebook at http://127.0.0.1:8000/admin/socialaccount/socialapp
--> you may also find this tutoriel useful
django-social-auth has officially been deprecated in favour of python-social-auth. So you should not be using it. Moreover the import error is most probably due to incompatibility with Django 1.9 as importlib has been deprecated from django.

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.

No module named http_client error when trying to run django with django rest framework

I am trying to create a simple API using django rest framework. In the view i have the following code.
from django.shortcuts import render
from moviestash.models import Movie
from moviestash.serializer import MovieSerializer
from rest_framework import generics
#List all movies and add movies
class MovieList(generics.ListCreateAPIView):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
#Get a movie and delete a movie
class MovieDetail(generics.RetrieveDestroyAPIView):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
when i run the server and try to go to any url i get the following error.
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.6
Python Version: 2.7.0
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'moviestash',
'south',
'rest_framework')
Installed Middleware:
('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')
Traceback:
File "N:\Python\venvs\rest_api\lib\site-packages\django\core\handlers\base.py" in get_response
101. resolver_match = resolver.resolve(request.path_info)
File "N:\Python\venvs\rest_api\lib\site-packages\django\core\urlresolvers.py" in resolve
318. for pattern in self.url_patterns:
File "N:\Python\venvs\rest_api\lib\site-packages\django\core\urlresolvers.py" in url_patterns
346. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "N:\Python\venvs\rest_api\lib\site-packages\django\core\urlresolvers.py" in urlconf_module
341. self._urlconf_module = import_module(self.urlconf_name)
File "N:\Python\venvs\rest_api\lib\site-packages\django\utils\importlib.py" in import_module
40. __import__(name)
File "N:\Python\movies_api\movies_api\urls.py" in <module>
10. url(r'^movies/', include('moviestash.urls')),
File "N:\Python\venvs\rest_api\lib\site-packages\django\conf\urls\__init__.py" in include
26. urlconf_module = import_module(urlconf_module)
File "N:\Python\venvs\rest_api\lib\site-packages\django\utils\importlib.py" in import_module
40. __import__(name)
File "N:\Python\movies_api\moviestash\urls.py" in <module>
3. from . import views
File "N:\Python\movies_api\moviestash\views.py" in <module>
4. from rest_framework import generics
File "N:\Python\venvs\rest_api\lib\site-packages\rest_framework\generics.py" in <module>
8. from rest_framework import views, mixins
File "N:\Python\venvs\rest_api\lib\site-packages\rest_framework\views.py" in <module>
14. from rest_framework.response import Response
File "N:\Python\venvs\rest_api\lib\site-packages\rest_framework\response.py" in <module>
8. from django.utils.six.moves.http_client import responses
Exception Type: ImportError at /
Exception Value: No module named http_client
When i go into the django shell and i can perform the following import with no issue from django.utils.six.moves import http_client. Also after i import http_client i also performed a dir(http_client) and i can see the responses object, but for some reason when i try to import using from django.utils.six.moves.http_client import responses i get an ImportError: No module named http_client. This is very frustrating to say the least.
It looks like you are hitting issue 2969. It should work if you upgrade from Django 1.6 to 1.6.11. However, please note that 1.6 is now end of life and does not receive security fixes, so ideally you should upgrade to the latest supported version of Django or the latest LTS.

Categories