1

I currently have a url based on the name of the list entered by the user. list_name. Everything queries and displays no issues. However, when a user enters a space as the list name, the browser doesn't handle it so nicely. I've realized I need to slugify the string, but am not sure how to go about doing this implementation. I have some feeling that I add some sort of slug field to the model and then query the slug field name to associate itself with the model object rendering to the page. I'm just not sure how to code it up.

Model

class newlist(models.Model):
    user = models.ForeignKey(User)
    list_name = models.CharField(max_length = 100,)
    picture = models.ImageField(upload_to='profiles/', default = "/media/profiles/default.jpg")

    def __str__(self):
        return self.list_name

View

def mylistpage(request, username, listname):


    context = RequestContext(request)
    #make sure that the user is authenticated
    if username == request.user.username:
        #If the user is authenticated, then perform the following functions to the page
        if request.user.is_authenticated():
            #Store the current user request object into a variable
            user = User.objects.get(username=username)

            #Store the list name to the item that starts with the url input
            listname = request.user.newlist_set.filter(list_name__iexact=listname)

            listitems = request.user.newlist_set.all()
            if not listname:
                return redirect('/notfound')
    else:
        return redirect('/notfound')

    return render_to_response('listview.html', {'lista': listname}, context)

URL

url(r'^user/(?P<username>\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'),
ryan
  • 625
  • 3
  • 10
  • 23

1 Answers1

4

Spaces in URLs is not a good idea. This use case is a typical candidate for a SlugField

A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs

So basically, in your models, you would add another field called slug, and pass that in the URL.

You could use a readily available package called django-autoslug to auto-generate slugs.

Here are some posts which might give more insights on slugs:

Community
  • 1
  • 1
karthikr
  • 97,368
  • 26
  • 197
  • 188