【问题标题】:What is the best way to return multiple values from django views.py to a template从 django views.py 返回多个值到模板的最佳方法是什么
【发布时间】:2014-08-26 19:23:59
【问题描述】:

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

例如,我希望人们通过在 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'),

【问题讨论】:

  • 如果您已经有一个可以传递的类,则无需创建另一个类:用户。
  • @DanielRoseman 好点,我也不确定我的 URL 模式,因为它似乎无法将字符串识别为参数。你能提供任何帮助吗? :)
  • 你应该问一个新问题。但是它完全被破坏了:\s 只匹配一个空格。您可能需要\w+ 用于多个字母数字字符,或者[\w-_]+ 如果您还需要破折号和下划线。

标签: django django-templates django-views


【解决方案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}}

【讨论】:

    【解决方案2】:

    我认为你的 url 匹配模式不对:

    试试这个:

    urls.py

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

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

    【讨论】:

    • 支持\s不合适,[\w-_]+会更好
    猜你喜欢
    • 2010-09-07
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 2013-10-21
    • 2020-07-04
    • 2019-01-23
    相关资源
    最近更新 更多