calling a django view recursively - django

I am trying to call a view recursively. Below is my code.
views.py
def survey_start(request):
post = models.Post.objects.all().order_by('id')
return HttpResponseRedirect(reverse('post_form_upload',args=(post[0].id,)))
def post_form_upload(request, id):
post = get_object_or_404(models.Post, id=id)
if request.method == 'GET':
content = post.content
form = CommentModelForm(content = content)
else:
form = CommentModelForm(request.POST)
if form.is_valid():
message = form.cleaned_data['message']
created_at = form.cleaned_data['created_at']
post1 = models.Comment.objects.create(post = id,
message = message,
created_at = created_at)
return HttpResponseRedirect(reverse('post_form_upload',
args= (post.next_id,)))
return render(request, 'survey_forms/post_form_upload.html',{
'form':form,
})
urls.py
urlpatterns = [
url(r'^post/form_upload.html$',views.survey_start, name='survey_start'),
url(r'^post/(?P<id>\d+)/post_form_upload.html$',views.post_form_upload, name='post_form_upload'),
]
I have two questions.
1. I keep on getting this error. It does enter the view. I printed a counter to check.
Reverse for 'post_form_upload' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['survey_forms/post/(?P<id>\\d+)/post_form_upload.html$']
Here is the traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/survey_forms/post/1/post_form_upload.html
Django Version: 1.8.3
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',
'survey',
'dynamic_forms',
'crispy_forms',
'formtools',
'survey_forms')
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',
'dynamic_forms.middlewares.FormModelMiddleware')
Template error:
In template /Users/Desktop/VtStudy/python/django/2dj_proto/mysurvey/survey_forms/templates/survey_forms/post_form_upload.html, error at line 1
Reverse for 'post_form_upload' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['survey_forms/post/(?P<id>\\d+)/post_form_upload.html$']
1 : <form action=" {% url 'post_form_upload' %} " method='post'>
2 : {% csrf_token %}
3 :
4 : {{form.as_p}}
5 : <input type='submit' value='Submit'/>
6 : </form>
Traceback:
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Desktop/VtStudy/python/django/2dj_proto/mysurvey/survey_forms/views.py" in post_form_upload
132. 'form':form,
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/shortcuts.py" in render
67. template_name, context, request=request, using=using)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/loader.py" in render_to_string
99. return template.render(context, request)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site-packages/django/template/backends/django.py" in render
74. return self.template.render(context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/base.py" in render
209. return self._render(context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/base.py" in _render
201. return self.nodelist.render(context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site-packages/django/template/base.py" in render
903. bit = self.render_node(node, context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/debug.py" in render_node
79. return node.render(context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/defaulttags.py" in render
507. six.reraise(*exc_info)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site-packages/django/template/defaulttags.py" in render
493. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/core/urlresolvers.py" in reverse
579. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
496. (lookup_view_s, args, kwargs, len(patterns), patterns))
Exception Type: NoReverseMatch at /survey_forms/post/1/post_form_upload.html
Exception Value: Reverse for 'post_form_upload' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['survey_forms/post/(? P<id>\\d+)/post_form_upload.html$']
Each post is displayed in one single page. The user must navigate from one page to other on clicking "next". So I am calling this view post_upload_form recursively. Is this the right approach?
Thanks.

For first point: problem is in the template:
<form action=" {% url 'post_form_upload' %} " method='post'>
post_form_upload in your urls.py takes one non-empty argument, but you're not providing that in above line.
For second point: this is not an recursion, technically speaking. You are just redirecting user to next url, which is handled by same view function. And it is right approach, there is nothing wrong with that.

Related

Django Crispy Forms Rendering Issue 'cannot convert dictionary update sequence element #0 to a sequence'

Struggling to figure this one out. I've seen several issues where this error code shows up but all seem to have to do with data not being passed into the context for the template to render. I know my data is getting through to the template. Crispy forms must be doing something behind the scenes that is throwing me off? Weird thing is this literally worked 20 minutes ago. I don't know what I could have changed that would have affected this.
Here is my view:
class ContactListView(View):
template = 'support_tracker/contact_list.html'
def get(self,request,*args,**kwargs):
staff_id = kwargs.pop('staff_id',False)
if staff_id:
staff = Staff.objects.get(pk=staff_id)
else:
staff = request.user.staff
contact_list = staff.contacts.all()
search_term = request.GET.get('search_term',False)
sort_by = request.GET.get('sort_by',False)
filter_by = request.GET.get('filter_by',False)
##applying search term to determine contact_list
...
##
##sorting of contact_list
....
##
##filtering of contact_list
....
##
search_form = SearchForm()
sort_form = ContactListSortForm()
filter_form = FilterByStageForm()
##pagination to determine contacts
...
##
context = {
'staff':staff,
'contacts':contacts,
'search_form':search_form,
'sort_form':sort_form,
'filter_form':filter_form,
'filter_by':filter_by,
'search_term':search_term,
'sort_by':sort_by,
}
print context
return render(request,self.template,context)
My Forms:
##forms.py
class SearchForm(forms.Form):
search_term = forms.CharField(max_length=30,label='')
def __init__(self,*args,**kwargs):
super(SearchForm,self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-inline'
self.helper.form_method = 'GET'
self.helper.field_template = 'bootstrap3/layout/inline_field.html'
self.helper.layout = Layout(
InlineField('search_term',placeholder='Search'),
Submit('','Go',css_class='btn btn-primary'),
)
class FilterByStageForm(forms.Form):
filter_by = forms.ChoiceField(choices=get_stage_option_list(),required=False)
def __init__(self,*args,**kwargs):
super(FilterByStageForm,self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-inline'
self.helper.form_method = 'GET'
self.helper.field_template = 'bootstrap3/layout/inline_field.html'
self.helper.layout = Layout(
InlineField('filter_by',placeholder='Filter By'),
Submit('','Filter',css_class='btn btn-primary'),
)
class ContactListSortForm(forms.Form):
sort_by = forms.ChoiceField(choices=(##options),required=False)
def __init__(self,*args,**kwargs):
super(ContactListSortForm,self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-inline'
self.helper.form_method = 'GET'
self.helper.field_template = 'bootstrap3/layout/inline_field.html'
self.helper.layout = Layout(
InlineField('sort_by',placeholder='Sort By'),
Submit('','Sort',css_class='btn btn-primary'),
)
My template:
{% extends 'co_tools/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class='container'>
<div class='col-md-3 well'>
<h3><u>Search:</u></h3>
## This is the part that trips it up. If I take the forms out, the rest of the page loads fine
{% crispy search_form %}
{% crispy sort_form %}
{% crispy filter_form %}
<a href='/support/new_contact/' class='btn btn-primary'>New Contact</a>
</div>
...body...
</div>
{% endblock content %}
The full traceback
Request Method: GET
Request URL: http://127.0.0.1:8000/support/contact_list/
Django Version: 1.10.2
Python Version: 2.7.11
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'support_tracker',
'donor_reports',
'staff',
'financial_reports']
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']
Template error:
In template C:\...\project\support_tracker\templates\support_tracker\contact_list.html, error at line 8
cannot convert dictionary update sequence element #0 to a sequence 1 : {% extends 'co_tools/base.html' %}
2 : {% load crispy_forms_tags %}
3 :
4 : {% block content %}
5 : <div class='container'>
6 : <div class='col-md-3 well'>
7 : <h3><u>Search:</u></h3>
8 : {% crispy form %}
9 : <a href='/support/new_contact/' class='btn btn-primary'>New Contact</a>
10 : </div>
11 : <div class='col-md-9'>
12 : <table class='table table-condensed table-hover'>
13 : <thead>
14 : <th>Contact Name</th>
15 : <th>Phone Number</th>
16 : <th>Email</th>
17 : <th>Street Address</th>
18 : <th>City</th>
Traceback:
File "C:\...\project\env\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\...\project\env\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\...\project\env\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\...\project\env\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\...\project\env\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\...\project\support_tracker\views.py" in get
185. return render(request,self.template,context)
File "C:\...\project\env\lib\site-packages\django\shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "C:\...\project\env\lib\site-packages\django\template\loader.py" in render_to_string
68. return template.render(context, request)
File "C:\...\project\env\lib\site-packages\django\template\backends\django.py" in render
66. return self.template.render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render
208. return self._render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in _render
199. return self.nodelist.render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render
994. bit = node.render_annotated(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render_annotated
961. return self.render(context)
File "C:\...\project\env\lib\site-packages\django\template\loader_tags.py" in render
174. return compiled_parent._render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in _render
199. return self.nodelist.render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render
994. bit = node.render_annotated(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render_annotated
961. return self.render(context)
File "C:\...\project\env\lib\site-packages\django\template\loader_tags.py" in render
70. result = block.nodelist.render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render
994. bit = node.render_annotated(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render_annotated
961. return self.render(context)
File "C:\...\project\env\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py" in render
215. c = self.get_render(context)
File "C:\...\project\env\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py" in get_render
126. response_dict = self.get_response_dict(helper, context, is_formset)
File "C:\...\project\env\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py" in get_response_dict
160. attrs = helper.get_attributes(template_pack=self.template_pack)
File "C:\...\project\env\lib\site-packages\crispy_forms\helper.py" in get_attributes
364. if self.form_action:
File "C:\...\project\env\lib\site-packages\crispy_forms\helper.py" in form_action
237. return reverse(self._form_action)
File "C:\...\project\env\lib\site-packages\django\urls\base.py" in reverse
91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "C:\...\project\env\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
344. self._populate()
File "C:\...\project\env\lib\site-packages\django\urls\resolvers.py" in _populate
217. dict(defaults, **pattern.default_kwargs),
Exception Type: TypeError at /support/contact_list/
Exception Value: cannot convert dictionary update sequence element #0 to a sequence
I have no idea what is causing this. Any help would be greatly appreciated.
Ok solved the issue. I have no clue why this particular bit of code was causing the problem though.
In my urls.py, I had added the following four url expressions...
from django.conf.urls import url, include
import views
urlpatterns = [
...
#meeting urls
url(r'^record_meeting/(?P<meeting_id>[0-9]+)/',views.EditMeetingView.as_view(),{'record':True}),
url(r'^record_meeting/$',views.EditMeetingView.as_view(),{'record':True}),
url(r'^edit_meeting/(?P<meeting_id>[0-9]+)/',views.EditMeetingView.as_view(),{'record':False}),
url(r'^add_meeting/$',views.EditMeetingView.as_view()),
]
The fourth one was originally url(r'^add_meeting/$',views.EditMeetingView.as_view(),{'record':False}), which apparently, based on trial and error, was causing the issue. After removing the additional arguments, the problem went away. Does anyone know why this was an issue in the first place? I still don't understand.

django dynamic form ValueError

I want to get the select form which can display all the users who have the group name "sale".
My definition for my forms is like this:
class ArrangeUserForm(forms.Form):
def __init__(self, *args, **kwargs):
super(ArrangeUserForm, self).__init__(*args, **kwargs)
user_choices = []
for user in User.objects.all():
if user.groups.filter(name="sale"):
user_choices.append(user.first_name)
self.fields['user_field'] = forms.ChoiceField(widget=forms.Select, choices=user_choices)
mobile = forms.CharField(widget=forms.TextInput, max_length=11, min_length=11)
and my view is like this:
class ArrangeUserHandler(View):
def get(self, request):
form = ArrangeUserForm()
return render(request, 'student/student_form.html', {'form': form,})
def post(self, request):
pass
when I run my code and request for that view, I got the following error:
ValueError at /student/arrangeuser/
too many values to unpack
could anyone told me what's going wrong here?
Traceback:
request Method: GET
Request URL: http://domain/student/arrangeuser/
Django Version: 1.5
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'accounts',
'student',
'order')
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')
Template error:
In template /home/rogerliu/newproject/crm/templates/student/student_form.html, error at line 7
too many values to unpack
1 :
2 : <form method="post">
3 : {% csrf_token %}
4 : {% for field in form %}
5 : <div class="fieldWrapper">
6 : {{ field.errors }}
7 : {{ field.label_tag }}: {{ field }}
8 : </div>
9 : {% endfor %}
10 : <input type="submit" value="submit" />
11 :
12 : </form>
13 :
14 :
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/home/rogerliu/newproject/crm/student/views.py" in get
318. return render(request, 'student/student_form.html', {'form': form,})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
177. return t.render(context_instance)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
140. return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
134. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
830. bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
74. return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
188. nodelist.append(node.render(context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render
87. output = force_text(output)
File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_text
99. s = s.__unicode__()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in __str__
411. return self.as_widget()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in as_widget
458. return widget.render(name, self.value(), attrs=attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render
555. options = self.render_options(choices, [value])
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render_options
579. for option_value, option_label in chain(self.choices, choices):
Exception Type: ValueError at /student/arrangeuser/
Exception Value: too many values to unpack
~
As per my comment, choices needs to be a key, value mapping, use:
tuple(enumerate(user_choices))
My questions are: How did you define your models?
Can you get the users from the group?
Can you get the groups from the user?
something like that:
groups = Group.objects.get(pk=1)
groups.users
user = User.objects.get(pk=1)
user.groups
You can do that writing this in you code:
#models.py
class User(Model):
name = CharField(max_length=200)
class Group(Model):
name = CharField(max_length=200)
users = ManyToManyField(User, related_name="groups")
#forms.py
class ArrangeUserForm(forms.Form):
def __init__(self, *args, **kwargs):
super(ArrangeUserForm, self).__init__(*args, **kwargs)
groups = groups.objects.filter(name="sale")
user_choices = User.objects.filter(groups_in=groups)
self.fields['user_field'] = forms.ChoiceField(widget=forms.Select, choices=user_choices)
mobile = forms.CharField(widget=forms.TextInput, max_length=11, min_length=11)
#And you views.py
class ArrangeUserHandler(FormView):
form_class = ArrangeUserForm
template_name = 'student/student_form.html'
def form_valid(self, form):
#When the form is valid
return super(ArrangeUserHandler, self).form_valid(form)
def form_invalid(self, form):
#When the form is invalid
return super(ArrangeUserHandler, self).form_invalid(form)
I think that It should work fine and quickly.
Will you tell me if this lines work?
# ...
groups = groups.objects.filter(name="sale")
user_choices = User.objects.filter(groups_in=groups)
# ...
I hope that helps.
see the Documentation of ManyToMany field and
FormView if you are in django 1.5

NoReverseMatch - Reverse for 'detail' with arguments and keyword arguments {} not found

for some reason I cannot seem to solve this bug. I am using Django 1.5
The actual error I get is
Reverse for 'detail' with arguments '()' and keyword arguments '{u'slug': u'third-post'}' not found.
In my projest dir I have this urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'blog.views.home', name='home'),
# url(r'^blog/', include('blog.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
#include the blogapp url
url(r'', include('blogapp.urls', namespace='blog')),
)
The urls.py in my app folder looks like this
urlpatterns = patterns ('',
url(r'^$',
ListView.as_view(
queryset = Post.objects.order_by('-pub_date')[:5],
context_object_name = 'latest_posts',
template_name = 'blogapp/default.html'),
name = 'index'
),
url(r'^post/(?P<slug>\w+)/$',
PostDetailView.as_view(),
name = 'detail'
),
)
My post detail view looks like this
class PostDetailView(DetailView):
template_name = 'blogapp/post/detail.html'
def get_object(self):
return get_object_or_404(Post, slug__iexact = self.kwargs['slug'])
I have this in my html
{% for p in latest_posts %}
<li>{{p.title}}</li>
{% endfor %}
I can open my shell and I get a url back
>>> from django.core.urlresolvers import reverse
>>> reverse('blog:detail', kwargs={'slug':'test'})
'/post/test/'
The weird thing is in my html this line works
<li>{{p.title}}</li>
why would p.id work and not p.slug?
Here is the traceback
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.5
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'south',
'blogapp')
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')
Template error:
In template .../Development/Python/Django/dev/blog/blogapp/templates/blogapp/default.html, error at line 11
Reverse for 'detail' with arguments '()' and keyword arguments '{u'slug': u'third-post'}' not found.
1 : {% extends "blogapp/base.html" %}
2 :
3 : {% block title %}Blog Posts{% endblock %}
4 :
5 : {% block body %}
6 :
7 : {% if latest_posts %}
8 : <p>Latest 5 blog posts</p>
9 : <ul>
10 : {% for p in latest_posts %}
11 : <li>{{p.title}}</li>
12 : {% endfor %}
13 : </ul>
14 : {% else %}
15 : <p>No blog posts published.</p>
16 : {% endif %}
17 :
18 : {% endblock %}
19 :
20 :
Traceback:
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
140. response = response.render()
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/response.py" in render
105. self.content = self.rendered_content
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/response.py" in rendered_content
82. content = template.render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/base.py" in render
140. return self._render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/base.py" in _render
134. return self.nodelist.render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/base.py" in render
830. bit = self.render_node(node, context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/debug.py" in render_node
74. return node.render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/loader_tags.py" in render
124. return compiled_parent._render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/base.py" in _render
134. return self.nodelist.render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/base.py" in render
830. bit = self.render_node(node, context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/debug.py" in render_node
74. return node.render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/loader_tags.py" in render
63. result = block.nodelist.render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/base.py" in render
830. bit = self.render_node(node, context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/debug.py" in render_node
74. return node.render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/defaulttags.py" in render
284. return nodelist.render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/base.py" in render
830. bit = self.render_node(node, context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/debug.py" in render_node
74. return node.render(context)
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/defaulttags.py" in render
188. nodelist.append(node.render(context))
File ".../.virtualenvs/env1/lib/python2.7/site-packages/django/template/defaulttags.py" in render
424. raise e
Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'detail' with arguments '()' and keyword arguments '{u'slug': u'third-post'}' not found.
Because your url codes did not support this character "-", it must be
url(r'^post/(?P<slug>[\w\-]+)/$',
PostDetailView.as_view(),
name = 'detail'
),

WSGIRequest error using django_model_comments

Sorry to post yet another question related to the error:
'WSGIRequest' object has no attribute 'find'
But I really can't find the answer anywhere.
I'm trying to use the django_model_comments app, which extends django's included comment app.
Did everything the page tells, however when running the server, I get the following:
Environment:
Request Method: GET
Request URL: http://localhost:8000/feed/1
Django Version: 1.4.3
Python Version: 2.7.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'model_comments',
'django.contrib.comments',
'pinax_theme_bootstrap_account',
'pinax_theme_bootstrap',
'django_forms_bootstrap',
'account',
'metron',
'user_app',
'feed_app']
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']
Template error:
In template D:\Docs\Work\repo\project\feed_app\templates\feed.html, error at line 10
'WSGIRequest' object has no attribute 'find'
1 : {% load model_comment_tags %}
2 : {% get_comment_form for feed as post_form %}
3 : {% render_comment_form post_form %}
Traceback:
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "D:\Docs\Work\repo\project\feed_app\views.py" in get_user_feed
37. 'feed': private_feed})
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\base.py" in render
140. return self._render(context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\base.py" in render
823. bit = self.render_node(node, context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\debug.py" in render_node
74. return node.render(context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\defaulttags.py" in render
281. return nodelist.render(context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\base.py" in render
823. bit = self.render_node(node, context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\debug.py" in render_node
74. return node.render(context)
File "D:\Docs\Work\repo\project\model_comments\templatetags\model_comment_tags.py" in render
26. return self.func(context)
File "D:\Docs\Work\repo\project\model_comments\templatetags\model_comment_tags.py" in wrap
75. form.set_request(request)
File "D:\Docs\Work\repo\project\model_comments\forms.py" in set_request
106. self.fields['from_url'].initial = unicode(Url(request))
File "D:\Docs\Work\repo\project\model_comments\url_util.py" in __init__
11. self.scheme, self.netloc, self.path, self.params, self.query_string, self.fragment = urlparse.urlparse(url)
File "C:\Python27\Lib\urlparse.py" in urlparse
134. tuple = urlsplit(url, scheme, allow_fragments)
File "C:\Python27\Lib\urlparse.py" in urlsplit
173. i = url.find(':')
Exception Type: AttributeError at /feed/1
Exception Value: 'WSGIRequest' object has no attribute 'find'
And the error happens when a templatetag is used:
html = "{% load model_comment_tags %} \
{% get_comment_form for feed as post_form %}\
{% render_comment_form post_form %}"
t = template.Template(html)
html = t.render(RequestContext(request, {'feed': private_feed}))
I've checked all my middleware, the order of apps, deleted .pyc files, and made all sorts of experiments in the template.
There's a bug in the django_model_comments library, because here they pass the HttpRequest object, not a string which is what the Url class here is expecting, so instead it should call the build_absolute_uri() method on the request object and then pass the string to the Url class.
So basically replace
unicode(Url(request))
with
unicode(Url(request.build_absolute_uri()))

CSRF fails when trying to upload ImageField

I have a django template with an ImageField form to allow users to upload pictures on the site.
1) The form contains {% csfr_token %}
2) I render a template with render variables.
Also, I have set enctype="multipart/form-data" in the form in the template?
Still I get a CSFR verif. fail. Can anyone help?
Code from the template.html
<form enctype="multipart/form-data" action='{% url photo username %}' method="post">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.profile_picture.label_tag }} {{ form.profile_picture.help_text }}</p>
<p>
{{ form.profile_picture.errors }}
{{ form.profile_picture }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
The view:
def upload_photo(request, nick):
#c = {}
#c.update(csrf(request))
if request.method == 'POST':
form = PictureForm(request.POST, request.FILES)
if form.is_valid():
newpic = Picture(profile_picture = request.FILES['profile_picture'])
newpic.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('profiles.views.upload_photo', args=[nick]))
else:
form = PictureForm() # A empty, unbound form
# Load documents for the list page
pictures = Picture.objects.all()
# Render list page with the documents and the form
return render_to_response(
'profile.html',
#various render variables here
})
UPDATE:traceback
Environment:
Request Method: POST
Request URL: localhost/hello/john/
Django Version: 1.4.2
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'friendship',
'search',
'tour',
'profiles')
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')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/mike/Documents/ics/django/ics/profiles/views.py" in upload_photo
18. newpic.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
551. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
1593. return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
909. for sql, params in self.as_sql():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in as_sql
872. for obj in self.query.objs
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in pre_save
249. file.save(file.name, file, save=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in save
85. name = self.field.generate_filename(self.instance, name)
File "/home/mike/Documents/ics/django/ics/profiles/models.py" in get_image_name
8. name = str(instance.user_id) + ".jpg"
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py" in __get__
343. raise self.field.rel.to.DoesNotExist
I found that the error is here (models.py):
def get_image_name(instance, filename):
return str(instance.user_id) + ".jpg"
#str(____) + ".jpg" causes the exception
class Picture(models.Model):
user_id = models.ForeignKey(User)
profile_picture = models.ImageField(storage=OverwriteStorage(), upload_to=get_image_name)
Any thoughts why this happens?
What I'm trying to do is save the image the user uploads with their username. But how can I get the user's username within the models.py?
Since you are not manually updating your context with the csrf token you must use a RequestContext in your render to response method
return render_to_response('profile.html', {
..your data dict.. }, context_instance=RequestContext(request))
Please see https://docs.djangoproject.com/en/1.2/ref/templates/api/#subclassing-context-requestcontext as well (I link to an old version of django since you still use function-style views)
EDIT:
Now that the csrf problem is fixed, you're dealing with a separate, new error. Try changing 'user_id' to 'user' (for consistency) in your Picture model and use str(instance.user.username) in your get_image_name. Even if this does not work (which it normally should), please post a new question as the original request has been answered. People could search for csrf and end up here, reading for an unrelated problem.