0

I'm having some trouble trying to pass a string from a URL to the views. My page has user pages, and if you go to site.com/username it brings up that users page. But when I try going it says this: [invalid literal for int() with base 10: 'username'].

Here's my code:

urls.py:

(r'^user/(?P<userName>[^/]+)/$', 'mischief_blog.mischief_app.views.user_view'),

views.py:

def user_view(request, userName):
    postList = userPost.objects.filter(author=userName)
    return render_to_response('user.html', {"user": user_name, "postList": postList}, context_instance=RequestContext(request))

1 Answer 1

2

get name from url:

(r'^user/(?P<userName>\w+)/$', 'mischief_blog.mischief_app.views.user_view'),

get user from name, then get posts from user: (get_object_or_404) and (User)

from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User

def user_view(request, userName=None):
    user = get_object_or_404(User, username=userName)
    postList = userPost.objects.filter(author=user)
    return render_to_response('user.html', {"user": user, "postList": postList}, context_instance=RequestContext(request))
Sign up to request clarification or add additional context in comments.

5 Comments

This won't work for me because I don't have a model 'User'. I'm just using the built in django user system thing.
If you are using the default auth system you can just import the User model.
Oh I see, I didn't see your import statement :) sorry!
I have one further question. When I go to someone's profile, the url is site.com/user/username. But if I click any other link, home for example, it tries to go to site.com/user/home. How do I fix this so that it goes to site.com/home instead?
(r^'/$', 'home', name='home') and in templates {% url home %}, sorry on my mobile. But you can post another question if it's not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.