Django - AttributeError: 'Fichas' object has no attribute 'update' - django

I have a serializer that verify if some fields are empty or not. If a field is empty all works perfectly, but if all the fields are correct I obtain and AttributeError: 'Fichas' object has no attribute 'update'.
This is the view and the serializer:
views.py
class PublicarFichaViewSet(APIView):
permission_classes = (IsAuthenticated, GroupPermission)
def get_object(self, pk):
try:
return Fichas.objects.get(pk=pk)
except:
raise Http404
def get(self, request, pk, format=None):
ficha = self.get_object(pk)
serializer = PublicarFichaSerializer(ficha)
return Response(serializer.data)
def put(self, request, pk, format=None):
ficha = self.get_object(pk)
serializer = PublicarFichaSerializer(ficha, data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.py
class PublicarFichaSerializer(serializers.Serializer):
Centro_responsable = serializers.CharField(required=True, max_length=64)
Autor_de_la_ficha = serializers.CharField(required=True, max_length=64)
Correo_electronico_del_autor_de_la_ficha = serializers.EmailField(required=True)
Autor_del_caso_de_estudio = serializers.CharField(required=True, max_length=64)
Correo_electronico_del_autor_del_caso_de_estudio = serializers.EmailField(required=True)
Tutor = serializers.CharField(required=True, max_length=64)
Correo_electronico_del_tutor = serializers.EmailField(required=True)
Fecha_de_tutela = serializers.DateField(required=True)
Titulo = serializers.CharField(required=True, max_length=64)
Tipo_de_objeto_u_obra_por_su_funcion = serializers.CharField(required=True, max_length=64)
Plano_de_situacion = serializers.CharField(required=True, max_length=64)
Fecha_de_validez_legal = serializers.DateField(required=True)
Ficha_publicada = serializers.BooleanField()
def validate_Ficha_publicada(self, attrs, source):
if not attrs['Ficha_publicada']:
raise serializers.ValidationError("Ficha no publicada")
return attrs
EDIT: The traceback
Environment:
Request Method: POST
Request URL: http://localhost:8000/publicarficha/1/
Django Version: 1.6.5
Python Version: 2.7.6
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'phi_catalogo',
'rest_framework.authtoken',
'django_evolution',
'django.contrib.admin',
'multiselectfield',
'django_extensions',
'pytz')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware')
Traceback:
File "/Users/jian/phi/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/jian/phi/env/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/Users/jian/phi/env/lib/python2.7/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/Users/jian/phi/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
403. response = self.handle_exception(exc)
File "/Users/jian/phi/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
400. response = handler(request, *args, **kwargs)
File "/Users/jian/phi/backend/phi_catalogo/views.py" in put
148. if serializer.is_valid():
File "/Users/jian/phi/env/lib/python2.7/site-packages/rest_framework/serializers.py" in is_valid
550. return not self.errors
File "/Users/jian/phi/env/lib/python2.7/site-packages/rest_framework/serializers.py" in errors
542. ret = self.from_native(data, files)
File "/Users/jian/phi/env/lib/python2.7/site-packages/rest_framework/serializers.py" in from_native
375. return self.restore_object(attrs, instance=getattr(self, 'object', None))
File "/Users/jian/phi/env/lib/python2.7/site-packages/rest_framework/serializers.py" in restore_object
335. instance.update(attrs)
Exception Type: AttributeError at /publicarficha/1/
Exception Value: 'Fichas' object has no attribute 'update'

Try using a ModelSerializer instead of the Serializer as a super class.

Related

Django RestFramework _'NoneType' object has no attribute 'token'

I have this Serializer class for my User model:
serializers.py
class UserCreateSerializer(serializers.ModelSerializer):
"""User django serilization"""
key = serializers.StringRelatedField(source='key.token', read_only=True)
class Meta:
model = User
fields = ['phonenumber','id','email', 'username', 'key' ]
def create(self, validate_data):
user = User(**validate_data)
user.save()
return user
and this views.py
class UserListView(ListAPIView):
'''listing all users'''
permission_classes = (AllowAny,)
pagination_class = SmallPagination
throttle_classes = (UserRateThrottle, AnonRateThrottle,)
serializer_class = UserCreateSerializer
queryset = User.objects.all()
filter_backends = (filters.SearchFilter,)
search_fields = ('username', 'phonenumber', 'email')
I include 'rest_framework.authtoken', in my settings.py
and made a signal for Tokens from django Restframe work documentation.
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
urls.py
urlpatterns = [
re_path(r'^users/$', views.UserListView.as_view(), name='user-list'),]
so when I try to load my users List this error occurs :
'NoneType' object has no attribute 'token'
for attr in attrs:
try:
if isinstance(instance, collections.Mapping):
instance = instance[attr]
else:
instance = getattr(instance, attr) ...
except ObjectDoesNotExist:
return None
if is_simple_callable(instance):
try:
instance = instance()
except (AttributeError, KeyError) as exc:
....
the error location is from :
/backend/env/lib/python3.6/site-packages/rest_framework/fields.py in
get_attribute
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/api/users/create/
Django Version: 2.0
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
'main.apps.MainConfig',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'stdimage',
'rest_framework.authtoken',
'blog',
'taggit',
'taggit_serializer',
'django.contrib.sites',
'corsheaders',
'webpack_loader']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
494. response = self.handle_exception(exc)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
454. self.raise_uncaught_exception(exc)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
491. response = handler(request, *args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/mixins.py" in create
22. headers = self.get_success_headers(serializer.data)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data
537. ret = super(Serializer, self).data
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
491. attribute = field.get_attribute(instance)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/relations.py" in get_attribute
177. return get_attribute(instance, self.source_attrs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/fields.py" in get_attribute
100. instance = getattr(instance, attr)
Exception Type: AttributeError at /api/users/create/
Exception Value: 'NoneType' object has no attribute 'token'
authtoken model has related_name=auth_token to user models. So if you need to get token from user you should use auth_token.key:
key = serializers.StringRelatedField(source='auth_token.token', read_only=True)
I also got stuck in this error. But luckily i found the mistake i was doing.
I know its already been some time now. Still answering this question for newbies stuck in such silly error.
If we have to use Token model we have to mention the same in Installed Apps in settings.py file
'rest_framework.authtoken'
After that do migrate and you will see creation of new tables in the db.
Afterwards you can query the database like this...
Token.objects.all()
and you are good to go now.
Happy coding.

Django SingleObjectMixin

I try to create simple SingleObjectMixin class, later i will use it with render_json_response() for providing AJAX data streaming. The main goal is basket for online store. So there is simple test class:
class Test(SingleObjectMixin):
model = GoodsDescription
slug_url_kwarg = 'test_id'
slug_field = 'artikul' # pk field in 'GoodsDescription' table
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return render(request, 'temp_code.html', {'msg':self.object.name})
So the mistake is:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/test%3D5/
Django Version: 1.10.5
Python Version: 2.7.12
Installed Applications:
['alexbase',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'easy_thumbnails']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/.local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
Exception Type: TypeError at /admin/test=5/
Exception Value: object() takes no parameters
SingleObjectMixin is, well, a mixin. It's not a full view you can inherit from. You should use DetailView instead.
URL conf string should be right:
url(r'^(?:test=(?P<test_id>\d+))/$', login_required(views.TestAJAXView), name='temp_code'),
Finally, i want to use class like this:
class TestAJAXView(JSONResponseMixin, SingleObjectMixin):
model = GoodsDescription
slug_url_kwarg = 'test_id'
slug_field = 'artikul'
json_dumps_kwargs = {"indent": 2}
def get(self, request, *args, **kwargs):
self.object = self.get_object()
context_dict = {
"category": self.object.category,
"name": self.object.name
}
return self.render_json_response(context_dict)
But exception was raised, so i tried this:
class Test(SingleObjectMixin):
model = GoodsDescription
slug_url_kwarg = 'test_id'
slug_field = 'artikul' # pk field in 'GoodsDescription' table
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return render(request, 'temp_code.html', {'msg':self.object.name})

django how to add a MinLengthValidator validator in a form

I have a search form and I want to validate that the input 'seach_word' has at least 4 letters. I'm getting this error when I'm trying to validate my forms
The response content must be rendered before it can be iterated over.
#views.py
class SearchFormView(FormView):
form_class = PostSearchForm
template_name = 'lineup/post_search.html'
def form_valid(self, form):
schWord = form.cleaned_data['search_word']
search_type = form.cleaned_data['search_type']
context = {}
if search_type == 'store':
post_list = Store.objects.filter(
Q(cie_name__icontains=schWord)).distinct()
context['object_type'] = 'store'
context['object_list'] = post_list
if search_type == 'city':
post_list = Address.objects.filter(
Q(city__icontains=schWord)).distinct()
context['object_type'] = 'city'
context['object_list'] = post_list
context['form'] = form
context['search_term'] = schWord
return render(self.request, self.template_name, context)
def form_invalid(self, form):
schWord = form.cleaned_data['search_word']
messages.add_message(
self.request, messages.WARNING, _('Please correct this...'))
context = super(SearchFormView, self).form_invalid(form)
return render(self.request, self.template_name, context)
content of forms.py
#forms.py
class PostSearchForm(forms.Form):
SEARCH_TYPE_CHOICES = (
('city', 'city'),
('store', 'store'),
('product', 'product'),
)
search_type = forms.ChoiceField(choices=SEARCH_TYPE_CHOICES, required=True)
search_word = forms.CharField(label='Search Word',
validators=[MinLengthValidator(4)], required=True)
'''
def clean_search_word(self):
cd = self.cleaned_data
if len(cd['search_word']) < 4:
raise forms.ValidationError('too short.')
return cd['search_word']
'''
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Fieldset(
'',
Field('search_type', css_class='span6'),
Field('search_word', css_class='span6'),
),
FormActions(
Submit('submit', 'Go', css_class='btn btn-primary')
)
)
super(PostSearchForm, self).__init__(*args, **kwargs)
tracenack
Environment:
Request Method: POST
Request URL: http://localhost:8000/search/
Django Version: 1.10.3
Python Version: 3.5.2
Installed Applications:
['grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'debug_toolbar',
'stripe',
'vote',
'django_messages',
'pinax.notifications',
'admin_honeypot',
'easy_thumbnails',
'django_extensions',
'crispy_forms',
'datetimewidget',
'lineup',
'allauth',
'allauth.account',
'allauth.socialaccount']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.locale.LocaleMiddleware']
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/edit.py" in post
185. return self.form_invalid(form)
File "/home/laptopguy/Documents/lineupNovember/lineup/views.py" in form_invalid
58. return render(self.request, self.template_name, context)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
68. return template.render(context, request)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/backends/django.py" in render
64. context = make_context(context, request, autoescape=self.backend.engine.autoescape)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in make_context
267. context.push(original_context)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in push
59. return ContextDict(self, *dicts, **kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in __init__
18. super(ContextDict, self).__init__(*args, **kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/response.py" in __iter__
123. 'The response content must be rendered before it can be iterated over.'
Exception Type: ContentNotRenderedError at /search/
Exception Value: The response content must be rendered before it can be iterated over.
The traceback shows that your problem is in your form_invalid method. You are capturing the result from the superclass call as context, and passing it into the render function. But the superclass method returns a response, not a context - it has already rendered the template for you, you just need to return it.
def form_invalid(self, form):
schWord = form.cleaned_data['search_word']
messages.add_message(
self.request, messages.WARNING, _('Please correct this...'))
return super(SearchFormView, self).form_invalid(form)

Extending django User django-rest_framework gives me KeyError

I'm new to django rest_framework and have and issue, i've extended the auth_user as per the django docs, but is giving me a hard time...
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
national_id = models.CharField(max_length=10, blank=True, null=True)
mobile = models.CharField(max_length=10)
pin = models.IntegerField()
pattern = models.IntegerField(blank=True, null=True)
fingerprint = models.CharField(max_length=45, blank=True, null=True)
class Meta:
managed = False
db_table = 'user_profile'
serializers.py
class UserSerializer(serializers.ModelSerializer):
national_id = serializers.CharField(source='userprofile.national_id', allow_null=True, required=False)
mobile = serializers.CharField(source='userprofile.mobile')
pin = serializers.IntegerField(source='userprofile.pin', write_only=True)
pattern = serializers.IntegerField(source='userprofile.pattern', write_only=True)
fingerprint = serializers.CharField(source='userprofile.fingerprint', write_only=True, allow_null=True, required=False)
class Meta:
model = User
fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email', 'national_id', 'mobile', 'pin', 'pattern', 'fingerprint')
write_only_fields = ('password',)
read_only_fields = ('last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined')
def create(self, validated_data):
user = User(
username=validated_data['username'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.save()
userprofile = UserProfile(
user=user,
national_id=validated_data['national_id'],
mobile=validated_data['mobile'],
pin=validated_data['pin'],
pattern=validated_data['pattern'],
fingerprint=validated_data['fingerprint'],
)
userprofile.save()
return user
views.py
class UserView(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = get_user_model().objects
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.routers import DefaultRouter
from restful.views import *
router = DefaultRouter()
router.register(r'availability-notification', AvailabiltyNotificationView)
router.register(r'bank', BankView)
router.register(r'recipient', RecipientView)
router.register(r'user', UserView)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', admin.site.urls),
but keeps giving me:
Environment:
Request Method: POST Request URL: http://localhost:8000/user/
Django Version: 1.10.2 Python Version: 3.5.2 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'restful'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\core\handlers\exception.py"
in inner
39. response = get_response(request)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\core\handlers\base.py"
in _get_response
187. response = self.process_exception_by_middleware(e, request)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\core\handlers\base.py"
in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\views\decorators\csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\viewsets.py"
in view
87. return self.dispatch(request, *args, **kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\views.py"
in dispatch
474. response = self.handle_exception(exc)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\views.py"
in handle_exception
434. self.raise_uncaught_exception(exc)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\views.py"
in dispatch
471. response = handler(request, *args, **kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\mixins.py"
in create
21. self.perform_create(serializer)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\mixins.py"
in perform_create
26. serializer.save()
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\serializers.py"
in save
192. self.instance = self.create(validated_data)
File "C:\Users\echavez\Source\ws\restful\serializers.py" in create
45. national_id=validated_data['national_id'],
Exception Type: KeyError at /user/ Exception Value: 'national_id'
I know this is a newbie question, but, i really need help!
Thanks in advance.
You are getting profile data in wrong way.
validated_data is a dictionary of user and profile data which you are going to save separately.
Get it like this.
profile_data = validated_data.pop('userprofile')
Note that we poped userprofile data so now you have left only user data in validated_data. So a complete flow will look like below
profile_data = validated_data.pop('userprofile')
user = User.objects.create(**validated_data)
UserProfile.objects.create(user=user, **profile_data)
return user
Take a look here
http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations
Thanks to LaL ZaDa who pointed me in the right direction, my code finally looks like this and works:
serializers.py
class UserSerializer(serializers.ModelSerializer):
national_id = serializers.CharField(source='userprofile.national_id', allow_null=True, required=False)
mobile = serializers.CharField(source='userprofile.mobile')
pin = serializers.IntegerField(source='userprofile.pin', write_only=True)
pattern = serializers.IntegerField(source='userprofile.pattern', write_only=True)
fingerprint = serializers.CharField(source='userprofile.fingerprint', write_only=True, allow_null=True, required=False)
bank_accounts = UserBankAccountSerializer(many=True)
class Meta:
model = User
fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email', 'national_id', 'mobile', 'pin', 'pattern', 'fingerprint', 'bank_accounts')
write_only_fields = ('password',)
read_only_fields = ('last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined')
def create(self, validated_data):
user = User(
username=validated_data['username'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.save()
profile_data = validated_data.pop('userprofile')
userprofile = UserProfile(
user=user,
national_id=profile_data['national_id'],
mobile=profile_data['mobile'],
pin=profile_data['pin'],
pattern=profile_data['pattern'],
fingerprint=profile_data['fingerprint'],
)
userprofile.save()
return user
Cause, this is not exactly a nested model (the bank_accounts, are nested), so when i do like this:
profile_data = validated_data.pop('userprofile')
user = User.objects.create(**validated_data)
UserProfile.objects.create(user=user, **userprofile)
return user
was throwing me...
Environment:
Request Method: POST Request URL: http://localhost:8000/user/
Django Version: 1.10.2 Python Version: 3.5.2 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'restful'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\core\handlers\exception.py"
in inner
39. response = get_response(request)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\core\handlers\base.py"
in _get_response
187. response = self.process_exception_by_middleware(e, request)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\core\handlers\base.py"
in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\views\decorators\csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\viewsets.py"
in view
87. return self.dispatch(request, *args, **kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\views.py"
in dispatch
474. response = self.handle_exception(exc)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\views.py"
in handle_exception
434. self.raise_uncaught_exception(exc)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\views.py"
in dispatch
471. response = handler(request, *args, **kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\mixins.py"
in create
21. self.perform_create(serializer)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\mixins.py"
in perform_create
26. serializer.save()
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\rest_framework\serializers.py"
in save
192. self.instance = self.create(validated_data)
File "C:\Users\echavez\Source\ws\restful\serializers.py" in create
49. user = User.objects.create(**validated_data)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\manager.py"
in manager_method
85. return getattr(self.get_queryset(), name)(*args, **kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\query.py"
in create
397. obj = self.model(**kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\contrib\auth\base_user.py"
in init
68. super(AbstractBaseUser, self).init(*args, **kwargs)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\base.py"
in init
550. setattr(self, prop, kwargs[prop])
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\fields\related_descriptors.py"
in set
500. manager.set(value)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\fields\related_descriptors.py"
in set
687. self.add(*objs, bulk=bulk)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\fields\related_descriptors.py"
in add
597. self.field.name: self.instance,
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\query.py"
in update
637. rows = query.get_compiler(self.db).execute_sql(CURSOR)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\sql\compiler.py"
in execute_sql
1148. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\sql\compiler.py"
in execute_sql
824. sql, params = self.as_sql()
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\sql\compiler.py"
in as_sql
1102. val.prepare_database_save(field),
File
"C:\Users\echavez\Envs\YEiPii\lib\site-packages\django\db\models\base.py"
in prepare_database_save
999. raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self)
Exception Type: ValueError at /user/ Exception Value: Unsaved model
instance cannot be used in an ORM query.
Now i'll finish the create to include the nested one and the update and delete...
Thanks LaL

Error when attempting to take a quiz in django-quiz app

When I tried to take a quiz, it gives me that error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/quiz/testing-your-quiz/take/
Django Version: 1.9.4
Python Version: 3.5.1
Installed Applications:
['student',
'module_content',
'announcement',
'module_progress',
'coverage',
'quiz',
'multichoice',
'true_false',
'essay',
'todo',
'bootstrapform',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites']
Installed 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']
Traceback:
File "C:\Users\Randy\Envs\website\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Randy\Envs\website\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Randy\Envs\website\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Randy\Envs\website\tsl\quiz\views.py" in dispatch
155. return super(QuizTake, self).dispatch(request, *args, **kwargs)
File "C:\Users\Randy\Envs\website\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Users\Randy\Envs\website\lib\site-packages\django\views\generic\edit.py" in get
213. return self.render_to_response(self.get_context_data())
File "C:\Users\Randy\Envs\website\tsl\quiz\views.py" in get_context_data
190. context = super(QuizTake, self).get_context_data(**kwargs)
File "C:\Users\Randy\Envs\website\lib\site-packages\django\views\generic\edit.py" in get_context_data
122. kwargs['form'] = self.get_form()
File "C:\Users\Randy\Envs\website\lib\site-packages\django\views\generic\edit.py" in get_form_with_form_class
35. return get_form(self, form_class=form_class)
File "C:\Users\Randy\Envs\website\tsl\quiz\views.py" in get_form
168. return form_class(**self.get_form_kwargs())
File "C:\Users\Randy\Envs\website\tsl\quiz\forms.py" in __init__
8. choice_list = [x for x in question.get_answers_list()]
Exception Type: AttributeError at /quiz/testing-your-quiz/take/
Exception Value: 'bool' object has no attribute 'get_answers_list'
The problem is that I try to undo all changes done to the coding but it still gives me that error and I don't know why.
Here are the related files concerned by this error:
class QuizTake(FormView):
form_class = QuestionForm
template_name = 'question.html'
def dispatch(self, request, *args, **kwargs):
self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name'])
if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'):
raise PermissionDenied
self.logged_in_user = self.request.user.is_authenticated()
if self.logged_in_user:
self.sitting = Sitting.objects.user_sitting(request.user,
self.quiz)
else:
self.sitting = self.anon_load_sitting()
if self.sitting is False:
return render(request, 'single_complete.html')
return super(QuizTake, self).dispatch(request, *args, **kwargs)
Another snippet:
def get_context_data(self, **kwargs):
context = super(QuizTake, self).get_context_data(**kwargs)
context['question'] = self.question
context['quiz'] = self.quiz
if hasattr(self, 'previous'):
context['previous'] = self.previous
if hasattr(self, 'progress'):
context['progress'] = self.progress
return context
And the forms.py:
from django import forms
from django.forms.widgets import RadioSelect, Textarea
class QuestionForm(forms.Form):
def __init__(self, question, *args, **kwargs):
super(QuestionForm, self).__init__(*args, **kwargs)
choice_list = [x for x in question.get_answers_list()]
self.fields["answers"] = forms.ChoiceField(choices=choice_list,
widget=RadioSelect)
class EssayForm(forms.Form):
def __init__(self, question, *args, **kwargs):
super(EssayForm, self).__init__(*args, **kwargs)
self.fields["answers"] = forms.CharField(
widget=Textarea(attrs={'style': 'width:100%'}))
Can someone help me please? I seriously don't know how to fix it.
You need to pass a question to the QuestionForm when you instantiate it. This should probably be done in the get_form_kwargs method of your view.