[英]Django - modelform doesn't save image
I use Ubuntu 14.10 and apache2 web server. 我使用Ubuntu 14.10和apache2 Web服务器。 In my Django project i have the model with additional information about user:
在我的Django项目中,我具有包含有关用户的其他信息的模型:
class UserProfile(models.Model):
class Meta:
verbose_name_plural = u'User profile'
user = models.OneToOneField(User)
birthday = models.DateField(blank=True, null=True)
avatar = models.ImageField(upload_to='media/profile/avatar', blank=True, null=True)
name = models.CharField(blank=True, null=True, max_length=20)
surname = models.CharField(blank=True, null=True, max_length=50)
phone = models.CharField(blank=True, null=True, max_length=12)
def __unicode__(self):
return '%s' % self.user
Here is my form: 这是我的表格:
class ExtraProfileDataForm(ModelForm):
name = forms.CharField(label=(u'Enter your name'))
surname = forms.CharField(label=(u'Enter your surname'))
phone = forms.CharField(label=(u'Enter your phone'))
birthday = forms.DateField(label=(u'Birthday'))
avatar = forms.ImageField(label=(u'Avatar'))
class Meta:
model = UserProfile
fields = ('name', 'surname', 'phone', 'birthday', 'avatar')
def __init__(self, *args, **kwargs):
super(ExtraProfileDataForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].required = False
And this is the view: 这就是观点:
@login_required
def UserFullDataForm(request):
if request.method == 'POST':
form = ExtraProfileDataForm(request.POST)
if form.is_valid():
profile_user = request.user
user_profile, created = UserProfile.objects.get_or_create(user=profile_user)
user_profile.name = form.cleaned_data['name']
user_profile.surname = form.cleaned_data['surname']
user_profile.phone = form.cleaned_data['phone']
user_profile.birthday = form.cleaned_data['birthday']
user_profile.avatar = form.cleaned_data['avatar']
user_profile.save()
return HttpResponseRedirect('/profile/')
else:
return render(request, 'profiles/extra_profile.html', {'form':form})
else:
form = ExtraProfileDataForm()
context = {'form':form}
return render (request, 'profiles/extra_profile.html', context)
When i fill the form all fields saved to the database except image field. 当我填写表格时,除图像字段外,所有其他字段都保存到数据库中。 Chown of
media/profile/avatar
folders is www-data
and chmod is 775. Log files is empty. media/profile/avatar
文件夹的别名为www-data
,chmod为775。日志文件为空。 I have no any errors to understand why its happens. 我没有任何错误,以了解其发生原因。 Can you help me understand why its happens or what i have to do to see the error.
您能帮我理解为什么会发生这种情况,或者我必须做什么才能看到错误。 Thank you.
谢谢。 PS.
PS。 this how looks like media of the project in apache config:
这在apache config中看起来像项目的媒体:
Alias /media/ /var/www/project/media/
<Directory /var/www/project/>
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Require all granted
</Directory>
You may need to pass request.FILES
in form = ExtraProfileDataForm(request.POST, request.FILES)
您可能需要以
form = ExtraProfileDataForm(request.POST, request.FILES)
传递request.FILES
def UserFullDataForm(request):
if request.method == 'POST':
form = ExtraProfileDataForm(data=request.POST, files=request.FILES)
if form.is_valid():
user_form = form.save(commit=False)
user_form.user = request.user
user_form.save()
return HttpResponseRedirect('/profile/')
else:
return render(request, 'profiles/extra_profile.html', {'form':form})
else:
form = ExtraProfileDataForm()
context = {'form':form}
return render (request, 'profiles/extra_profile.html', context)
You have some code which is not required. 您有一些不需要的代码。 Just remove that code as
form.save()
will save your form. 只需删除该代码作为
form.save()
将保存您的表单。 Change your view like this. 像这样改变你的看法。
def UserFullDataForm(request):
if request.method == 'POST':
form = ExtraProfileDataForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/profile/')
else:
return render(request, 'profiles/extra_profile.html', {'form':form})
else:
form = ExtraProfileDataForm()
context = {'form':form}
return render (request, 'profiles/extra_profile.html', context)
As you form is storing data in two different tables, you have to write your own save function for your form like this. 当表单将数据存储在两个不同的表中时,您必须像这样为表单编写自己的保存功能。
def save(self, commit=True, **kwargs):
user = super(UserCreateForm, self).save(commit=False)
# get or create record for UserProfile against user and save it
In your settings.py
, add following 在您的
settings.py
,添加以下内容
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
In your project urls.py
, add following line at the end 在您的项目
urls.py
,在末尾添加以下行
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You model will be changed like this 您的模型将像这样更改
avatar = models.ImageField(upload_to='profile/avatar', blank=True, null=True)
For me, the issue had nothing to do with my Python code, which correctly did not return any errors. 对我来说,这个问题与我的Python代码无关,后者正确地没有返回任何错误。
The issue was my <form>
html did not have enctype set to support file post. 问题是我的
<form>
html没有将enctype设置为支持文件发布。
Example: 例:
<form action="." method="post" accept-charset="utf-8" enctype="multipart/form-data">
{{ form }}
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.