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 ;)
Related
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.
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})
I am using Django User model for one of the select field.
However i am not able to pass only users linked to a commmon organisation/company.
I have a onetoone profile linking for each user. This one to onetoone model is again linked to organisation model.
Now need a form where select field should have users linked to organisation model.
Here is my form.py:
class taskaddform(forms.ModelForm):
def __init__(self,user, *args, **kwargs):
self.user = kwargs.pop('user', None)
self.request = kwargs.pop('request', None)
super(taskaddform, self).__init__(*args, **kwargs)
self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
class Meta:
model=tasktable
fields=('task','assigned_to','discription','documents',)
views.py:
#login_required
def taskadd(request):
if request.method=='POST':
form=taskaddform(request.POST,request.FILES,request.user)
if form.is_valid():
new_form=form.save(commit=False)
new_form.created_by=request.user
new_form.company=request.user.company.entity
new_form.save()
return HttpResponseRedirect(reverse('taskadd'),messages.add_message(request, messages.SUCCESS,'Task added succesfully.'))
else:
form=taskaddform(request.user)
return render(request,'taskadd.html',{'form':form})
Error Log:
Request Method: GET
Request URL: http://127.0.0.1:8000/task/taskadd/
Django Version: 1.10
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'user'
traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/task/taskadd/
Django Version: 1.10
Python Version: 2.7.10
Installed Applications:
('invoice',
'support',
'task',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'widget_tweaks')
Installed Middleware:
('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',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/Users/pulkitsharma/Documents/workspace1/tiktant/task/views.py" in taskadd
38. form=taskaddform(request.user)
File "/Users/pulkitsharma/Documents/workspace1/tiktant/task/forms.py" in __init__
11. self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
Exception Type: AttributeError at /task/taskadd/
Exception Value: 'NoneType' object has no attribute 'user'
Updated views.py.
#login_required
def taskadd(request):
if request.method=='POST':
form=taskaddform(request, request.POST,request.FILES,request.user)
if form.is_valid():
new_form=form.save(commit=False)
new_form.created_by=request.user
new_form.company=request.user.company.entity
new_form.save()
return HttpResponseRedirect(reverse('taskadd'),messages.add_message(request, messages.SUCCESS,'Task added succesfully.'))
else:
form=taskaddform(request)
return render(request,'taskadd.html',{'form':form})
and in your forms.py --
class taskaddform(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
self.request = request
super(taskaddform, self).__init__(request, *args, **kwargs)
self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
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)
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.