我在用户完成注册后为每个用户显示个人资料图片时遇到问题。上传到/media/profile_pictures
文件夹后,我可以看到图片被保存,但我找不到在主页上显示该图片的方法。
请查看代码示例。我正在使用Django教程跟踪Tango上传图片,但是我在这里找到的与这个问题无关的问题并没有真正帮助我。
forms.py
:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('website', 'picture')
views.py
:
def register(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
profile.save()
registered = True
else:
print (user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request,'webapp/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})
models.py
:
class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
def __unicode__(self):
return self.user.username
settings.py
MEDIA_URL = '/media/profile_images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
home.html
:
<img src="{{ user.UserProfile.picture.url }}" width="240">
在urls.py
我添加了
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
答案 0 :(得分:1)
如果你小写UserProfile
,我认为它会起作用:
<img src="{{ user.userprofile.picture.url }}" width="240">
documentation for OneToOneField
says:
如果没有为
OneToOneField
指定related_name
参数,Django将使用当前模型的小写名称作为默认值。