我正在使用基于Django背面构建的Python站点(非常棒的框架,无法让我的头脑绕过python),我希望拆分从数据库返回的字符串,我希望它能够拆分第一个空格发生所以我尝试了这样的事情,
{{product.name.split(' ' ,1)}}
这不起作用,我得到了这个堆栈跟踪,
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)'
我认为这意味着我可以直接在模板中做我想做的事情?这就是我的问题所在,因为我不知道在我的观点中该做什么,我希望有人能指出我正确的方向?
这是我的观点,
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, data, 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))
如果需要我的模型,我可以发布这个没问题。
我真的希望有些人可以帮助我。
非常感谢
答案 0 :(得分:11)
您可以使用{{ }}
调用方法 - 但该方法不需要任何属性。
在这种情况下,我要做的是在模型上添加一个执行所需行为的方法。例如:
class Product(models.Model):
...
def get_first_name(self):
if self.name:
return self.name.partition(' ')[0]
return None
然后,在您的模板中,您可以将其称为{{ product.get_first_name }}
。
您的另一个选择是编写自定义过滤器,这会稍微复杂一些。有关详细信息,请参阅Django documentation on custom template tags。