gpt4 book ai didi

python - 将帖子标题转换为 CamelCase

转载 作者:太空狗 更新时间:2023-10-30 00:48:56 26 4
gpt4 key购买 nike

我正在尝试将帖子标题转换为 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)

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

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

模型.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})

最佳答案

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

关于python - 将帖子标题转换为 CamelCase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35249514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com