Ben
Ben

Reputation: 7124

Calling information from request inside a django template

I have a django app using authentication where user's can view one another's profiles.

In my views.py

def display(request, edit=False, pk=None): 
    if not pk:
        pk = request.user.profile.pk

    profile = Profile.objects.get(pk=pk)
    d = get_user_info(profile) # returns a dictionary of some info from a user's profile

    if edit and request.user == profile.user:
        return render(request, 'edit_profile.html', d)
    else:
        return render(request, 'profile.html', d)

Inside my template I would like to give a user the option to click a link allowing them to edit information if they are viewing their own profile.

{% if request.user == profile.user %}
    <a href="{% url "edit_profile" %}">edit</a>
{% endif %}

I have two questions about this.
First: I thought using render() allowed me to access request inside the template. However, that's not working. Am I doing it wrong? Or do I need to explicitly pass render with the dictionary?

d['request']=request    
return render(request, 'profile.html', d) 

Second: Is this okay to do? Or should I be doing this some other way?

Upvotes: 0

Views: 788

Answers (1)

Rohan
Rohan

Reputation: 53386

Django has a request context processor that adds request object in template context. This is not added by default so you need to enable that in the TEMPLATE_CONTEXT_PROCESSORS settings.

However, django adds current request.user as user context variable, so you can use that if that is sufficient.

Upvotes: 3

Related Questions