将多个值从django views.py返回到模板的最佳方法是什么?

时间:2014-08-26 19:23:59

标签: django django-templates django-views

将Django views.py中的多个值返回给模板的最佳方法是什么?

例如,我希望用户通过在网址中输入用户名来访问任何用户的公开个人资料:

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'),

2 个答案:

答案 0 :(得分:1)

您可以将用户字段存储在字典中,并将其作为上下文传递给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)

将用户对象传递给模板可能更简单:

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)

然后,模板需要引用user

的字段
First Name: {{user.first_name}}

答案 1 :(得分:1)

我认为您的网址匹配模式不对:

试试这个:

urls.py

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

我也不确定你是否以正确的方式指向你的视图(register_success是你在urls.py中调用的函数,但在上面的例子中你调用了函数public_profile)。