【问题标题】:Django errors submitting imagefield in formDjango 错误提交表单中的图像字段
【发布时间】:2013-05-29 00:11:16
【问题描述】:

我有一个 Django 表单正在尝试提交到我的服务器。当提交按钮被按下时,它会发送一个 post 请求,并将两个对象(一个 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>

【问题讨论】:

  • 你能把你的模型和表格贴出来吗?
  • @Brandon 请看一下!

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


【解决方案1】:

默认情况下,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

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 2014-11-11
    • 2013-12-26
    • 1970-01-01
    • 2012-05-28
    • 2015-08-23
    • 1970-01-01
    • 2012-01-17
    • 2015-11-04
    相关资源
    最近更新 更多