Question

I am following a tutorial to add friends in Django: Building Friend Networks

I am getting a 404 page because I have set it in my code to raise a Http404 if the username was not found in request.GET:

views.py:

def friend_add(request):
    if 'username' in request.GET:
        friend = get_object_or_404(User, username=request.GET['username'])
        friendship = Friendship(from_friend=request.user, to_friend=friend)
        friendship.save()
        return HttpResponseRedirect('/friends/%s' % request.user.username)
    else:
        raise Http404

urls.py:

url(r'^friend/add/(?P<username>\w+)$', photo.views.friends_request),
url(r'^friends/(?P<username>\w+)$', photo.views.friends),
url(r'^request_sent/$', photo.views.friend_add),

I am using template tags like this as shown from the tutorial:

{% ifequal user.username abuild.user %}
    <a href="/builds/friends/{{ user.username }}">view your friends</a>
{% else %}
    {% if is_friend %}
        <a href="/builds/friends/{{ abuild.user }}">
        {{ abuild.user }} is a friend of yours</a> 
    {% else %}
        <a href="/builds/request_sent/">
        add {{ abuild.user}} to your friends</a> 
    {% endif %}
    - <a href="/builds/friends/{{ abuild.user }}">
    view {{abuild.user}}'s friends</a>
{% endifequal %}

How do I ensure that I am getting the username when I click on a link that goes to /request_sent/?

abuild.user is the user who I am trying to add, while user.username is the person logged in.

Was it helpful?

Solution

You should pass the username in the url as you are doing in other cases.

So your template would change to

<a href="/builds/request_sent/{{abuild.user.username}}">

urls.py would change to

 url(r'^request_sent/(?P<username>\w+)$', photo.views.friend_add),

And then view would change to

def friend_add(request, username):
    if 'username' in request.GET:
    ....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top