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})
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 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.
I would like to redirect the success_url to the same form after the form was submitted and valid. Online I found a description of a solution, however this solution and my other code option generate the same error message.
Exception Value: 'NoneType' object has no attribute 'find'
urls.py
url(r'^pictures/(?P<id>\d+)/$', PictureUpload.as_view(), name='picture_upload'),
...
1st views.py option
copies the existing link path
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = lambda self: self.request.path
2nd views.py option
recreates the link path based on the reverse url plus the id
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = reverse('picture_upload',
kwargs={'id': self.kwargs.get('id', None)})
Both options end up in the same traceback.
Request Method: POST
Request URL: http://127.0.0.1:8000/pictures/2/
Django Version: 1.5.1
Python Version: 2.7.1
Installed Applications:
('django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'picture',
'debug_toolbar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in post
165. return self.form_valid(form)
File "/Users/Development/project/apps/picture/picture_views.py" in form_valid
180. return super(PictureUpload, self).form_valid(form)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in form_valid
65. return HttpResponseRedirect(self.get_success_url())
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/http/response.py" in __init__
388. parsed = urlparse(redirect_to)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlparse
134. tuple = urlsplit(url, scheme, allow_fragments)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlsplit
173. i = url.find(':')
Exception Type: AttributeError at /pictures/2/
Exception Value: 'NoneType' object has no attribute 'find'
It looks like neither of your get_success_url implementations actually return the URL, so assuming that's not just a cut-and-paste error you're passing None to the HttpResponseRedirect.