使用图像字段更新django

时间:2012-08-01 07:49:04

标签: python django orm

我正在尝试使用django orm来更新图像字段,即用户稍后将添加图像并将在主表中更新

我试过

MerchantProfile.objects.filter(id='%s'%(cd['id'])).update(photo='%s'%(cd['photo']))

但它只更新标题而图像未保存在文件夹

然后我尝试了

p1=MerchantProfile()
p1.id=cd['id']
if cd['photo']:
       p1.photo=cd['photo']
else:
       p1.photo=cd['uploaded_photo']
p1.save()

它会保存图片,但会显示错误,例如payment_card不能null

我的模型如下

class Merchantprofile:
   user = models.OneToOneField(UserProfile, related_name="merchant_profile")
   payment_card = models.OneToOneField(PaymentCard, related_name="merchant_profile")
   current_state = models.IntegerField('State', choices=STATE_CHOICES)
   name = models.CharField('Merchant Name', max_length=64)
   photo=models.ImageField(upload_to='logo',blank=True)

形式

class LogoForm(forms.Form):
     id = forms.CharField(widget=forms.HiddenInput,required=False)
     photo = forms.ImageField(
        required=False,
        label='Upload photo',
        initial=True,
        help_text='max. 4 megabytes'
    )

所以只有在相关文件夹上传照片才能更新照片字段的最佳方法是什么,因为我无法每次都更新所有字段

1 个答案:

答案 0 :(得分:0)

试试这个:

p1 = MerchantProfile.objects.filter(id=cd['id'])
if cd['photo']:
   p1.photo=cd['photo']
else:
   p1.photo=cd['uploaded_photo']
p1.save()