在清理/验证之前如何编辑Django表单数据?

时间:2019-08-12 15:23:20

标签: django django-forms

在验证或保存之前,如何编辑django表单字段返回的值?

对于example,如果我有:

from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        # the widget returns user.id's (django-select2 ModelSelect2MultipleWidget
        recipient_ids = self.data['recipients']  

        # need to convert IDs to usernames
        usernames = User.objects.filter(id=recipient_ids).values_list(username, flat=True)

        # now I have a list of usernames, I need to put those back into the data to finish cleaning etc:

        self.data['recipients'] = usernames  # error, data isn't mutable...

        return super().clean()

如何在将表单数据self.data['recipients'] = usernames发送给清理之前对其进行修改?

关于为什么需要这样做的旁注:我正在尝试对Django-postman收件人字段使用Django-select2 ModelSelect2MultipleWidget(返回pks),但是Django postman中的收件人不能是id,它必须是用户名或其他字段(我尝试设置POSTNAME_NAME_USER_AS ='pk',但邮递员不接受,所以我只使用默认的'用户名')

1 个答案:

答案 0 :(得分:0)

但这就是clean(或特定的clean_fieldname方法)的用途。对于clean,您应该修改self.cleaned_data;对于clean_recipients,您只需返回修改后的数据即可。