Django - modelform没有保存图像

时间:2016-02-29 09:44:37

标签: python django apache django-forms

我使用Ubuntu 14.10和apache2 web服务器。在我的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

这是我的表格:

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

这就是观点:

@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)

当我填写表单时,除了图像字段之外,所有字段都保存到数据库中。 media/profile/avatar文件夹的chown为www-data,chmod为775.日志文件为空。我没有任何错误可以理解为什么会发生这种错误。你能帮助我理解为什么会发生这种情况或我必须做些什么才能看到错误。谢谢。 PS。这看起来像apache config中的项目媒体:

Alias /media/ /var/www/project/media/
    <Directory /var/www/project/>
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

3 个答案:

答案 0 :(得分:0)

您可能需要在request.FILES

中传递form = ExtraProfileDataForm(request.POST, 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)

答案 1 :(得分:0)

您有一些不需要的代码。只需删除该代码,form.save()即可保存您的表单。改变你的观点。

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)

由于您的表单是将数据存储在两个不同的表中,您必须为您的表单编写自己的保存功能。

def save(self, commit=True, **kwargs):
    user = super(UserCreateForm, self).save(commit=False)
    # get or create record for UserProfile against user and save it

settings.py中,添加以下内容

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

在您的项目urls.py中,在末尾添加以下行

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

你的模特会像这样改变

avatar = models.ImageField(upload_to='profile/avatar', blank=True, null=True)

答案 2 :(得分:0)

对我来说,这个问题与我的Python代码无关,它正确地没有返回任何错误。

问题是我的<form> html没有 enctype 设置为支持文件发布。

示例:

<form action="." method="post" accept-charset="utf-8" enctype="multipart/form-data">
    {{ form }}
</form>