如何从模板中的扩展用户配置文件访问数据?

时间:2012-07-27 05:15:49

标签: django templates view model

我正在尝试确定我应该在下面的模板中包含什么,以便将插入到下面模型的“quote”字段中的数据拉入其中。目前,模板中没有显示任何内容。有什么建议?

模型

class UserProfile(models.Model):
    user = models.ForeignKey(User, primary_key=True)
    quote = models.CharField('About', max_length =  200, null=True, blank=True)
    website = models.URLField('Personal website/blog', null=True, blank=True)
    #facebook = models.CharField('Facebook profile page', max_length = 200, null=True, blank=True)

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ('quote', 'website')
        widgets = {
            'quote': Textarea(attrs={'cols': 18, 'rows': 7, 'style': "width: 300px;"}),
        }

视图

@login_required 
def user_profile(request):
    user = User.objects.get(pk=request.user.id)
    if request.method == 'POST':
        upform = UserProfileForm(request.POST)
        if upform.is_valid():
            up = upform.save(commit=False)
            up.user = request.user
            up.save()
            return HttpResponseRedirect('/accounts/profile')
    else:
        upform = UserProfileForm()
    return render_to_response('reserve/templates/edit_profile.html', locals(), context_instance=RequestContext(request))

模板

{{user.quote}}

1 个答案:

答案 0 :(得分:1)

试试这个

{% for profile in user.userprofile_set.all %}
   {{profile.quote}}
{% endfor %}  

quote不是User模型的字段,因此首先访问UserProfile个实例然后访问quote