需要帮助图片上传django表单

时间:2012-05-04 06:14:11

标签: python django forms django-models

我使用以下代码

提取了上次上传的图片
class categoryForm(forms.Form):
   name = forms.CharField(widget=forms.TextInput(attrs={'class':'box'}),max_length=32,label='Category',required=True)
   is_active = forms.BooleanField(required=False)
   id = forms.CharField(widget=forms.HiddenInput,required=False)
   photo = forms.ImageField(
     required=False,
     label='Upload photo',
     initial=True,
     help_text='max. 4 megabytes'
     )
   def __init__(self, data,**kwargs):
     super(categoryForm, self).__init__(data, **kwargs)
      if self.data['photo']!='':
         self.fields['photo'].initial=self.data['photo']

我在填充更新表格时传递了数据

p=Category.objects.get(id='%s'%(target_id))
formdata = categoryForm({'name':p.name,'is_active':p.is_active,'id':p.id,'photo':p.image()})

完美呈现初始图像

由于我也有FileField,我需要在动作页面中传递额外的参数,其中调用了categoryForm,即

formdata = categoryForm(request.POST,request.FILES)

这个额外的参数给我错误

__init__() takes exactly 2 arguments (3 given)

如果我删除request.FILES init ()工作正常,但我无法上传图片:)

请指导我

2 个答案:

答案 0 :(得分:2)

是否将__init__功能更改为此帮助?

  def __init__(self, data, *args, **kwargs):
     super(categoryForm, self).__init__(data, **kwargs)
      if self.data['photo']!='':
         self.fields['photo'].initial=self.data['photo']

答案 1 :(得分:0)

我不确定你的代码是否正确,如果你说它有效......那么它是有效的。 错误来自这里:

   def __init__(self, data,**kwargs):
     super(categoryForm, self).__init__(data, files, **kwargs)
      if self.data['photo']!='':
         self.fields['photo'].initial=self.data['photo']

或者你可以这样做:

formdata = categoryForm(data = request.POST, files = request.FILES)

   def __init__(self, *args, **kwargs):
     super(categoryForm, self).__init__(*args, **kwargs)
      if self.data['photo']!='':
         self.fields['photo'].initial=self.data['photo']