我正在尝试将帖子标题转换为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})
最佳答案
>>> 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()])
关于python - 将帖子标题转换为CamelCase,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35249514/