I'm trying to convert a post title to CamelCase to create a twitter hashtag, I'm using strip but its returning a object instead I dont know if this is the right way?
# 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)
Which returns <built-in method strip of unicode object at 0x031ECB48>
in the template var, the result I'm looking for is like this MyPostTitle
into the template
# 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})
strip
only removes the whitespace from the beginning or end of the string (https://docs.python.org/2/library/string.html#string.strip). You might use
instance.hashtag = instance.title.replace(' ', '')
As a side note, it might be cleaner to add this functionality as a method to your model class:
class Post(models.Model):
...
def hashtag(self):
if self.title is not None:
return self.title.replace(' ', '')
>>> a = "foo baz bar"
>>> "".join([s.capitalize() for s in a.rsplit()])
>>> FooBazBar
To save:
import re
r = re.compile("[/!/?,:.;-]")
t = r.sub(" ",instance.title) # clear punctuation
instance.hashtag = "".join([s.capitalize() for s in t.rsplit()])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With