Matchday
Matchday

Reputation: 649

What is the best way to return multiple values from django views.py to a template

What would be the best way of returning multiple values in a Django views.py to the template?

For example, I want people to access any user's public profile by entering their username in the URL:

views.py

def public_profile(request, username_in_url):
    #Get appropriate user data from database
    user = User.objects.get(username = username_in_url)
    username = user.username
    first_name = user.first_name
    last_name = user.last_name
    date_joined = user.date_joined
    bio = user.userprofile.bio
    matchday_rating = user.userprofile.matchday_rating
    following = user.userprofile.following
    followers = user.userprofile.followers
    ..
    ..
    [return render_to_response..?]
    [use a Class instead and store values in a context?]

public_profile.html

   <h2> {{username}} </h2><br><br>

   <h4> 
       First Name: {{first_name}} <br>
       Last Name: {{last_name}} <br>
       Date Joined: {{date_joined}} <br><br>
       Matchday Rating: {{matchday_rating}} <br>
       Following: {{following}} <br>
       Followers: {{followers}}
   </h4>

   <br>

   <h4> User Bio: </h4><br>
   <p>{{bio}}</p>

urls.py

url(r'^(?P<username>\s)/$', 'fantasymatchday_1.views.register_success'),

Upvotes: 0

Views: 4851

Answers (2)

Isaac Ray
Isaac Ray

Reputation: 1361

I think your url matching pattern is not right:

Try this:

urls.py

(r'^(?P<username_in_url>\w+)$', 'fantasymatchday_1.views.register_success')

I'm also not sure that you are pointing to your view the right way (register_success is the function you call in urls.py but in your example above you call the function public_profile).

Upvotes: 1

tcarobruce
tcarobruce

Reputation: 3838

You can store the user fields in a dictionary and pass it as context to render_to_response:

def public_profile(request, username_in_url):
    user = User.objects.get(username = username_in_url)
    context = {
        'first_name': user.first_name,
        # ...
    }
    return render_to_response('public_profile.html', context)

It may be simpler to just pass the user object to the template:

def public_profile(request, username_in_url):
    user = User.objects.get(username = username_in_url)
    context = {
        'user': user,
    }
    return render_to_response('public_profile.html', context)

The template would then need to reference the fields of user:

First Name: {{user.first_name}}

Upvotes: 2

Related Questions