Django错误提交表单中的imagefield

时间:2013-05-29 00:11:16

标签: django django-models django-forms django-templates

我有一个django表单,我正在尝试提交给我的服务器。当按下提交按钮时,它发送一个发布请求,并向视图功能发送两个对象(stream_id和图像)。我可以从调试页面看到该对象分别包含POST和FILES对象中的stream_id和image。

然而,一旦命中了视图函数,我尝试按如下方式初始化表单:

uploadImageForm = UploadImageForm(request.POST, request.FILES)

并向我发出验证错误。

[28/May/2013 18:46:32] DEBUG [ct:194] uploadImage - method is post, errors:
<ul class="errorlist"><li>stream_id<ul class="errorlist">
<li>This field is required.</li></ul></li>
<li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
[28/May/2013 18:46:32] DEBUG [ct:195] cleaned data: {}

知道为什么吗?

我的表格:

class UploadImageForm(forms.Form):
    image = forms.ImageField()
    image.widget.attrs["onchange"]="this.form.submit();"
    stream_id = forms.CharField(max_length=100)
    stream_id.widget.attrs["style"]="display:none;"

    def __init__(self,stream_id,*args,**kwrds):
        super(UploadImageForm,self).__init__(*args,**kwrds)
        self.fields['stream_id'].widget.attrs["value"]= stream_id

型号:

class Stream(models.Model):
    tracked_user = models.ForeignKey(TrackedUser)
    stream_id = models.CharField(max_length=255)
    stream_hash = models.CharField(max_length=255)
    name = models.CharField(max_length=60)
    start_time = models.DateTimeField(default=datetime.datetime.now(pytz.utc))
    end_time = models.DateTimeField(default=None)
    end_time.null = True 
    image = models.ImageField(upload_to="/")
    image.null = True 

    def __unicode__(self):
        return self.name

views.py中的代码:

def uploadImage(request):
    uploadImageForm = None
    if (request.method == "POST"):
        uploadImageForm = UploadImageForm(request.POST, request.FILES) 
        log.debug("uploadImage - method is post, errors: " +
            str(uploadImageForm.errors))

有趣的是,绑定表单输出如下:

<p>
    <label for="id_image">Image:</label>
    <input id="id_image" name="image" onchange="this.form.submit();" type="file" />
</p>
<ul class="errorlist">
    <li>This field is required.</li>
</ul>

<p>
    <label for="id_stream_id">Stream id:</label>
    <input id="id_stream_id" maxlength="100" name="stream_id"
        style="display:none;" type="text" value="&lt;QueryDict:
        {u&#39;stream_id&#39;:[u&#39;d21256f37601d2800b0b9604f0e94e1e&#39;],
        u&#39;csrfmiddlewaretoken&#39;:
        [u&#39;F0fmAD0VAj0RHrM0GGfnaSb6vTNgj9ZJ&#39;]}&gt;" />
</p>

1 个答案:

答案 0 :(得分:0)

默认情况下,Django表单中的所有字段都是必需的,这就是您在Stream ID和其他字段上出现错误的原因。在您不想要的字段上设置blank=True,或者在表单类中选择性地要求:

class Stream(models.Model):
    tracked_user = models.ForeignKey(TrackedUser)
    stream_id = models.CharField(max_length=255, blank=True)
    stream_hash = models.CharField(max_length=255, blank=True)
    name = models.CharField(max_length=60)
    start_time = models.DateTimeField(default=datetime.datetime.now(pytz.utc))
    end_time = models.DateTimeField(default=None, null=True)
    image = models.ImageField(upload_to="/")

    def __unicode__(self):
        return self.name

我不太清楚你在使用ImageUploadForm做了什么,但是你将会以当前编写的方式获得初始化错误。您没有在视图中传递stream_id

class UploadImageForm(forms.Form):
    image = forms.ImageField()
    image.widget.attrs["onchange"]="this.form.submit();"
    stream_id = forms.CharField(max_length=100)
    stream_id.widget.attrs["style"]="display:none;"

    def __init__(self, *args, **kwargs):
        stream_id = kwargs.pop('stream_id')
        super(UploadImageForm,self).__init__(*args, **kwargs)
        self.fields['stream_id'].widget.attrs["value"]= stream_id

我在想你是想继承ModelForm ......

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = Stream

    def __init__(self, *args, **kwargs):
        stream_id = kwargs.pop('stream_id')

        super(UploadImageForm, self).__init__(*args, **kwargs)

            # this is really bad practice. I would add this click handler
            # unobtrusively
            self.fields['image'].widget.attrs["onchange"] = "this.form.submit();"
            stream_id = self.fields['stream_id']

            # not sure what you're trying to accomplish here...
            self.fields['stream_id'].widget.attrs["style"] = "display:none;"

            stream_id.initial = stream_id