I am working on a site in Python built on the back of Django(awesome framework, cant get my head around python), I looking to split a string that is returned from a database and I want it to be split when the first space occurs so I tried something like this,
{{product.name.split(' ' ,1)}}
This did not work and I get this stacktrace,
Environment:
Request Method: GET
Request URL: http://website.co.uk/products/
Django Version: 1.1.1
Python Version: 2.5.2
Installed Applications:
['django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'website.news',
'website.store_locator',
'website.css_switch',
'website.professional',
'website.contact',
'website.shop',
'tinymce',
'captcha']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Template error:
In template /var/www/website/src/website/shop/templates/category.html, error at line 6
Could not parse the remainder: '(' ',1)' from 'product.name.split(' ',1)'
1 : {% extends "shopbase.html" %}
2 : {% block pageid %}shop{%endblock%}
3 : {% block right-content %}
4 : <div class="products">
5 : <form method="post" action="{% url category category.slug %}">
6 : {% for product in category.products.all %}
7 : <div class="{% cycle 'clear' '' '' %}">
8 : <img src="{{MEDIA_URL}}{{product.mini_thumbnail}}" alt="{{product.name}}" class="thumbnail"/>
9 : <div class="prod-details">
10 : <h3><a href="{% url shop.views.product category.slug product.slug %}">{{product.name.split(' ',1)}}</a></h3>
11 : <p class="strap">{{ product.strap }}</p>
12 : <ul>
13 : <li class="price">£{{product.price}}</li>
14 : <li class="quantity">
15 : <select name="quantity_{{product.id}}">
16 : <option label="1" value="1">1</option>
Traceback:
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/website/src/website/shop/views.py" in home
716. return category(request, Category.objects.root_category(), data={'pageclass':'stylers'})
File "/var/www/website/src/website/shop/views.py" in category
738. return render_to_response(template, data, RequestContext(request))
File "/usr/lib/python2.5/site-packages/django/shortcuts/__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/lib/python2.5/site-packages/django/template/loader.py" in render_to_string
103. t = get_template(template_name)
File "/usr/lib/python2.5/site-packages/django/template/loader.py" in get_template
82. template = get_template_from_string(source, origin, template_name)
File "/usr/lib/python2.5/site-packages/django/template/loader.py" in get_template_from_string
90. return Template(source, origin, name)
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in __init__
168. self.nodelist = compile_string(template_string, origin)
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in compile_string
189. return parser.parse()
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in parse
285. compiled_result = compile_func(self, token)
File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in do_extends
169. nodelist = parser.parse()
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in parse
285. compiled_result = compile_func(self, token)
File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in do_block
147. nodelist = parser.parse(('endblock', 'endblock %s' % block_name))
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in parse
285. compiled_result = compile_func(self, token)
File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in do_for
688. nodelist_loop = parser.parse(('empty', 'endfor',))
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in parse
266. filter_expression = self.compile_filter(token.contents)
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in compile_filter
358. return FilterExpression(token, self)
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in __init__
538. raise TemplateSyntaxError("Could not parse the remainder: '%s' from '%s'" % (token[upto:], token))
Exception Type: TemplateSyntaxError at /products/
Exception Value: Could not parse the remainder: '(' ',1)' from 'product.name.split(' ',1)'
I assume this means that I can do what I want to do straight in the template? This is where my problem comes as I dont know where to do it in my views, I was hoping some could point me in the correct direction?
This is my view,
def home(request):
"""
The home page, borrows functionality from category
"""
return category(request, Category.objects.root_category(), data={'pageclass':'stylers'})
def category(request, category_slug, template='category.html', data={}):
"""
Display a category in the store
"""
import re
category = get_object_or_404(Category, slug=category_slug)
basket = Basket(request)
if request.method == "POST":
for k, v in request.POST.iteritems():
match = re.match('^add_to_basket_([0-9])+$',k)
if match:
id = match.group(1)
basket.add_item(Product.objects.get(id=id), request.POST['quantity_%s' % id])
break
return HttpResponseRedirect(reverse('basket'))
data['category'] = category
return render_to_response(template, dat开发者_JAVA技巧a, RequestContext(request))
def product(request, category_slug, product_slug):
"""
Display a product in the store, nominated by product_slug, that is in the
category nominated by category_slug
"""
data = {'pageclass':'irons'}
category = get_object_or_404(Category, slug=category_slug)
product = get_object_or_404(Product, slug=product_slug)
basket = Basket(request)
if request.method == "POST":
basket.add_item(product, request.POST['quantity'])
return HttpResponseRedirect(reverse('basket'))
data['category'] = category
data['product'] = product
return render_to_response('product.html', data, RequestContext(request))
If my model is needed I can post this up no problem.
I really hope some can help me.
Thanks very much
You can call methods using the {{ }}
-- but the method can't require any attributes.
What I would do in this case is add a method on your model that performs the desired behavior. Example:
class Product(models.Model):
...
def get_first_name(self):
if self.name:
return self.name.partition(' ')[0]
return None
Then, in your template, you can call it as {{ product.get_first_name }}
.
Your other option would be to write a custom filter, which would be marginally more complicated. See the Django documentation on custom template tags for more information.
精彩评论