'str' object has no attribute 'attname' - django

I am trying to display a link to the next and previous object according the title field using get_next_or_previous_by_FIELD. Django 1.6 is throwing me this error.
Error during template rendering
'str' object has no attribute 'attname'
Error occurs here in template.
{% with next_lesson=lesson.get_next_by_title %}
And here in my models.
return self._get_next_or_previous_by_FIELD('title', is_next=True)
Here is my model.
class LessonManager(models.Manager):
def all(self):
return super(LessonManager, self).filter(active=True)
class Lesson(models.Model):
active = models.BooleanField(default=False)
title = models.CharField(max_length=65)
slug = models.SlugField(unique=True)
objects = LessonManager()
def __unicode__(self, ):
return self.title
class Meta:
ordering = ['title']
def get_absolute_url(self):
return reverse('lesson', args=[str(self.slug)])
def get_next_by_title(self):
try:
return self._get_next_or_previous_by_FIELD('title', is_next=True)
except Lesson.DoesNotExist:
return None
def get_previous_by_title(self):
try:
return self._get_next_or_previous_by_FIELD(order='title', is_next=False)
except Lesson.DoesNotExist:
return None
And here is my template.
<a class="col-md-6" href="{{ lesson.get_previous_by_title.get_absolute_url }}" title="{% trans "View previous post" %}">« {{ lesson.get_previous_by_title.title }}</a>
<a class="col-md-6" href="{{ lesson.get_next_by_title.get_absolute_url }}" title="{% trans "View previous post" %}">« {{ lesson.get_next_by_title.title }}</a>
Here is the full traceback as requested.
Environment:
Request Method: GET
Request URL: /tutorials/lesson/lesson-name/
Django Version: 1.6.2
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'ckeditor',
'tutorials')
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')
Template error:
In template C:\Users\Shaun\Desktop\sg\static\templates\tutorials\lesson.html, error at line 22
'str' object has no attribute 'attname'
12 : {% endif %}
13 : {% if lesson.get_next_by_timestamp %}
14 : <a class="right" href="{{ lesson.get_next_post.get_absolute_url }}">{{ lesson.get_next_post.title|truncatewords:'4' }} »</a>
15 : {% endif %}
16 :
17 : <div class='clearfix'></div>
18 :
19 : <h2>{{ lesson.title|upper }}</h2>
20 : <p>{{ lesson.content|safe }}</p>
21 :
22 : <a class="col-md-6" href=" {{ lesson.get_previous_by_title.get_absolute_url }} " title="{% trans "View previous post" %}">« {{ lesson.get_previous_by_title.title }}</a>
23 : <a class="col-md-6" href="{{ lesson.get_next_by_title.get_absolute_url }}" title="{% trans "View previous post" %}">« {{ lesson.get_next_by_title.title }}</a>
24 :
25 : {% endblock %}
Traceback:
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Shaun\Desktop\sg\src\tutorials\views.py" in single_lesson
13. return render_to_response('tutorials/lesson.html', locals(), context_instance=RequestContext(request))
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\shortcuts\__init__.py" in render_to_response
29. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\loader.py" in render_to_string
169. return t.render(context_instance)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in render
140. return self._render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in render
840. bit = self.render_node(node, context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\debug.py" in render_node
78. return node.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\loader_tags.py" in render
123. return compiled_parent._render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in render
840. bit = self.render_node(node, context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\debug.py" in render_node
78. return node.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in render
840. bit = self.render_node(node, context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\debug.py" in render_node
78. return node.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\debug.py" in render
88. output = self.filter_expression.resolve(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in resolve
585. obj = self.var.resolve(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in resolve
735. value = self._resolve_lookup(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in _resolve_lookup
789. current = current()
File "C:\Users\Shaun\Desktop\sg\src\tutorials\models.py" in get_previous_by_title
64. return self._get_next_or_previous_by_FIELD('title', is_next=False)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\db\models\base.py" in _get_next_or_previous_by_FIELD
708. param = force_text(getattr(self, field.attname))
Exception Type: AttributeError at /tutorials/lesson/setting-up-your-django-blog-application/
Exception Value: 'str' object has no attribute 'attname'

_get_next_or_previous_by_FIELD isn't supposed to be something you call yourself.
The main problem you're having is that it is expecting a Field object, not a string, hence the error. This is because the method is actually used as part of a curried function that is created by the field class itself, which in turn is called by the model metaclass when the model is first imported.
The currying creates the actual get_next_by_foo and get_previous_by_foo methods. In fact, these are only created for Date and Datetime fields.
Note that the uncurried method name begins with an underscore, which - with the exception of Model._meta - is a good sign that you're not supposed to be using it in your own code.

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 IntegrityError (1048, "Column 'network_id' cannot be null")

Ok, so i searched high and low for this, and both the docs, and almost every page on google tells me my code should be legit.
Let me start with models.py:
class Network(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=500)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.id
class NetworkForm(ModelForm):
class Meta:
model = Network
class Range(models.Model):
network = models.ForeignKey(Network)
range_start = models.GenericIPAddressField(unpack_ipv4=True)
range_end = models.GenericIPAddressField(unpack_ipv4=True)
range_title = models.CharField(max_length=50)
range_description = models.CharField(max_length=300)
def __unicode__(self):
return self.range_title
class RangeForm(ModelForm):
class Meta:
model = Range
exclude = ('network',)
Then my views.py:
#login_required(login_url='/login/')
def add_network(request):
if request.method == "POST":
net_form = NetworkForm(request.POST)
range_formset = RangeForm(request.POST)
if net_form.is_valid and range_formset.is_valid:
net_form.save(commit=False)
range_formset.network = net_form
range_formset.save()
net_form.save()
return HttpResponseRedirect('/')
else:
net_form = NetworkForm()
range_form = RangeForm()
return render_to_response('networks/add.html', {
"net_form": net_form,
"range_form": range_form,
}, context_instance=RequestContext(request))
And my template:
{% extends 'base.html' %}
{% block title %}Add Network{% endblock %}
{% block content %}
<div class="row-fluid">
<div class="span7 offset2 well">
<h3>Add network:</h3>
<hr />
<form class="form-horizontal" method="post" action="">
{% csrf_token %}
{{ net_form }}
<h4>Add a range to the network:</h4>
<hr />
<div class="form-inline">
{{ range_form }}
</div>
<hr />
<button type="submit" class="btn btn-primary btn-large">Add network</button>
</form>
</div>
</div>
{% endblock %}
Now, there most be something obvious i'm missing here, just failing to make the last connection. If somebody could enlighten me that would be great.
PS: In case anybody wondered i validated my model by looking in MySQL Workbench, MySQL Commandline client, and manage.py dbshell and inspectdb, all id columns are present. I even dropped the whole db and recreated it with manage.py.
Its been grinding my gears for about a week now, so time to ask for help. If anybody would be so kind to help me solve this, it would be great!
Here is the traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/network/add/
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_nose',
'networks')
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',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
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/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/home/alexander/PycharmProjects/NOC/networks/views.py" in add_network
29. range_form.save()
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in save
370. fail_message, commit, construct=False)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in save_instance
87. instance.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
546. force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
650. 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
215. return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
1673. 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
937. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py" in execute
41. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py" in execute
127. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py" in execute
120. return self.cursor.execute(query, args)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py" in execute
174. self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py" in defaulterrorhandler
36. raise errorclass, errorvalue
Exception Type: IntegrityError at /network/add/
Exception Value: (1048, "Column 'network_id' cannot be null")
You have at least four errors.
Firstly, you have to actually call is_valid: it is a method, not a property.
Secondly, form.save(commit=False) returns the model instance. It doesn't magically convert the form object into an instance. You need to assign it to a variable which you then set the extra attributes on.
Thirdly, you're doing the commit=False on the wrong object - you should be doing it on the one you subsequently want to modify.
Fourth, don't redirect unless the forms are valid.
So:
range_form = RangeForm(request.POST)
if net_form.is_valid() and range_form.is_valid():
net_obj = net_form.save()
range_obj = range_form.save(commit=False)
range_obj.network = net_obj
range_obj.save()
return HttpResponseRedirect('/')
else:
net_form = NetworkForm()
range_form = RangeForm()
return render_to_response('networks/add.html', {
"net_form": net_form,
"range_form": range_form,
}, context_instance=RequestContext(request))
(And don't call things formsets when they're not, they're just forms. Except that of course you actually should probably be using inline formsets for the range forms, but that's a separate question.)

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()))

Weird error message with django-ratings

I'm getting a strange error message with [django-ratings][1]. The following is in my urls.py:
url(r'^rate/(?P<object_id>\d+)/(?P<score>\d+)/', AddRatingFromModel(),{
'app_label': 'spiceapp',
'model': 'spice',
'field_name': 'rating',
}),
If I navigate to this page: /spiceapp/rate/1/2, I get the following error:
Caught AttributeError while rendering: 'AddRatingFromModel' object has no attribute 'name'
What would cause this to happen?
Environment:
Request Method: GET
Request URL: http://localhost:8000/spiceapp/rate/1/2/
Django Version: 1.3.1
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.humanize',
'django.contrib.markup',
'mptt',
'treenav',
'djangoratings',
'django.contrib.databrowse',
'pinax.templatetags',
'django_facebook',
'aiteo',
'haystack',
'notification',
'staticfiles',
'debug_toolbar',
'mailer',
'uni_form',
'crispy_forms',
'django_openid',
'ajax_validation',
'timezones',
'emailconfirmation',
'announcements',
'pagination',
'friends',
'messages',
'oembed',
'groups',
'threadedcomments',
'wakawaka',
'swaps',
'tagging',
'bookmarks',
'photologue',
'avatar',
'flag',
'microblogging',
'locations',
'django_sorting',
'tagging_ext',
'smuggler',
'voting',
'pinax.apps.signup_codes',
'pinax.apps.analytics',
'pinax.apps.blog',
'pinax.apps.tribes',
'pinax.apps.photos',
'pinax.apps.topics',
'pinax.apps.threadedcomments_extras',
'about',
'account',
'waitinglist',
'spiceapp',
'bbauth',
'profiles']
Installed Middleware:
['django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_openid.consumer.SessionConsumer',
'django.contrib.messages.middleware.MessageMiddleware',
'groups.middleware.GroupAwareMiddleware',
'pinax.apps.account.middleware.AuthenticatedMiddleware',
'pinax.apps.account.middleware.LocaleMiddleware',
'django.middleware.doc.XViewMiddleware',
'pagination.middleware.PaginationMiddleware',
'django_sorting.middleware.SortingMiddleware',
'pinax.middleware.security.HideSensistiveFieldsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Template error:
In template /Users/nb/Desktop/myenv2/lib/python2.7/site-packages/debug_toolbar/templates/debug_toolbar/base.html, error at line 48
Caught AttributeError while rendering: 'AddRatingFromModel' object has no attribute '__name__'
38 : </div>
39 : {% for panel in panels %}
40 : {% if panel.has_content %}
41 : <div id="{{ panel.dom_id }}" class="panelContent">
42 : <div class="djDebugPanelTitle">
43 : {% trans "Close" %}
44 : <h3>{{ panel.title|safe }}</h3>
45 : </div>
46 : <div class="djDebugPanelContent">
47 : <div class="scroll">
48 : {{ panel.content|safe }}
49 : </div>
50 : </div>
51 : </div>
52 : {% endif %}
53 : {% endfor %}
54 : <div id="djDebugWindow" class="panelContent"></div>
55 : </div>
56 :
Traceback:
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
178. response = middleware_method(request, response)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/debug_toolbar/middleware.py" in process_response
104. smart_unicode(self.debug_toolbars[request].render_toolbar() + self.tag))
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/debug_toolbar/toolbar/loader.py" in render_toolbar
78. return render_to_string('debug_toolbar/base.html', context)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
183. return t.render(Context(dictionary))
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/test/utils.py" in instrumented_test_render
60. return self.nodelist.render(context)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/defaulttags.py" in render
227. nodelist.append(node.render(context))
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/defaulttags.py" in render
311. return self.nodelist_true.render(context)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/base.py" in render
744. bits.append(self.render_node(node, context))
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/debug.py" in render_node
73. result = node.render(context)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/debug.py" in render
90. output = self.filter_expression.resolve(context)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/base.py" in resolve
510. obj = self.var.resolve(context)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/base.py" in resolve
653. value = self._resolve_lookup(context)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/template/base.py" in _resolve_lookup
698. current = current()
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/debug_toolbar/panels/request_vars.py" in content
35. 'view_func': '%s.%s' % (self.view_func.__module__, self.view_func.__name__),
Exception Type: TemplateSyntaxError at /spiceapp/rate/1/2/
Exception Value: Caught AttributeError while rendering: 'AddRatingFromModel' object has no attribute '__name__'
This looks like an old bug in django-debug-toolbar. Do you happen to know which version you are using? Because the file looks like the one in this commit. Several fixes has been made to that file since then: this one, for example seems to address specifically your issue.
In any case, the version you're using seems to predate the 2nd of June, 2011. I would try looking into updating your environment.