在保存期间,并非所有表单字段都到达模型

时间:2019-07-11 06:46:34

标签: python django

我要将裁剪尺寸的图像字段发送到django,以便在保存之前编辑图像。编辑和保存部分有效,但仅当我对所需尺寸进行硬编码时才可用。

我的问题是,在模型中,裁剪尺寸不会出现并显示为“无”。

要保存的模型使用表单集进行处理。

稍后添加了裁剪尺寸,我没有忘记迁移字段。

这是我的代码:

view.py

for i, form in enumerate(picture_formset_from_request.forms):
    if form.is_valid():
        form.save()

在pycharm中,这似乎是不再进一步传递数据的文件:

forms / models.py

def save(self, commit=True):
    """
    Save this form's self.instance object if commit=True. Otherwise, add
    a save_m2m() method to the form which can be called after the instance
    is saved manually at a later time. Return the model instance.
    """
    if self.errors:
        raise ValueError(
            "The %s could not be %s because the data didn't validate." % (
                self.instance._meta.object_name,
                'created' if self.instance._state.adding else 'changed',
            )
        )
    if commit:
        # If committing, save the instance and the m2m data immediately.
        self.instance.save() # <- it seems to go wrong here
        self._save_m2m()
    else:
        # If not committing, add a method to the form to allow deferred
        # saving of m2m data.
        self.save_m2m = self._save_m2m
    return self.instance

save.alters_data = True

在self.instance.save()在线上,所需的数据位于“ cleanded_data”中,但在“ instance”中,x,y,w,h均显示为None。

x,y,w,h稍后添加,以尝试在保存之前裁剪照片。

models.py

class LetterPicture(models.Model):
    letter = models.ForeignKey(Letter, on_delete=models.CASCADE)
    slot = models.IntegerField()
    picture = models.ImageField(upload_to="letter_pictures/%Y/%m/%d", default="empty.jpg")
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    publish = models.DateTimeField(auto_now=True)
    x = models.FloatField(null=True)
    y = models.FloatField(null=True)
    w = models.FloatField(null=True)
    h = models.FloatField(null=True)

    def save(self, *args, **kwargs):
        self.set_image( # <- data not available here
            desired_width=200,
            desired_height=200
        )

        super().save(*args, **kwargs)

forms.py

class LetterPictureModelForm(forms.ModelForm):
    picture = forms.ImageField(
        label='Picture',
        widget=ClearableFileInput(attrs={
            'class': 'form-control',
            'placeholder': 'Picture'
        })
    )
    x = forms.FloatField(widget=forms.HiddenInput())
    y = forms.FloatField(widget=forms.HiddenInput())
    w = forms.FloatField(widget=forms.HiddenInput())
    h = forms.FloatField(widget=forms.HiddenInput())

    class Meta:
        model = LetterPicture
        fields = ['picture', 'x', 'y', 'w', 'h', ]
        widgets = {
            'letter': forms.HiddenInput(),
            'slot': forms.HiddenInput(),
            'x': forms.HiddenInput(),
            'y': forms.HiddenInput(),
            'w': forms.HiddenInput(),
            'h': forms.HiddenInput(),
        }

我刚接触Django仅4周-因此,我对自己正在做的事情的了解还不够。

在保存过程中什么阻止了x,y,w,h字段到达模型?

1 个答案:

答案 0 :(得分:0)

我不完全知道问题出在哪里,但这是一个成功的解决方案,感觉上不太hacky:

if form.is_valid():
    letter_picture_pre_save = form.save(commit=False)
    letter_picture_pre_save.x = form.cleaned_data['x']
    letter_picture_pre_save.y = form.cleaned_data['y']
    letter_picture_pre_save.w = form.cleaned_data['w']
    letter_picture_pre_save.h = form.cleaned_data['h']
    letter_picture_pre_save.save()