将帖子标题转换为CamelCase

时间:2016-02-07 03:51:45

标签: python django python-2.7 django-templates django-views

我正在尝试将帖子标题转换为CamelCase来创建一个Twitter标签,我正在使用strip但是它返回了一个对象,而我不知道这是不是正确的方式?

# views.py
def post_create(request):
    if not request.user.is_authenticated():
        raise Http404

    form_class = PostCreateForm
    if request.method == 'POST':

        form = form_class(request.POST, request.FILES)
        if form.is_valid():

            instance = form.save(commit=False)
            instance.creator = request.user
            instance.slug = slugify(instance.title)
            instance.hashtag = instance.title.strip()
            instance.save()


            slug = slugify(instance.title)
            return redirect(instance.get_absolute_url())

    else:
        form = form_class()

    context = {
        'form': form,
    }

    return render(request, "posts/post_create.html", context)

在模板var中返回<built-in method strip of unicode object at 0x031ECB48>,我正在寻找的结果就像这个MyPostTitle一样进入模板

    # Template view
    <h3>#{{instance.hashtag|title}}</h3>

models.py

class Post(models.Model):
    creator = models.ForeignKey(ProfileUser)
    title = models.CharField(max_length=80)
    hashtag = models.CharField(max_length=80)
    slug = models.SlugField(unique=True)

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"slug": self.slug})

3 个答案:

答案 0 :(得分:4)

strip仅从字符串的开头或结尾删除空格(https://docs.python.org/2/library/string.html#string.strip)。你可以使用

instance.hashtag = instance.title.replace(' ', '')

作为旁注,将此功能作为方法添加到模型类可能更简洁:

class Post(models.Model):
    ...
    def hashtag(self):
        if self.title is not None:
            return self.title.replace(' ', '')

答案 1 :(得分:3)

>>> a = "foo baz bar"
>>> "".join([s.capitalize() for s in a.rsplit()])
>>> FooBazBar

保存:

import re
r = re.compile("[/!/?,:.;-]")

t = r.sub(" ",instance.title) # clear punctuation
instance.hashtag = "".join([s.capitalize() for s in t.rsplit()])

答案 2 :(得分:1)

Python的unicode类也有一个title()方法,这意味着你可以这样做:

$ python3
>>> 'foo bar baz'.title()
'Foo Bar Baz'
>>> 'foo bar baz'.title().replace(' ', '')
'FooBarBaz'

请注意,.title().replace()的顺序很重要!