class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
profile_image = models.ImageField(upload_to="/perfil/", blank=True, null=True)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user = u)[0])
urls.py:
urlpatterns = patterns('',
url(r'^perfil/$', 'apps.userprofile.views.user_profile', name= 'perfil'),
)
和views.py:
# Create your views here.
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
@login_required
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('../index')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance = profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('profile.html', args)
当然还有forms.py:
from django import forms
from models import UserProfile
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout
from crispy_forms.bootstrap import (FormActions, )
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
helper = FormHelper()
helper.form_method = 'POST'
helper.layout = Layout(
'profile_image',
FormActions(Submit('Editar', 'Editar', css_class= 'btn-primary'))
)
def save(self, commit=True):
fact = super(UserProfileForm, self).save(commit=False)
if commit:
fact.save()
return fact
所以,我要做的是让用户上传图片,让它用作个人资料图片。我设置了:
AUTH_PROFILE_MODULE = 'apps.userprofile.UserProfile' (the app is inside a folder call 'apps' that´s why the first 'apps' before userprofile)
在settings.py中,我将'userprofile'的网址添加到主项目中。现在我有了可以上传图像的模板,问题是图像永远不会保存在数据库中,因此我无法调用函数在模板中显示图像,请说“用户配置文件”页面。 / p>
有人看着代码知道我做错了什么吗?
答案 0 :(得分:0)
根据Django 1.7文档,ModelForm
类必须明确指定在调用save()
方法时应更新哪些字段。尝试将fields = __all__
添加到您的UserProfileForm
类元。
Relevant section of ModelForm documentation
请注意该链接中注释的第一行:
上述逻辑中未包含在表单中的任何字段都不会被设置 通过表单的save()方法。
我自己还在学习Django,但这是我先尝试的。 :)