django.core.exceptions.ImproperlyConfigured - python

I have recently moved to another machine and have had to check my project out from subversion again, but I am pretty sure this computer has Django 1.8 and the project is expecting 1.7.
I have tried to sync my db with the code to create the necessary tables but I get the following error.
C:\Users\jont\Documents\ATP\Webapp>manage.py syncdb
C:\Python27\lib\site-packages\admin_tools\utils.py:9: RemovedInDjango19Warning:
django.utils.importlib will be removed in Django 1.9.
from django.utils.importlib import import_module
c:\users\jont\documents\django-trunk\django\contrib\contenttypes\models.py:148:
RemovedInDjango19Warning: Model class django.contrib.contenttypes.models.ContentType doesn't de
her isn't in an application in INSTALLED_APPS or else was imported before its application was
loaded. This will no longer be supported in Django 1.9.
class ContentType(models.Model):
C:\Python27\lib\site-packages\admin_tools\dashboard\modules.py:8: RemovedInDjango19Warning: The
django.forms.util module has been renamed. Use django.forms.utils instead.
from django.forms.util import flatatt
C:\Python27\lib\site-packages\django_tables2\tables.py:171: RemovedInDjango19Warning: SortedDict
is deprecated and will be removed in Django 1.9. attrs["base_columns"] =
SortedDict(parent_columns)
C:\Python27\lib\site-packages\django_tables2\tables.py:193: RemovedInDjango19Warning: SortedDict
is deprecated and will be removed in Django 1.9.
attrs["base_columns"].update(SortedDict(cols))
Traceback (most recent call last):
File "C:\Users\jont\Documents\ATP\Webapp\manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "c:\users\jont\documents\django-trunk\django\core\management\__init__.py", line 336, in
execute_from_command_line
utility.execute()
File "c:\users\jont\documents\django-trunk\django\core\management\__init__.py", line 310, in
execute
django.setup()
File "c:\users\jont\documents\django-trunk\django\__init__.py", line 23, in setup
apps.populate(settings.INSTALLED_APPS)
File "c:\users\jont\documents\django-trunk\django\apps\registry.py", line 115, in populate
app_config.ready()
File "c:\users\jont\documents\django-trunk\django\contrib\admin\apps.py", line 22, in ready
self.module.autodiscover()
File "c:\users\jont\documents\django-trunk\django\contrib\admin\__init__.py", line 24, in
autodiscover
autodiscover_modules('admin', register_to=site)
File "c:\users\jont\documents\django-trunk\django\utils\module_loading.py", line 73, in
autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\jont\Documents\ATP\Webapp\jobs\admin.py", line 4, in <module>
from jobs.views import registration
File "C:\Users\jont\Documents\ATP\Webapp\jobs\views.py", line 12, in <module>
from jobs.forms import ApplicantForm, JobForm, \
File "C:\Users\jont\Documents\ATP\Webapp\jobs\forms.py", line 8, in <module>
class JobForm(forms.ModelForm):
File "c:\users\jont\documents\django-trunk\django\forms\models.py", line 272, in __new__
"needs updating." % name
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form JobForm needs updating.
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form JobForm needs updating.

Like the error mentions, you need to explicitly specify the fields, or exclude.
Try this
class JobForm(models.ModelForm):
#fields
class Meta:
model = Job
fields = "__all__"
which would include all the fields
Here is the relevant documentation (release notes 1.6)
Previously, if you wanted a ModelForm to use all fields on the model,
you could simply omit the Meta.fields attribute, and all fields would
be used.
This can lead to security problems where fields are added to the model
and, unintentionally, automatically become editable by end users. In
some cases, particular with boolean fields, it is possible for this
problem to be completely invisible. This is a form of Mass assignment
vulnerability.
For this reason, this behavior is deprecated, and using the
Meta.exclude option is strongly discouraged. Instead, all fields that
are intended for inclusion in the form should be listed explicitly in
the fields attribute.
If this security concern really does not apply in your case, there is
a shortcut to explicitly indicate that all fields should be used - use
the special value "__all__" for the fields attribute

You can set fields or exclude in the ModelForm in Django 1.7.
It changes in 1.8, you should set fields or exclude in the Meta class within ModelForm.
class JobForm(models.ModelForm):
#fields
class Meta:
model = Job
fields = "__all__"

I got the same error when I set "Meta" inner class without "fields" or "exclude" attributes in "NewUserForm(UserCreationForm)" class in "account/forms.py" to create a form as shown below:
# "account/forms.py"
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class NewUserForm(UserCreationForm):
class Meta: # Here
model = User
So, I added "fields" attribute to "Meta" inner class as shown below:
# "account/forms.py"
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class NewUserForm(UserCreationForm):
class Meta: # Here
model = User
fields = ("username",) # Here
Or, added "exclude" attribute to "Meta" inner class as shown below:
# "account/forms.py"
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class NewUserForm(UserCreationForm):
class Meta: # Here
model = User
exclude = ("first_name", "last_name") # Here
Then, I could solve the error.

Dropping to Django 1.7 seemed to do the trick. There didn't seem to be an easy way to adapt the code to fit Django 1.8.

Related

ImportError: cannot import name 'fields' from 'django.db.models.fields'

I got the following error during creation of django serializer.
ImportError: cannot import name 'fields' from 'django.db.models.fields' (/home/user_name/anaconda3/lib/python3.7/site-packages/django/db/models/fields/__init__.py)
and the serializer.py file is
from django.db.models.base import Model
from django.db.models.fields import fields, files
from rest_framework import serializers
from .models import Lead
#create serializers for Lead
class LeadSerializer(serializers.ModelSerializer):
class Meta:
model = Lead
fields = '__all__'
my current django version is 3.0.7.
what is wrong in this code ?
I'm not sure why you are trying to import fields or files as a matter of fact.
You are trying to import fields from fields. That will not work.
Also, the class Meta doesn't need you to import fields as it has access to this already. Remove the second line of code and give it a go, or if you need files for some other part of your code then just remove fields.

Trying to add custom fields to users in Django

I am fairly new to django and was it was going well until this.
i'm trying to add fields 'address' and 'phone_number' to users (create custom user basically) but i keep getting this error like this...
File "C:\Users\will5\Desktop\City\city_info\forms.py", line 5, in <module>
class UserForm(forms.ModelForm):
File "C:\Users\will5\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\forms\models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (phone_number, address)
specified for User
this is models
...
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
phone_number = models.IntegerField(default=0)
address = models.CharField(max_length=150)
...
this is in my forms
from django.contrib.auth.models import User
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password', 'address', 'phone_number']
I also read that in order to fix this problem i will have to restart my project by creating the custom user and migrating and i don't wanna do that.
The problem is that you are still importing the built in user model
You can fix it by replacing
from django.contrib.auth.models import User
with
from django.contrib.auth import get_user_model
User = get_user_model()
This assumes that you have set AUTH_USER_MODEL = 'yourapp.User' in your settings.
As you have read in the docs, it is extremely difficult to switch to a custom user model after the project has started, there isn't an easy solution to this. If you can't restart your project, perhaps you could create a Profile model with a OneToOneField to the default User instead.

Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"

I am building a project in Django Rest Framework where users can login to view their wine cellar.
My ModelViewSets were working just fine and all of a sudden I get this frustrating error:
Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
The traceback shows:
[12/Dec/2013 18:35:29] "GET /bottles/ HTTP/1.1" 500 76677
Internal Server Error: /bottles/
Traceback (most recent call last):
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/viewsets.py", line 78, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/views.py", line 399, in dispatch
response = self.handle_exception(exc)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/views.py", line 396, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/mixins.py", line 96, in list
return Response(serializer.data)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/serializers.py", line 535, in data
self._data = [self.to_native(item) for item in obj]
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/serializers.py", line 325, in to_native
value = field.field_to_native(obj, field_name)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/relations.py", line 153, in field_to_native
return self.to_native(value)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/relations.py", line 452, in to_native
raise Exception(msg % view_name)
Exception: Could not resolve URL for hyperlinked relationship using view
name "user-detail". You may have failed to include the related model in
your API, or incorrectly configured the `lookup_field` attribute on this
field.
I have a custom email user model and the bottle model in models.py is:
class Bottle(models.Model):
wine = models.ForeignKey(Wine, null=False)
user = models.ForeignKey(User, null=False, related_name='bottles')
My serializers:
class BottleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Bottle
fields = ('url', 'wine', 'user')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'password', 'is_superuser')
My views:
class BottleViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows bottles to be viewed or edited.
"""
queryset = Bottle.objects.all()
serializer_class = BottleSerializer
class UserViewSet(ListCreateAPIView):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
and finally the url:
router = routers.DefaultRouter()
router.register(r'bottles', views.BottleViewSet, base_name='bottles')
urlpatterns = patterns('',
url(r'^', include(router.urls)),
# ...
I don't have a user detail view and I don't see where this issue could come from. Any ideas?
Thanks
Because it's a HyperlinkedModelSerializer your serializer is trying to resolve the URL for the related User on your Bottle.
As you don't have the user detail view it can't do this. Hence the exception.
Would not just registering the UserViewSet with the router solve your issue?
You could define the user field on your BottleSerializer to explicitly use the UserSerializer rather than trying to resolve the URL. See the serializer docs on dealing with nested objects for that.
I came across this error too and solved it as follows:
The reason is I forgot giving "**-detail" (view_name, e.g.: user-detail) a namespace. So, Django Rest Framework could not find that view.
There is one app in my project, suppose that my project name is myproject, and the app name is myapp.
There is two urls.py file, one is myproject/urls.py and the other is myapp/urls.py. I give the app a namespace in myproject/urls.py, just like:
url(r'', include(myapp.urls, namespace="myapp")),
I registered the rest framework routers in myapp/urls.py, and then got this error.
My solution was to provide url with namespace explicitly:
class UserSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="myapp:user-detail")
class Meta:
model = User
fields = ('url', 'username')
And it solved my problem.
Maybe someone can have a look at this : http://www.django-rest-framework.org/api-guide/routers/
If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters on the serializers correctly reflect the namespace. For example:
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include(router.urls, namespace='api')),
]
you'd need to include a parameter such as view_name='api:user-detail' for serializer fields hyperlinked to the user detail view.
class UserSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="api:user-detail")
class Meta:
model = User
fields = ('url', 'username')
Another nasty mistake that causes this error is having the base_name unnecessarily defined in your urls.py. For example:
router.register(r'{pathname}', views.{ViewName}ViewSet, base_name='pathname')
This will cause the error noted above. Get that base_name outta there and get back to a working API. The code below would fix the error. Hooray!
router.register(r'{pathname}', views.{ViewName}ViewSet)
However, you probably didn't just arbitrarily add the base_name, you might have done it because you defined a custom def get_queryset() for the View and so Django mandates that you add the base_name. In this case you'll need to explicitly define the 'url' as a HyperlinkedIdentityField for the serializer in question. Notice we are defining this HyperlinkedIdentityField ON THE SERIALIZER of the view that is throwing the error. If my error were "Could not resolve URL for hyperlinked relationship using view name "study-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field." I could fix this with the following code.
My ModelViewSet (the custom get_queryset is why I had to add the base_name to the router.register() in the first place):
class StudyViewSet(viewsets.ModelViewSet):
serializer_class = StudySerializer
'''custom get_queryset'''
def get_queryset(self):
queryset = Study.objects.all()
return queryset
My router registration for this ModelViewSet in urls.py:
router.register(r'studies', views.StudyViewSet, base_name='studies')
AND HERE'S WHERE THE MONEY IS! Then I could solve it like so:
class StudySerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="studies-detail")
class Meta:
model = Study
fields = ('url', 'name', 'active', 'created',
'time_zone', 'user', 'surveys')
Yep. You have to explicitly define this HyperlinkedIdentityField on itself for it to work. And you need to make sure that the view_name defined on the HyperlinkedIdentityField is the same as you defined on the base_name in urls.py with a '-detail' added after it.
This code should work, too.
class BottleSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
class Meta:
model = Bottle
fields = ('url', 'wine', 'user')
Today, I got the same error and below changes rescue me.
Change
class BottleSerializer(serializers.HyperlinkedModelSerializer):
to:
class BottleSerializer(serializers.ModelSerializer):
I ran into this error after adding namespace to my url
url('api/v2/', include('api.urls', namespace='v2')),
and adding app_name to my urls.py
I resolved this by specifying NamespaceVersioning for my rest framework api in settings.py of my project
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.NamespaceVersioning'}
TL;DR: It may be as simple as removing a trailing 's' from the router basename. No need to define a url field in your serializer.
For the original poster, the issue was resolved simply by registering the UserViewSet, as suggested in the top answer.
However, if anyone else has this issue even with all ViewSets registered, I think I've figured out what's going wrong, and I've found a solution that's cleaner than a lot of the others here.
In my case, I encountered this issue after trying to create a ViewSet with a custom get_queryset() function. When I replaced the ViewSet's queryset field with a custom get_queryset() function, I was then hit with this error:
AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute.
So, of course, I went to urls.py and modified my registration to include a basename as such:
router.register(r'messages', MessageViewSet, basename='messages')
But then I was hit with this error (as we see in the original post):
Could not resolve URL for hyperlinked relationship using view name "message-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
After reading the DRF docs on routers, I learned that the router automatically generates two url patterns for you, which have names:
'basename-list'
'basename-detail'
Because I set my basename='messages' (note the 's' at the end), my url patterns were named:
'messages-list'
'messages-detail'
Since DRF was looking a url pattern named 'message-detail' (note here the lack of 's'), I realized that I could resolve this simply by removing the trailing 's' from my basename as such:
router.register(r'messages', MessageViewSet, basename='message')
My final serializer and ViewSet implementations were as simple as this!
class MessageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Message
fields = ['url', 'message', 'timestamp', 'sender', ...]
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
def get_queryset(self):
return Message.objects.filter(...)
It appears that HyperlinkedModelSerializer do not agree with having a path namespace. In my application I made two changes.
# rootapp/urls.py
urlpatterns = [
# path('api/', include('izzi.api.urls', namespace='api'))
path('api/', include('izzi.api.urls')) # removed namespace
]
In the imported urls file
# app/urls.py
app_name = 'api' // removed the app_name
Hope this helps.
Same Error, but different reason:
I define a custom user model, nothing new field:
from django.contrib.auth.models import (AbstractUser)
class CustomUser(AbstractUser):
"""
custom user, reference below example
https://github.com/jonathanchu/django-custom-user-example/blob/master/customuser/accounts/models.py
# original User class has all I need
# Just add __str__, not rewrite other field
- id
- username
- password
- email
- is_active
- date_joined
- method, email_user
"""
def __str__(self):
return self.username
This is my view function:
from rest_framework import permissions
from rest_framework import viewsets
from .models import (CustomUser)
class UserViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.AllowAny,)
serializer_class = UserSerializer
def get_queryset(self):
queryset = CustomUser.objects.filter(id=self.request.user.id)
if self.request.user.is_superuser:
queryset = CustomUser.objects.all()
return queryset
Since I didn't give queryset directly in UserViewSet, I have to set base_name when I register this viewset. This is where my error message caused by urls.py file:
from myapp.views import (UserViewSet)
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'users', UserViewSet, base_name='customuser') # <--base_name needs to be 'customuser' instead of 'user'
You need a base_name same as your model name - customuser.
If you're extending the GenericViewSet and ListModelMixin classes, and have the same error when adding the url field in the list view, it's because you're not defining the detail view. Be sure you're extending the RetrieveModelMixin mixin:
class UserViewSet (mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
A bit late but in Django 3 and above, include doesn't support namespace without specifying the app_name. Checking the source code for include, we see that the condition
if namespaces and not app_name:
....
is checked. And still from the source code, app_name is gotten like;
urlconf_module, app_name = arg
where arg is the first argument of the include. This tells us that, our include should be defined as
include((app.urls, app_name), namespace='...')
Example
Say you have a project myproject and an app myapp. Then you want to establish an address. You should use a viewset and define a router as below
myapp.urls
router.register('address', exampleviewset, basename='address')
myproject.urls
path('api/v1/', include(('myapp.urls', 'myapp'), namespace='myapp')),
serializers.py
class AddressSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="myapp:address-detail")
class Meta:
model = Address
fields = ('url',...)
Apparently, we can't use fields='__all__'. We must include url explicitly and list the remaining fields we need.
I ran into the same error while I was following the DRF quickstart guide
http://www.django-rest-framework.org/tutorial/quickstart/ and then attempting to browse to /users. I've done this setup many times before without problems.
My solution was not in the code but in replacing the database.
The difference between this install and the others before was when I created the local database.
This time I ran my
./manage.py migrate
./manage.py createsuperuser
immediately after running
virtualenv venv
. venv/bin/activate
pip install django
pip install djangorestframework
Instead of the exact order listed in the guide.
I suspected something wasn't properly created in the DB. I didn't care about my dev db so I deleted it and ran the ./manage.py migrate command once more, created a super user, browsed to /users and the error was gone.
Something was problematic with the order of operations in which I configured DRF and the db.
If you are using sqlite and are able to test changing to a fresh DB then it's worth an attempt before you go dissecting all of your code.
Bottle = serializers.PrimaryKeyRelatedField(read_only=True)
read_only allows you to represent the field without having to link it to another view of the model.
I got that error on DRF 3.7.7 when a slug value was empty (equals to '') in the database.
I ran into this same issue and resolved it by adding generics.RetrieveAPIView as a base class to my viewset.
I was stuck in this error for almost 2 hours:
ImproperlyConfigured at /api_users/users/1/
Could not resolve URL for hyperlinked relationship using view name "users-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
When I finally get the solution but I don't understand why, so my code is:
#models.py
class Users(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50, blank=False, null=False)
email = models.EmailField(null=False, blank=False)
class Meta:
verbose_name = "Usuario"
verbose_name_plural = "Usuarios"
def __str__(self):
return str(self.name)
#serializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Users
fields = (
'id',
'url',
'name',
'email',
'description',
'active',
'age',
'some_date',
'timestamp',
)
#views.py
class UserViewSet(viewsets.ModelViewSet):
queryset = Users.objects.all()
serializer_class = UserSerializer
#urls_api.py
router = routers.DefaultRouter()
router.register(r'users',UserViewSet, base_name='users')
urlpatterns = [
url(r'^', include(router.urls)),
]
but in my main URLs, it was:
urlpatterns = [
url(r'^admin/', admin.site.urls),
#api users
url(r'^api_users/', include('usersApi.users_urls', namespace='api')),
]
So to finally I resolve the problem erasing namespace:
urlpatterns = [
url(r'^admin/', admin.site.urls),
#api users
url(r'^api_users/', include('usersApi.users_urls')),
]
And I finally resolve my problem, so any one can let me know why, bests.
If you omit the fields 'id' and 'url' from your serializer you won't have any problem. You can access to the posts by using the id that is returned in the json object anyways, which it makes it even easier to implement your frontend.
I had the same problem , I think you should check your
get_absolute_url
object model's method input value (**kwargs) title.
and use exact field name in lookup_field
It is worth noting that if you create an action with detail=False (typo?) then this errors will be raised, replace it with detail=True:
#action(detail=True)
...
I wanted to stay with everything as-is out of the box so I just added a User serializer:
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['id', 'username']
A Viewset:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
And added to urls:
router.register(r'users', UserViewSet)
From DRF Docs:
drf docs note source
Note: If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as view_name='app_name:user-detail' for serializer fields hyperlinked to the user detail view.
The automatic view_name generation uses a pattern like %(model_name)-detail. Unless your models names actually clash you may be better off not namespacing your Django REST Framework views when using hyperlinked serializers.
Solution
example of setting view_name
from rest_framework import serializers
from myapp.models import Post
from django.contrib.auth.models import User
class PostSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="api:post-detail")
author = serializers.HyperlinkedRelatedField(view_name="api:user-detail", read_only=True)
viewers = serializers.HyperlinkedRelatedField(view_name="api:user-detail", read_only=True, many=True)
class Meta:
model = Post
fields = ('id', 'title', 'url', 'author', 'viewers')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"

Django ORM cannot resolve keyword for related field for aggregate when model used by more than one application

In Django 1.5 I have 3 apps: common, app1, app2 in which I have the following (simplified) models:
# common/models.py
class ApiUser(models.Model):
username = models.CharField(max_length=255)
channel = models.CharField(max_length=20)
# app1/models.py
class Place(models.Model):
title = models.CharField(max_length=255)
created_by = models.ForeignKey('common.ApiUser', null=True, related_name="%(app_label)s_places")
# app2/models.py
class Tag(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey('common.ApiUser', null=True, related_name="%(app_label)s_tags")
app1 is listed before app2 in INSTALLED_APPS.
When I try to create the following queryset:
qs = ApiUser.objects.filter(channel='app1').annotate(Count('app1_places'))
I get back:
Cannot resolve keyword 'app1_places' into field. Choices are: app2_tags, channel, username
Where the list of choices provided does not include 'app1_places' but does contain 'app2_tags'. However if I try to reference app1_places on a model instance I don't get an error; it works fine:
>>> u = ApiUser.objects.get(pk=23)
>>> u.app1_places.all()
[]
Annotate with app2_tags works too:
qs = ApiUser.objects.filter(channel='app2').annotate(Count('app2_tags'))
Is this a bug in django or is there something I am doing wrong configuring these fields.
edit: here is the stack trace:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/vagrant/.virtualenvs/thorium/lib/python2.6/site-packages/django/db/models/query.py", line 795, in annotate
is_summary=False)
File "/home/vagrant/.virtualenvs/thorium/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1019, in add_aggregate
field_list, opts, self.get_initial_alias(), False)
File "/home/vagrant/.virtualenvs/thorium/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1337, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'app1_places' into field. Choices are: app2_tags, channel, username
Note: some app1 models are using the GeoDjango GeoManager (including places) but there are also models in app1 which don't use the geomanager and have foreign keys that also do not work with annotate.
It turns out the issue was with a proxy model that was on app1 and not app2. The proxy model had a custom manager:
# app1/models.py
class App1User(common_models.ApiUser):
objects = common_models.ApiUser.objects.filter(channel='app1')
class Meta:
proxy = True
App2 is not using a corresponding proxy model for ApiUser. When django first loads all the models to determine the model domain and calculate backwards references the overridden manager in the proxy model short-circuited the loading of app1.models, leaving all the backwards references for that module uninitialised.
Removing the custom manager definition resolved the issue.

Django 1.6 AbstractUser m2m models validation error

I don't have errors with Django 1.5.4 (stable), but when I was testing my application on Django 1.6 beta 4 from official tar.gz I got error with validation models on startup.
models.py
from django.contrib.auth.models import AbstractUser, User
class ShopUser(AbstractUser):
model_car = models.CharField(max_length=200)
date_car = models.DateField()
description = models.TextField(blank=True, db_index=True)
manager = models.ForeignKey(User)
This is manage.py runserver console log:
Validating models...
Unhandled exception in thread started by <function wrapper at 0x2d941b8>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 93, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 97, in inner_run
self.validate(display_num_errors=True)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 312, in validate
raise CommandError("One or more models did not validate:\n%s" % error_text)
django.core.management.base.CommandError: One or more models did not validate:
adminka.shopuser: Accessor for m2m field 'groups' clashes with related m2m field 'Group.user_set'. Add a related_name argument to the definition for 'groups'.
adminka.shopuser: Accessor for m2m field 'user_permissions' clashes with related m2m field 'Permission.user_set'. Add a related_name argument to the definition for 'user_permissions'.
auth.user: Accessor for m2m field 'groups' clashes with related m2m field 'Group.user_set'. Add a related_name argument to the definition for 'groups'.
auth.user: Accessor for m2m field 'user_permissions' clashes with related m2m field 'Permission.user_set'. Add a related_name argument to the definition for 'user_permissions'.
python -c "import django;print django.get_version()"
1.6b4
What need to do for solve this problem?
You must declare AUTH_USER_MODEL on your settings.py. In your case:
AUTH_USER_MODEL = 'your_app.ShopUser'
For me this was fixed in Django 1.6.5 by changing this:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
to this:
from django.contrib.auth.models import AbstractBaseUser
class CustomUser(AbstractBaseUser):
pass
No other changes needed in Django 1.6.5. #Stormlifter's suggestion has merit but I am using this CustomUser with this stuff for OAuth2 via python-social-auth:
$ pip freeze
Django==1.6.5
Markdown==2.4.1
MySQL-python==1.2.5
PyJWT==0.2.1
South==1.0
basicauth==0.2
boto==2.28.0
django-filter==0.7
django-guardian==1.2.0
django-storages==1.1.8
djangorestframework==2.3.14
httplib2==0.9
oauth2==1.5.211
oauthlib==0.6.3
python-memcached==1.53
python-oauth2==0.7.0
python-openid==2.2.5
python-social-auth==0.2.1
requests==2.4.1
requests-oauthlib==0.4.1
shortuuid==0.4.2
six==1.7.2
wsgiref==0.1.2
My new CustomUser will be doing more than the default user and does need to be the AUTH_USER_MODEL='myapp.CustomUser' in settings.py as #jordiburgos suggested.
I hope this helps!
You want to inherit from AbstractBaseUser not from AbstractUser.
However, it looks like you just want to store some additional information for users, I wouldn't recommend using a custom user model for this. Just use relationships.
class ShopUser(models.Model):
model_car = models.CharField(max_length=200)
date_car = models.DateField()
description = models.TextField(blank=True, db_index=True)
user = models.OneToOneField(User)
You could make that a ForeignKey if you need Multiple ShopUser's to relate to a single user, but I think OneToOne makes the most sense.
As told by Django Documents:
Specifying a custom user model
AbstractBaseUser

Categories