Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert post title to CamelCase

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})
like image 220
linski Avatar asked Feb 07 '16 03:02

linski


2 Answers

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(' ', '')
like image 82
Selcuk Avatar answered Sep 29 '22 18:09

Selcuk


>>> 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()])
like image 44
Aviah Laor Avatar answered Sep 29 '22 18:09

Aviah Laor