Python在django验证之前编辑表单数据

时间:2016-11-01 18:12:33

标签: python django forms validation django-forms

我对python很新,并且在所有标准python表单/字段验证器完成他们的魔术之前,我一直在寻找如何编辑表单数据。

我有一个带有IntegerField的模型表单,我想删除" $"和逗号(使用某种自定义验证),然后让正常的to_python()validate()等做他们的事情。

我的代码如下 - 任何帮助都将非常感谢!

forms.py

class BuyerSettingsForm(forms.ModelForm):
    total_offer_limit = forms.IntegerField(required=False, max_value=10000000, min_value=0)

    def __init__(self, request, *args, **kwargs):
        super(BuyerSettingsForm, self).__init__(*args, **kwargs)    

    class Meta:
        model = Buyer
        fields = ['total_offer_limit']

    def save(self, commit=True):
        profile = super(BuyerSettingsForm, self).save(commit=commit)
        profile.total_offer_limit = self.cleaned_data['total_offer_limit']
        profile.save()
        return profile

views.py

class SettingsPreferences(LoginRequiredMixin, BuyerAccessRequiredMixin, BuyerAdminAccessRequiredMixin, UpdateView):
    template_name = 'invoicely/buyer/settings/buyer_settings.html'
    form_class = BuyerSettingsForm
    success_url = reverse_lazy('settings_preferences')

    def get_object(self, *args, **kwargs):
        return self.request.user.profile.buyer

    def get_initial(self):
        ctx = super(SettingsPreferences, self).get_initial()
        ctx.update({
            'total_offer_limit': self.object.total_offer_limit,
        })
        return ctx

    def get_form_kwargs(self):
        kwargs = super(SettingsPreferences, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs

    def form_valid(self, form):
        self.object = form.save()
        messages.add_message(self.request, messages.SUCCESS, "Settings successfully updated")
        return super(SettingsPreferences, self).form_valid(form)

1 个答案:

答案 0 :(得分:0)

如果您已经超载var content2=""; ,则可以执行此操作。这是您的表单将初始化的数据。所以我们可以在初始化之前对其进行编辑。

get_form_kwargs