0

我使用以下代码提取了最后上传的图像

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 () 工作正常,但我无法上传图片:)

请指导我

4

2 回答 2

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']
于 2012-05-04T06:25:39.443 回答
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']
于 2012-05-04T06:27:30.923 回答