我的 Django 应用程序有一个 entity Campaign。对于我的 UI,我已经实现CampaignForm了具有重要逻辑的逻辑。
我还集成了 Django Rest Framework,以允许Campaign通过 API实现类的CRUD 功能。
在 Google 和 DRF 的文档上搜索后,我发现没有将 Django Forms 集成到 DRF 的官方方法。
我一定是误会了吧?
我唯一看到的是 DRF 有自定义验证器,但我认为它不能将我的表单的所有逻辑移植到 DRF 的验证器。
如何将我的 CampaignForm 的逻辑包含到我的 API 中?
参考:
class CampaignForm(forms.ModelForm):
class Meta:
model = Campaign
fields = '__all__'
help_texts = {
'dayparting_schedule': schedule_help_text
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super().__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
"""
- All Active MUST have dayparting schedule defined
- If schedule is set then timezone must also be set
"""
cleaned_data = super().clean()
status = cleaned_data.get('status')
dayparting_schedule = cleaned_data.get('dayparting_schedule')
if status == Campaign.ACTIVE:
# if there is no existing dayparting_schedule OR
# if this form does not have dayparting_schedule
if dayparting_schedule is None \
and self.instance.dayparting_schedule is None:
raise forms.ValidationError(_('dayparting_schedule cannot be empty for Active'))
schedule_present = bool(dayparting_schedule)
timezone_present = bool(cleaned_data.get('dayparting_timezone'))
# XOR: 0^0, 1^1 => 0, otherwise 1
if schedule_present ^ timezone_present:
raise forms.ValidationError(
_('dayparting_schedule and dayparting_timezone must be set together.'))
return cleaned_data
def clean_dayparting_schedule(self, *args, **kwargs):
schedule = self.cleaned_data.get('dayparting_schedule')
if not schedule:
return
self.validate_schedule(schedule)
return schedule
def validate_schedule(self, yaml_s):
dic = yaml.load(yaml_s)
郎朗坤
相关分类