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

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.

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)

How to access related object id in DeleteView

I have a DeleteView. In which i want to access related object id. When user make POST request.
View:
class DeletePacketView(LoginRequiredMixin, DeleteView):
model = Packet
template_name = DELETE_PACKET_TEMPLATE
def get_success_url(self):
# Return to customer home
return reverse('myapp:view_customer',
kwargs={'pk': self.object.customer.id
}
)
def post(self, request, *args, **kwargs):
html = """
<html>
<head>
<script>window.onunload = refreshParent; function refreshParent() {
window.opener.location.href=%s;
}
</script>
</head>
<body>
<h1>object deleted successfully</h1>
<button type="button" onclick="window.close()">OK</button>
</body>
</html>
""" % reverse('myapp:view_customer',
kwargs={'pk': self.object.customer.id
}
)
super(DeletePacketView, self).post(request, *args, **kwargs)
return HttpResponse(html)
But I am getting error when I try to submit form.
Traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/delete/packet/96/
Django Version: 1.7
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp')
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',
'django.contrib.admindocs.middleware.XViewMiddleware')
Traceback:
File "C:\Users\PrImE\envs\ge\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\PrImE\envs\ge\lib\site-packages\django\views\generic\base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "C:\Users\PrImE\envs\ge\lib\site-packages\django\utils\decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "C:\Users\PrImE\envs\ge\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "C:\Users\PrImE\envs\ge\lib\site-packages\django\utils\decorators.py" in bound_func
23. return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
File "C:\Users\PrImE\envs\ge\lib\site-packages\django\views\generic\base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "C:\Users\PrImE\workspace\myproject\repo\dev\myproject\myproject\myapp\views\delete_views\delete_packet_view.py" in post
66. kwargs={'pk': self.object.customer.id
Exception Type: AttributeError at /delete/packet/96/
Exception Value: 'DeletePacketView' object has no attribute 'object'
I am getting this error because the object is deleted. But get_success_url method works fine it is redirecting user to the customer page why not post method is working and how do I access self.object.customer.id???
def post(self, request, *args, **kwargs):
self.object = self.get_object() #Add this to load the object
#Your code
return HttpResponse(html)
PS: Please use Django template ;)

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

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.