DRF: Cannot POST or create a new object through admin interface












1














I am getting the following error when I try to create a new object through the admin interface:




TypeError: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple'




I have the following models:



class CustomUser(AbstractUser):
def __str__(self):
return self.email

class Meta:
ordering = ('id',)
verbose_name = 'user'

class Address(models.Model):
"""Address contains information about location. Address can be own by any
kind of model."""
content_type = models.ForeignKey(
ContentType, on_delete=models.CASCADE, null=True
)
object_id = models.PositiveIntegerField(null=True)
owner = GenericForeignKey("content_type", "object_id")

CATEGORIES = Choices('billing', 'shipping')
category = models.CharField(choices=CATEGORIES, max_length=16)
address_1 = models.CharField("address line 1", max_length=128)
address_2 = models.CharField("address line 2", max_length=128, blank=True)
city = models.CharField(max_length=64)
state_province = models.CharField('state/province', max_length=128)
country = CountryField(blank_label='(select country)')
zip_code = models.CharField(max_length=10)

def __str__(self):
return (
f'{self.address_1}, {self.city}, {self.state_province}, '
f'{self.country.name}, {self.zip_code}'
)

class Meta:
ordering = ('id',)

class Company(Group):
"""An abstract base class that inherits Group."""
addresses = GenericRelation(Address)
owner = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='%(class)ss',
related_query_name='%(class)s')
logo = CloudinaryField('image',
default='your_logo_here',
null=True,
blank=True)
description = models.TextField('description', max_length=3000, blank=True)
facebook_url = models.URLField('facebook url', blank=True)
twitter_url = models.URLField('twitter url', blank=True)
instagram_url = models.URLField('instagram url', blank=True)
pinterest_url = models.URLField('pinterest url', blank=True)
portfolio_url = models.URLField('portfolio url', blank=True)
phone_number = PhoneNumberField('phone number', blank=True)

class Meta:
abstract = True
ordering = ('id',)


class Brand(Company):
"""A Brand can have multiple members."""


These are my serializers:



class CustomUserSerializer(HyperlinkedModelSerializer):
brands = HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='brand-detail'
)

class Meta:
model = CustomUser
fields = (
'url',
'username',
'email',
'brands',
)

class AddressSerializer(HyperlinkedModelSerializer):
owner = GenericRelatedField({
Brand: HyperlinkedRelatedField(
queryset=Brand.objects.all(),
view_name='brand-detail',
)
})

class Meta:
model = Address
fields = (
'url',
'category',
'address_1',
'address_2',
'city',
'state_province',
'country',
'zip_code',
'owner',
)


class BrandSerializer(HyperlinkedModelSerializer):
addresses = HyperlinkedRelatedField(many=True,
read_only=True,
view_name='address-detail')

class Meta:
model = Brand
fields = (
'url',
'owner',
'logo',
'description',
'facebook_url',
'twitter_url',
'instagram_url',
'pinterest_url',
'portfolio_url',
'phone_number',
'addresses',
)


This is how I configured the urls:



router = DefaultRouter()
router.register('users', CustomUserViewSet)
router.register('addresses', AddressViewSet)
router.register('brands', BrandViewSet)

urlpatterns = [
path('', include(router.urls)),
path('auth/', include('rest_framework.urls', namespace='rest_framework')),
]


I can access http://localhost:8000/api/addresses/, and I have the following form:



enter image description here



The problem is when I try to POST to create a new object. I am getting that error I have described, and it seems because I am not passing properly the owner (actually I have no idea how to pass an object here, should I use a JSON or how).



enter image description here



Questions:




  1. How can I solve this error because I am also trying to test the POST method, and it was when I realized this was not working?


  2. Is there any way to include the fields of a GenericForeignKey in that form?



This is my traceback:



File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in to_internal_value
39. serializer = self.get_deserializer_for_data(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in get_deserializer_for_data
75. 'Could not determine a valid serializer for value %r.' % value)

During handling of the above exception (Could not determine a valid serializer for value ''.), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in to_internal_value
488. validated_value = field.run_validation(primitive_value)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in run_validation
536. value = self.to_internal_value(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in to_internal_value
41. raise ValidationError(e)

During handling of the above exception (["Could not determine a valid serializer for value ''."]), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in get_error_detail
240. error_dict = exc_info.error_dict

During handling of the above exception ('ValidationError' object has no attribute 'error_dict'), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/mixins.py" in create
20. serializer.is_valid(raise_exception=True)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in is_valid
236. self._validated_data = self.run_validation(self.initial_data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in run_validation
434. value = self.to_internal_value(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in to_internal_value
494. errors[field.field_name] = get_error_detail(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in get_error_detail
245. for error in exc_info.error_list]

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in <listcomp>
245. for error in exc_info.error_list]

Exception Type: TypeError at /api/addresses/
Exception Value: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple'









share|improve this question
























  • Please add the full error traceback to your question.
    – Klaus D.
    Nov 23 '18 at 3:11










  • @KlausD, I just added it.
    – lmiguelvargasf
    Nov 23 '18 at 3:15






  • 1




    try to comment out the __str__() method of Address model and try again
    – JPG
    Nov 23 '18 at 3:21










  • @JPG, I did it, and I am still getting the same error. I wonder why you are suggesting that since the __str__ method is just a string representation.
    – lmiguelvargasf
    Nov 23 '18 at 3:24










  • If I do a web search for 'ImproperlyConfigured' I find a lot of results referencing 'ImproperlyConfigured' and wsgi. How are you running your server?
    – Red Cricket
    Nov 23 '18 at 4:29
















1














I am getting the following error when I try to create a new object through the admin interface:




TypeError: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple'




I have the following models:



class CustomUser(AbstractUser):
def __str__(self):
return self.email

class Meta:
ordering = ('id',)
verbose_name = 'user'

class Address(models.Model):
"""Address contains information about location. Address can be own by any
kind of model."""
content_type = models.ForeignKey(
ContentType, on_delete=models.CASCADE, null=True
)
object_id = models.PositiveIntegerField(null=True)
owner = GenericForeignKey("content_type", "object_id")

CATEGORIES = Choices('billing', 'shipping')
category = models.CharField(choices=CATEGORIES, max_length=16)
address_1 = models.CharField("address line 1", max_length=128)
address_2 = models.CharField("address line 2", max_length=128, blank=True)
city = models.CharField(max_length=64)
state_province = models.CharField('state/province', max_length=128)
country = CountryField(blank_label='(select country)')
zip_code = models.CharField(max_length=10)

def __str__(self):
return (
f'{self.address_1}, {self.city}, {self.state_province}, '
f'{self.country.name}, {self.zip_code}'
)

class Meta:
ordering = ('id',)

class Company(Group):
"""An abstract base class that inherits Group."""
addresses = GenericRelation(Address)
owner = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='%(class)ss',
related_query_name='%(class)s')
logo = CloudinaryField('image',
default='your_logo_here',
null=True,
blank=True)
description = models.TextField('description', max_length=3000, blank=True)
facebook_url = models.URLField('facebook url', blank=True)
twitter_url = models.URLField('twitter url', blank=True)
instagram_url = models.URLField('instagram url', blank=True)
pinterest_url = models.URLField('pinterest url', blank=True)
portfolio_url = models.URLField('portfolio url', blank=True)
phone_number = PhoneNumberField('phone number', blank=True)

class Meta:
abstract = True
ordering = ('id',)


class Brand(Company):
"""A Brand can have multiple members."""


These are my serializers:



class CustomUserSerializer(HyperlinkedModelSerializer):
brands = HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='brand-detail'
)

class Meta:
model = CustomUser
fields = (
'url',
'username',
'email',
'brands',
)

class AddressSerializer(HyperlinkedModelSerializer):
owner = GenericRelatedField({
Brand: HyperlinkedRelatedField(
queryset=Brand.objects.all(),
view_name='brand-detail',
)
})

class Meta:
model = Address
fields = (
'url',
'category',
'address_1',
'address_2',
'city',
'state_province',
'country',
'zip_code',
'owner',
)


class BrandSerializer(HyperlinkedModelSerializer):
addresses = HyperlinkedRelatedField(many=True,
read_only=True,
view_name='address-detail')

class Meta:
model = Brand
fields = (
'url',
'owner',
'logo',
'description',
'facebook_url',
'twitter_url',
'instagram_url',
'pinterest_url',
'portfolio_url',
'phone_number',
'addresses',
)


This is how I configured the urls:



router = DefaultRouter()
router.register('users', CustomUserViewSet)
router.register('addresses', AddressViewSet)
router.register('brands', BrandViewSet)

urlpatterns = [
path('', include(router.urls)),
path('auth/', include('rest_framework.urls', namespace='rest_framework')),
]


I can access http://localhost:8000/api/addresses/, and I have the following form:



enter image description here



The problem is when I try to POST to create a new object. I am getting that error I have described, and it seems because I am not passing properly the owner (actually I have no idea how to pass an object here, should I use a JSON or how).



enter image description here



Questions:




  1. How can I solve this error because I am also trying to test the POST method, and it was when I realized this was not working?


  2. Is there any way to include the fields of a GenericForeignKey in that form?



This is my traceback:



File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in to_internal_value
39. serializer = self.get_deserializer_for_data(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in get_deserializer_for_data
75. 'Could not determine a valid serializer for value %r.' % value)

During handling of the above exception (Could not determine a valid serializer for value ''.), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in to_internal_value
488. validated_value = field.run_validation(primitive_value)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in run_validation
536. value = self.to_internal_value(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in to_internal_value
41. raise ValidationError(e)

During handling of the above exception (["Could not determine a valid serializer for value ''."]), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in get_error_detail
240. error_dict = exc_info.error_dict

During handling of the above exception ('ValidationError' object has no attribute 'error_dict'), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/mixins.py" in create
20. serializer.is_valid(raise_exception=True)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in is_valid
236. self._validated_data = self.run_validation(self.initial_data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in run_validation
434. value = self.to_internal_value(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in to_internal_value
494. errors[field.field_name] = get_error_detail(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in get_error_detail
245. for error in exc_info.error_list]

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in <listcomp>
245. for error in exc_info.error_list]

Exception Type: TypeError at /api/addresses/
Exception Value: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple'









share|improve this question
























  • Please add the full error traceback to your question.
    – Klaus D.
    Nov 23 '18 at 3:11










  • @KlausD, I just added it.
    – lmiguelvargasf
    Nov 23 '18 at 3:15






  • 1




    try to comment out the __str__() method of Address model and try again
    – JPG
    Nov 23 '18 at 3:21










  • @JPG, I did it, and I am still getting the same error. I wonder why you are suggesting that since the __str__ method is just a string representation.
    – lmiguelvargasf
    Nov 23 '18 at 3:24










  • If I do a web search for 'ImproperlyConfigured' I find a lot of results referencing 'ImproperlyConfigured' and wsgi. How are you running your server?
    – Red Cricket
    Nov 23 '18 at 4:29














1












1








1







I am getting the following error when I try to create a new object through the admin interface:




TypeError: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple'




I have the following models:



class CustomUser(AbstractUser):
def __str__(self):
return self.email

class Meta:
ordering = ('id',)
verbose_name = 'user'

class Address(models.Model):
"""Address contains information about location. Address can be own by any
kind of model."""
content_type = models.ForeignKey(
ContentType, on_delete=models.CASCADE, null=True
)
object_id = models.PositiveIntegerField(null=True)
owner = GenericForeignKey("content_type", "object_id")

CATEGORIES = Choices('billing', 'shipping')
category = models.CharField(choices=CATEGORIES, max_length=16)
address_1 = models.CharField("address line 1", max_length=128)
address_2 = models.CharField("address line 2", max_length=128, blank=True)
city = models.CharField(max_length=64)
state_province = models.CharField('state/province', max_length=128)
country = CountryField(blank_label='(select country)')
zip_code = models.CharField(max_length=10)

def __str__(self):
return (
f'{self.address_1}, {self.city}, {self.state_province}, '
f'{self.country.name}, {self.zip_code}'
)

class Meta:
ordering = ('id',)

class Company(Group):
"""An abstract base class that inherits Group."""
addresses = GenericRelation(Address)
owner = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='%(class)ss',
related_query_name='%(class)s')
logo = CloudinaryField('image',
default='your_logo_here',
null=True,
blank=True)
description = models.TextField('description', max_length=3000, blank=True)
facebook_url = models.URLField('facebook url', blank=True)
twitter_url = models.URLField('twitter url', blank=True)
instagram_url = models.URLField('instagram url', blank=True)
pinterest_url = models.URLField('pinterest url', blank=True)
portfolio_url = models.URLField('portfolio url', blank=True)
phone_number = PhoneNumberField('phone number', blank=True)

class Meta:
abstract = True
ordering = ('id',)


class Brand(Company):
"""A Brand can have multiple members."""


These are my serializers:



class CustomUserSerializer(HyperlinkedModelSerializer):
brands = HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='brand-detail'
)

class Meta:
model = CustomUser
fields = (
'url',
'username',
'email',
'brands',
)

class AddressSerializer(HyperlinkedModelSerializer):
owner = GenericRelatedField({
Brand: HyperlinkedRelatedField(
queryset=Brand.objects.all(),
view_name='brand-detail',
)
})

class Meta:
model = Address
fields = (
'url',
'category',
'address_1',
'address_2',
'city',
'state_province',
'country',
'zip_code',
'owner',
)


class BrandSerializer(HyperlinkedModelSerializer):
addresses = HyperlinkedRelatedField(many=True,
read_only=True,
view_name='address-detail')

class Meta:
model = Brand
fields = (
'url',
'owner',
'logo',
'description',
'facebook_url',
'twitter_url',
'instagram_url',
'pinterest_url',
'portfolio_url',
'phone_number',
'addresses',
)


This is how I configured the urls:



router = DefaultRouter()
router.register('users', CustomUserViewSet)
router.register('addresses', AddressViewSet)
router.register('brands', BrandViewSet)

urlpatterns = [
path('', include(router.urls)),
path('auth/', include('rest_framework.urls', namespace='rest_framework')),
]


I can access http://localhost:8000/api/addresses/, and I have the following form:



enter image description here



The problem is when I try to POST to create a new object. I am getting that error I have described, and it seems because I am not passing properly the owner (actually I have no idea how to pass an object here, should I use a JSON or how).



enter image description here



Questions:




  1. How can I solve this error because I am also trying to test the POST method, and it was when I realized this was not working?


  2. Is there any way to include the fields of a GenericForeignKey in that form?



This is my traceback:



File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in to_internal_value
39. serializer = self.get_deserializer_for_data(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in get_deserializer_for_data
75. 'Could not determine a valid serializer for value %r.' % value)

During handling of the above exception (Could not determine a valid serializer for value ''.), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in to_internal_value
488. validated_value = field.run_validation(primitive_value)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in run_validation
536. value = self.to_internal_value(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in to_internal_value
41. raise ValidationError(e)

During handling of the above exception (["Could not determine a valid serializer for value ''."]), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in get_error_detail
240. error_dict = exc_info.error_dict

During handling of the above exception ('ValidationError' object has no attribute 'error_dict'), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/mixins.py" in create
20. serializer.is_valid(raise_exception=True)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in is_valid
236. self._validated_data = self.run_validation(self.initial_data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in run_validation
434. value = self.to_internal_value(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in to_internal_value
494. errors[field.field_name] = get_error_detail(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in get_error_detail
245. for error in exc_info.error_list]

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in <listcomp>
245. for error in exc_info.error_list]

Exception Type: TypeError at /api/addresses/
Exception Value: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple'









share|improve this question















I am getting the following error when I try to create a new object through the admin interface:




TypeError: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple'




I have the following models:



class CustomUser(AbstractUser):
def __str__(self):
return self.email

class Meta:
ordering = ('id',)
verbose_name = 'user'

class Address(models.Model):
"""Address contains information about location. Address can be own by any
kind of model."""
content_type = models.ForeignKey(
ContentType, on_delete=models.CASCADE, null=True
)
object_id = models.PositiveIntegerField(null=True)
owner = GenericForeignKey("content_type", "object_id")

CATEGORIES = Choices('billing', 'shipping')
category = models.CharField(choices=CATEGORIES, max_length=16)
address_1 = models.CharField("address line 1", max_length=128)
address_2 = models.CharField("address line 2", max_length=128, blank=True)
city = models.CharField(max_length=64)
state_province = models.CharField('state/province', max_length=128)
country = CountryField(blank_label='(select country)')
zip_code = models.CharField(max_length=10)

def __str__(self):
return (
f'{self.address_1}, {self.city}, {self.state_province}, '
f'{self.country.name}, {self.zip_code}'
)

class Meta:
ordering = ('id',)

class Company(Group):
"""An abstract base class that inherits Group."""
addresses = GenericRelation(Address)
owner = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='%(class)ss',
related_query_name='%(class)s')
logo = CloudinaryField('image',
default='your_logo_here',
null=True,
blank=True)
description = models.TextField('description', max_length=3000, blank=True)
facebook_url = models.URLField('facebook url', blank=True)
twitter_url = models.URLField('twitter url', blank=True)
instagram_url = models.URLField('instagram url', blank=True)
pinterest_url = models.URLField('pinterest url', blank=True)
portfolio_url = models.URLField('portfolio url', blank=True)
phone_number = PhoneNumberField('phone number', blank=True)

class Meta:
abstract = True
ordering = ('id',)


class Brand(Company):
"""A Brand can have multiple members."""


These are my serializers:



class CustomUserSerializer(HyperlinkedModelSerializer):
brands = HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='brand-detail'
)

class Meta:
model = CustomUser
fields = (
'url',
'username',
'email',
'brands',
)

class AddressSerializer(HyperlinkedModelSerializer):
owner = GenericRelatedField({
Brand: HyperlinkedRelatedField(
queryset=Brand.objects.all(),
view_name='brand-detail',
)
})

class Meta:
model = Address
fields = (
'url',
'category',
'address_1',
'address_2',
'city',
'state_province',
'country',
'zip_code',
'owner',
)


class BrandSerializer(HyperlinkedModelSerializer):
addresses = HyperlinkedRelatedField(many=True,
read_only=True,
view_name='address-detail')

class Meta:
model = Brand
fields = (
'url',
'owner',
'logo',
'description',
'facebook_url',
'twitter_url',
'instagram_url',
'pinterest_url',
'portfolio_url',
'phone_number',
'addresses',
)


This is how I configured the urls:



router = DefaultRouter()
router.register('users', CustomUserViewSet)
router.register('addresses', AddressViewSet)
router.register('brands', BrandViewSet)

urlpatterns = [
path('', include(router.urls)),
path('auth/', include('rest_framework.urls', namespace='rest_framework')),
]


I can access http://localhost:8000/api/addresses/, and I have the following form:



enter image description here



The problem is when I try to POST to create a new object. I am getting that error I have described, and it seems because I am not passing properly the owner (actually I have no idea how to pass an object here, should I use a JSON or how).



enter image description here



Questions:




  1. How can I solve this error because I am also trying to test the POST method, and it was when I realized this was not working?


  2. Is there any way to include the fields of a GenericForeignKey in that form?



This is my traceback:



File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in to_internal_value
39. serializer = self.get_deserializer_for_data(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in get_deserializer_for_data
75. 'Could not determine a valid serializer for value %r.' % value)

During handling of the above exception (Could not determine a valid serializer for value ''.), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in to_internal_value
488. validated_value = field.run_validation(primitive_value)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in run_validation
536. value = self.to_internal_value(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/generic_relations/serializers.py" in to_internal_value
41. raise ValidationError(e)

During handling of the above exception (["Could not determine a valid serializer for value ''."]), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in get_error_detail
240. error_dict = exc_info.error_dict

During handling of the above exception ('ValidationError' object has no attribute 'error_dict'), another exception occurred:

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/mixins.py" in create
20. serializer.is_valid(raise_exception=True)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in is_valid
236. self._validated_data = self.run_validation(self.initial_data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in run_validation
434. value = self.to_internal_value(data)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/serializers.py" in to_internal_value
494. errors[field.field_name] = get_error_detail(exc)

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in get_error_detail
245. for error in exc_info.error_list]

File "/Users/user/.local/share/virtualenvs/na-ERB0uoVd/lib/python3.7/site-packages/rest_framework/fields.py" in <listcomp>
245. for error in exc_info.error_list]

Exception Type: TypeError at /api/addresses/
Exception Value: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple'






python django django-rest-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 3:15

























asked Nov 23 '18 at 3:06









lmiguelvargasf

11.2k1080103




11.2k1080103












  • Please add the full error traceback to your question.
    – Klaus D.
    Nov 23 '18 at 3:11










  • @KlausD, I just added it.
    – lmiguelvargasf
    Nov 23 '18 at 3:15






  • 1




    try to comment out the __str__() method of Address model and try again
    – JPG
    Nov 23 '18 at 3:21










  • @JPG, I did it, and I am still getting the same error. I wonder why you are suggesting that since the __str__ method is just a string representation.
    – lmiguelvargasf
    Nov 23 '18 at 3:24










  • If I do a web search for 'ImproperlyConfigured' I find a lot of results referencing 'ImproperlyConfigured' and wsgi. How are you running your server?
    – Red Cricket
    Nov 23 '18 at 4:29


















  • Please add the full error traceback to your question.
    – Klaus D.
    Nov 23 '18 at 3:11










  • @KlausD, I just added it.
    – lmiguelvargasf
    Nov 23 '18 at 3:15






  • 1




    try to comment out the __str__() method of Address model and try again
    – JPG
    Nov 23 '18 at 3:21










  • @JPG, I did it, and I am still getting the same error. I wonder why you are suggesting that since the __str__ method is just a string representation.
    – lmiguelvargasf
    Nov 23 '18 at 3:24










  • If I do a web search for 'ImproperlyConfigured' I find a lot of results referencing 'ImproperlyConfigured' and wsgi. How are you running your server?
    – Red Cricket
    Nov 23 '18 at 4:29
















Please add the full error traceback to your question.
– Klaus D.
Nov 23 '18 at 3:11




Please add the full error traceback to your question.
– Klaus D.
Nov 23 '18 at 3:11












@KlausD, I just added it.
– lmiguelvargasf
Nov 23 '18 at 3:15




@KlausD, I just added it.
– lmiguelvargasf
Nov 23 '18 at 3:15




1




1




try to comment out the __str__() method of Address model and try again
– JPG
Nov 23 '18 at 3:21




try to comment out the __str__() method of Address model and try again
– JPG
Nov 23 '18 at 3:21












@JPG, I did it, and I am still getting the same error. I wonder why you are suggesting that since the __str__ method is just a string representation.
– lmiguelvargasf
Nov 23 '18 at 3:24




@JPG, I did it, and I am still getting the same error. I wonder why you are suggesting that since the __str__ method is just a string representation.
– lmiguelvargasf
Nov 23 '18 at 3:24












If I do a web search for 'ImproperlyConfigured' I find a lot of results referencing 'ImproperlyConfigured' and wsgi. How are you running your server?
– Red Cricket
Nov 23 '18 at 4:29




If I do a web search for 'ImproperlyConfigured' I find a lot of results referencing 'ImproperlyConfigured' and wsgi. How are you running your server?
– Red Cricket
Nov 23 '18 at 4:29












1 Answer
1






active

oldest

votes


















0














If add read_only=True like the following:



owner = GenericRelatedField({
Brand: HyperlinkedRelatedField(
queryset=Brand.objects.all(),
view_name='brand-detail',
)
}, read_only=True)


the error will disappear. But then you need to write your
own create() method in the same serializer with serialization of owner to account for how
you would like to save owner.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440189%2fdrf-cannot-post-or-create-a-new-object-through-admin-interface%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    If add read_only=True like the following:



    owner = GenericRelatedField({
    Brand: HyperlinkedRelatedField(
    queryset=Brand.objects.all(),
    view_name='brand-detail',
    )
    }, read_only=True)


    the error will disappear. But then you need to write your
    own create() method in the same serializer with serialization of owner to account for how
    you would like to save owner.






    share|improve this answer


























      0














      If add read_only=True like the following:



      owner = GenericRelatedField({
      Brand: HyperlinkedRelatedField(
      queryset=Brand.objects.all(),
      view_name='brand-detail',
      )
      }, read_only=True)


      the error will disappear. But then you need to write your
      own create() method in the same serializer with serialization of owner to account for how
      you would like to save owner.






      share|improve this answer
























        0












        0








        0






        If add read_only=True like the following:



        owner = GenericRelatedField({
        Brand: HyperlinkedRelatedField(
        queryset=Brand.objects.all(),
        view_name='brand-detail',
        )
        }, read_only=True)


        the error will disappear. But then you need to write your
        own create() method in the same serializer with serialization of owner to account for how
        you would like to save owner.






        share|improve this answer












        If add read_only=True like the following:



        owner = GenericRelatedField({
        Brand: HyperlinkedRelatedField(
        queryset=Brand.objects.all(),
        view_name='brand-detail',
        )
        }, read_only=True)


        the error will disappear. But then you need to write your
        own create() method in the same serializer with serialization of owner to account for how
        you would like to save owner.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 20 '18 at 16:41









        Hanna Howz

        313




        313






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440189%2fdrf-cannot-post-or-create-a-new-object-through-admin-interface%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Berounka

            Sphinx de Gizeh

            Different font size/position of beamer's navigation symbols template's content depending on regular/plain...