Python {{user.get_profile.foo}}不在Django中工作
我试图在用户配置文件(我知道是原始的)中显示用户配置文件信息,但除非它是配置文件的表单视图,否则我无法让它工作。我用Python {{user.get_profile.foo}}不在Django中工作,python,django,Python,Django,我试图在用户配置文件(我知道是原始的)中显示用户配置文件信息,但除非它是配置文件的表单视图,否则我无法让它工作。我用{form.instance.user}在我的用户配置文件编辑表单中调用user和foo,效果很好 我已经在我的静态用户配置文件模板(loggedin.html)中实现了{{user.get_profile.foo}},但什么也没发生 我的静态用户配置文件(loggedin.html)模板如下所示: {% extends "base.html" %} {% block conte
{form.instance.user}
在我的用户配置文件编辑表单中调用user
和foo
,效果很好
我已经在我的静态用户配置文件模板(loggedin.html
)中实现了{{user.get_profile.foo}}
,但什么也没发生
我的静态用户配置文件(loggedin.html
)模板如下所示:
{% extends "base.html" %}
{% block content %}
<title>{% block title %} | {{ username }}{% endblock %}</title>
<h2>Hi, {{ username }}!</h2>
<h3>{{ user.get_profile.foo }}</h3>
<a href="/accounts/profile/">Edit Profile</a>
{% endblock content %}
我的用户配置文件编辑表单(profile.html
)模板:
{% extends "base.html" %}
{% block content %}
<title>{% block title %} | Edit Profile{% endblock %}</title>
<h2>Edit {{ username }}</h2>
{% for field in form %}
{{ field.error }}
{% endfor %}
<form action="/accounts/profile/" method="post">{% csrf_token %}
<label for="id_user">Username:</label>
<br>
<input id="id_user" name="user" type="text" value="{{form.instance.user}}">
<br><br>
<label for="id_foo">Foo:</label>
<br>
<input id="id_foo" name="foo" type="text" value="{{form.instance.foo}}">
<br><br>
<input type="submit" value="Update">
</form>
{% endblock content %}
我的用户配置文件(表单)视图:
我可以获得username
和foo
值,以便在用户配置文件表单中显示良好,但是当我尝试获得相同的信息以显示在静态配置文件中时,它不起作用
完全公开:我的静态配置文件位于一个名为polls
的应用程序中,它不同于我的编辑表单模型和模板所在的userprofile
应用程序,但我不确定这是否与此问题有关
如果您需要查看我的URL、设置或管理代码,请告诉我;我觉得它不相关,只会添加混乱,但如果需要,我很乐意添加它。您的属性是
User.profile
。所以你应该试试
{{ user.profile.foo }}
在您的模板中,不是使用
{{user.get_profile.foo}
{user.foo}模板中的{user.foo}
返回什么?您已经添加了一个属性user.profile
,但是您正在尝试访问模板中的user.get_profile
。我已经尝试了{user.foo}
,{user.get_profile.foo}/code>,{{User.foo}
并且它们都不返回任何内容。如果您的属性是User.profile
,您是否尝试过{{User.profile.foo}
?
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
foo = models.CharField(max_length=30)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from forms import UserProfileForm
from django.contrib.auth.decorators import login_required
from userprofile.models import UserProfile
@login_required
def user_profile(request):
user = request.user
username = request.user.username
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
args['user'] = user
args['username'] = username
return render_to_response('profile.html', args)
{{ user.profile.foo }}