3

我有一个包含以下模型的 django 应用程序:

class Business(models.Model, GetDistance):
    business_name = models.CharField(max_length=128)
    .
    user = models.ForeignKey(User)
    .
    media_dir = models.CharField(max_length=256, blank=True)
    .
    business_image = models.ImageField(max_length=128, upload_to=upload_business_image_handler, blank=True, height_field='business_image_height', width_field='business_image_width')

    business_image_height = models.IntegerField(blank=True, null=True)
    business_image_width = models.IntegerField(blank=True, null=True)

然后我还定义了一个在“业务”模型中使用的上传处理程序:

def upload_business_image_handler(instance, filename):
    # determine the upload path
    .
    return file_path

我有一个表单使用一些小部件更改输入字段的默认呈现,例如:

business_name = forms.CharField(widget=forms.TextInput(attrs={'size':'50', 'class': 'address'}), required=True)

在表单中,我没有指定 business_image 字段,以便采用模型的默认值。模板中的表格有:

<form enctype="multipart/form-data" method="POST" action="">{% csrf_token %}

并且视图代码包含:

business_form = BusinessForm(request.POST, request.FILES, auto_id='id_registration_%s', branch_list = branch_list, country_list = country_list)

现在,当我在表单中输入一些数据并为 business_image 字段选择图像时,一切都按预期工作。文件名在业务对象中,文件上传到由“upload_business_image_handler”确定的目录中。但是,当我将 business_image 字段更改为:

business_image = models.ImageField(max_length=128, upload_to=upload_business_image_handler, height_field='business_image_height', width_field='business_image_width')

即删除“空白=真”选项,然后我总是得到一个“此字段是必需的”错误,即使我在 business_image 表单字段中选择了一个图像。

当我在视图中插入“assert False”时,我可以看到错误,但我也可以看到文件名和文件对象,所以我不理解错误消息。

4

0 回答 0