ModelForm和模型验证一起玩

时间:2017-04-19 12:17:41

标签: django validation model modelform

我有以下型号:

class Advertisement(models.Model):

    slug = models.UUIDField(default=uuid4, blank=True, editable=False)

    advertiser = models.ForeignKey(Advertiser)
    position = models.SmallIntegerField(choices=POSITION_CHOICES)
    share_type = models.CharField(max_length=80)
    country = CountryField(countries=MyCountries, default='DE')
    postal_code = models.CharField(max_length=8, null=True, blank=True)

    date_from = models.DateField()
    date_to = models.DateField()

根据广告客户,排名,类型国家/地区和邮政编码,存储范围为date_from和date_to的广告。

advertiser, position, share_type, country and postal_code

来自请求,并在

中提取
class CreateAdvertisment(LoginRequiredMixin, CreateView):

    # Some usefull stuff

    def dispatch(self, request, *args, **kwargs):

        self.advertiser = Advertiser.objects.get(user=self.request.user)
        self.share_type = self.kwargs.get('share_type', None)
        self.country = self.kwargs.get('country', None)
        self.postal_code = self.kwargs.get('postal_code', None)
        self.position = int(self.kwargs.get('position', None))
        self.position_verbose = verbose_position(self.position)

        ret = super(CreateAdvertisment, self).dispatch(request, *args, **kwargs)

        return ret

没有任何验证来检查date_from,date_to。我可以简单地做

def form_valid(self, form):

    form.instance.advertiser = self.advertiser
    form.instance.share_type = self.share_type
    form.instance.country = self.country
    form.instance.postal_code = self.postal_code
    form.instance.position = self.position

    ret = super(CreateAdvertisment, self).form_valid(form)
    return ret

我完成了。不幸的是,我不能这样做,因为我必须检查广告的有效时间帧以避免同时进行双重预订。我在模型中执行以下操作:

def clean(self):
    ret = super(Advertisement, self).clean()
    print ("country [%s] position [%s] share_type [%s] postal_code [%s]" % (self.country,
           self.position, self.share_type, self.postal_code))
    if self.between_conflict():
        raise ValidationError("Blocks between timeframe")
    elif self.end_conflict():
        raise ValidationError("End occupied")
    elif self.during_conflict():
        raise ValidationError("Time Frame complete occupied")
    elif self.start_conflict():
        raise ValidationError("Start Occupied")
    return ret

def start_conflict(self):

    start_conflict = Advertisement.objects.filter(country=self.country,
                                                  position=self.position,
                                                  share_type=self.share_type,
                                                  postal_code=self.postal_code).filter(
        date_from__range=(self.date_from, self.date_to))

    return start_conflict

这很好用,我会过滤掉给定时期内的任何冲突。问题是我没有实例变量,因为它们是在view.form_valid()中设置的,而model.clean()是由表单验证过程调用的。

我这里有鸡蛋问题。我正在考虑将请求参数设置为

中的kwargs形式
def get_form_kwargs(self, **kwargs):
    kwargs = super(CreateAdvertisment, self).get_form_kwargs()
    kwargs['advertiser'] = self.advertiser
    kwargs['position'] = self.position
    ....

然后将它们放入表单中的表单实例。 init ()

def __init__(self, *args, **kwargs):
    advertiser = kwargs.pop('advertiser')
    position = kwargs.pop('position')
    # .. and so on
    super(AdvertismentCreateForm, self).__init__(*args, **kwargs)

由于某些原因,我不认为这是非常pythonic。有没有人有更好的主意?我会发布我的解决方案。

2 个答案:

答案 0 :(得分:0)

我认为覆盖get_form_kwargs是可以的。如果所有kwargs都是实例属性,那么我将在get_form_kwargs方法中更新实例。那么您就不必覆盖表单__init__,或者更新form_valid方法中的实例属性。

def get_form_kwargs(self, **kwargs):
    kwargs = super(CreateAdvertisment, self).get_form_kwargs()
    if kwargs['instance'] is None:
        kwargs['instance'] = Advertisement()
    kwargs['instance'].advertiser = self.advertiser
    ...
    return kwargs

在模型的简洁方法中,您现在可以访问self.advertiser

答案 1 :(得分:0)

alasdairs提案工作正常我现在有以下内容:

def get_form_kwargs(self, **kwargs):
    kwargs = super(CreateAdvertisment, self).get_form_kwargs()

    if kwargs['instance'] is None:
        kwargs['instance'] = Advertisement()

    kwargs['instance'].advertiser = self.advertiser
    kwargs['instance'].share_type = self.share_type
    kwargs['instance'].country = self.country
    kwargs['instance'].postal_code = self.postal_code
    kwargs['instance'].position = self.position

    return kwargs

def form_valid(self, form):

    ret = super(CreateAdvertisment, self).form_valid(form)
    return ret

当然不再需要覆盖form_valid。我刚刚包含在这里是为了显示我们不再设置实例字段,因为这已经在get_form_kwargs()中完成了