Discussion:
Apps aren't loaded yet
Alexander Lamas
2018-08-20 07:33:40 UTC
Permalink
Hi guys,

I'm new in Python and Django, and I'm creating a Restful Web API using
Django REST framework.

I'm creating Unit Tests for my app, and for some reason I'm getting a
message like "Apps aren't loaded yet".
It looks like is some missing setting, but I have no idea how to fix that.

this is my unit test file

from django.urls import reversefrom rest_framework import statusfrom rest_framework.test import APITestCase, APIClientfrom app.models import Vendor
class VendorTests(APITestCase):

def test_1_Vendor_List_ReturnAllVendors(self):
url = reverse('vendor-list')
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Vendor.objects.count(), 0)

def test_2_Vendor_Post_ReturnNothing(self):
url = reverse('vendor-list')
data = {'id': 1, 'name': 'Vendor1'}
#data = {'name': 'Vendor1'}

response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data, data)

def test_3_Vendor_List_ReturnRegisteredVendors(self):
url = reverse('vendor-list')
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Vendor.objects.count(), 1)


This is my model class

from django.db import models
class Vendor(models.Model):
Name = models.CharField(db_column='Name', max_length=100, null=False)

def __str__(self):
return self.Name

class Meta:
ordering = ['Name']

def save(self, *args, **kwargs):
Name = self.Name
super(Vendor, self).save(*args, **kwargs)


this is my view

from rest_framework import generics, permissions, renderers, viewsetsfrom rest_framework.decorators import api_view, detail_routefrom app.models import Vendorfrom app.serializers import VendorSerializer
class VendorViewSet(viewsets.ModelViewSet):
queryset = Vendor.objects.all()
serializer_class = VendorSerializer

@detail_route(renderer_classes=[renderers.StaticHTMLRenderer])

def perform_create(self, serializer):
serializer.save()


this is my serializer

from rest_framework import serializersfrom app.models import Vendor
class VendorSerializer(serializers.ModelSerializer):
class Meta:
model = Vendor
fields = '__all__'


and this is my settings.py

import osimport posixpath
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '??????????????????????????????'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []
# Application definition

INSTALLED_APPS = [
'utils',
'rest_framework',
# Add your apps here to enable them
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',]

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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',]

ROOT_URLCONF = 'MyApp.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 = 'MyApp.wsgi.application'
# Database# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'root',
'PASSWORD': 'masterkey',
'HOST': 'localhost',
'PORT': '3306',
'TEST': {'NAME' : 'test_mydb'},
}}
# Password validation# https://docs.djangoproject.com/en/1.9/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/1.9/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/1.9/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'TEST_REQUEST_DEFAULT_FORMAT': 'json'}
# If you have own settings, make "local_settings.py" file and import in following.# And not include "local_settings.py" in remote repository.# When you want to save local settings, save in "local_setting_files" directory as rename.try:
from .local_settings import * except ImportError:
pass
#debug_toolbar settingsif DEBUG:
INTERNAL_IPS = ('127.0.0.1',
'localhost')
MIDDLEWARE += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)

INSTALLED_APPS += (
'debug_toolbar',
)

DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
]

DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}



Any ideas why I'm getting this message and why I can't run my unit tests?

Any help will be greatly appreciated.

Thanks in advance.

Regards,
Alex
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Carlton Gibson
2018-08-20 07:39:46 UTC
Permalink
I'm getting a message like "Apps aren't loaded yet".
This normally means you’re trying “use” a model at import-time, i.e. when the scripts are first loaded.
Look at the full traceback and see where your code is — the error should be there.

Normally you just need to move whatever you’re doing into an app ready handler, or into a runtime function or
 (depends where it’s coming up) — you just to delay execution of whatever is causing the issue.

(Hard to say without more detail but) hopefully that helps.

Kind Regards,

Carlton
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Alexander Lamas
2018-08-20 08:16:40 UTC
Permalink
Hi Carlton,

Thanks for your reply.

I actually, just found out that I have to add these 2 lines in the
beginning of my test file.

import django
django.setup()

then everything works as expected.

Thank you anyway!

Regards,
Alex
Post by Alexander Lamas
Hi guys,
I'm new in Python and Django, and I'm creating a Restful Web API using
Django REST framework.
I'm creating Unit Tests for my app, and for some reason I'm getting a
message like "Apps aren't loaded yet".
It looks like is some missing setting, but I have no idea how to fix that.
this is my unit test file
from django.urls import reversefrom rest_framework import statusfrom rest_framework.test import APITestCase, APIClientfrom app.models import Vendor
url = reverse('vendor-list')
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Vendor.objects.count(), 0)
url = reverse('vendor-list')
data = {'id': 1, 'name': 'Vendor1'}
#data = {'name': 'Vendor1'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data, data)
url = reverse('vendor-list')
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Vendor.objects.count(), 1)
This is my model class
from django.db import models
Name = models.CharField(db_column='Name', max_length=100, null=False)
return self.Name
ordering = ['Name']
Name = self.Name
super(Vendor, self).save(*args, **kwargs)
this is my view
from rest_framework import generics, permissions, renderers, viewsetsfrom rest_framework.decorators import api_view, detail_routefrom app.models import Vendorfrom app.serializers import VendorSerializer
queryset = Vendor.objects.all()
serializer_class = VendorSerializer
@detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
serializer.save()
this is my serializer
from rest_framework import serializersfrom app.models import Vendor
model = Vendor
fields = '__all__'
and this is my settings.py
import osimport posixpath
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '??????????????????????????????'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'utils',
'rest_framework',
# Add your apps here to enable them
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',]
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',]
ROOT_URLCONF = 'MyApp.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 = 'MyApp.wsgi.application'
# Database# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'root',
'PASSWORD': 'masterkey',
'HOST': 'localhost',
'PORT': '3306',
'TEST': {'NAME' : 'test_mydb'},
}}
# Password validation# https://docs.djangoproject.com/en/1.9/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/1.9/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/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'TEST_REQUEST_DEFAULT_FORMAT': 'json'}
pass
INTERNAL_IPS = ('127.0.0.1',
'localhost')
MIDDLEWARE += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
INSTALLED_APPS += (
'debug_toolbar',
)
DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
]
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
Any ideas why I'm getting this message and why I can't run my unit tests?
Any help will be greatly appreciated.
Thanks in advance.
Regards,
Alex
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Carlton Gibson
2018-08-20 08:17:54 UTC
Permalink
How are you running your tests? (django-admin test does all this for you
)
I actually, just found out that I have to add these 2 lines in the beginning of my test file.
import django
django.setup()
then everything works as expected.
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Alexander Lamas
2018-08-21 00:23:02 UTC
Permalink
Hi Carlton,

I'm running my tests via Microsoft Visual Studio.

Maybe that's why I've got that problem.

By the way, maybe this is a subject for another thread, but, in regards to
my unit test, is there a better way way of testing my model class?
I'm finishing testing the CRUD operations though.

Would you have any sample for model class unit testing, using Django Rest
Framework?

Also, how about my views and serializers, should I test them too? If so,
how can I do that?

Thank you very much!

Alex
Post by Carlton Gibson
How are you running your tests? (django-admin test does all this for you
)
I actually, just found out that I have to add these 2 lines in the
beginning of my test file.
import django
django.setup()
then everything works as expected.
--
You received this message because you are subscribed to the Google Groups
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an
For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Carlton Gibson
2018-08-21 08:39:14 UTC
Permalink
Hi Alex.

Big topic!

The quick points I can make here are:

* The “TestClient” based testing basically test the whole stack. They’re great but a bit broad brush.
* If you have a model method (say) that you want to test, create a unit test which just creates the model instance and executes the particular method. (Rather than using the test client to run the whole view stack that you wrapped around that.) Same with serialisers, and even views to some extent. (Instantiate the view, call the methods, check the return value — many times this doesn’t need the whole HTTP request-response cycle.)
* Some tests are better than no tests. It doesn’t have to be perfect. If you find a bug try to create a test for it before you fix it. These add up over time.

Don’t think I can say much more here.

Good luck.

Kind Regards,

Carlton
Post by Alexander Lamas
Hi Carlton,
I'm running my tests via Microsoft Visual Studio.
Maybe that's why I've got that problem.
By the way, maybe this is a subject for another thread, but, in regards to my unit test, is there a better way way of testing my model class?
I'm finishing testing the CRUD operations though.
Would you have any sample for model class unit testing, using Django Rest Framework?
Also, how about my views and serializers, should I test them too? If so, how can I do that?
Thank you very much!
Alex
How are you running your tests? (django-admin test does all this for you
)
I actually, just found out that I have to add these 2 lines in the beginning of my test file.
import django
django.setup()
then everything works as expected.
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
For more options, visit https://groups.google.com/d/optout <https://groups.google.com/d/optout>.
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
For more options, visit https://groups.google.com/d/optout <https://groups.google.com/d/optout>.
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Continue reading on narkive:
Loading...