Django ModelForm验证基于某些情况?

时间:2011-09-01 16:19:38

标签: django forms model

我有一张表格:

class AdForm(ModelForm):
    class Meta:
        model = Ad
        widgets = {
            'title': TextInput(attrs={'class': 'small'}),
            'link': TextInput(attrs={'class': 'large'}),
            'code': Textarea(attrs={'class': 'limit', 'cols': 60, 'rows': 20}),
            'clicks': TextInput(attrs={'class': 'tiny', 'value': 0}),
        }

基于:

TYPE_CHOICES = (
    ('Image', 'Image'),
    ('Code', 'Code'),
)

SIZE_CHOICES = (
    ('Leaderboard', 'Leaderboard'),
    ('Banner', 'Banner'),
    ('Skyscraper', 'Skyscraper'),
    ('Square', 'Square'),
)

class Ad(models.Model):
    title = models.CharField(max_length=40)
    type = models.CharField(max_length=5, choices=TYPE_CHOICES)
    size = models.CharField(max_length=11, choices=SIZE_CHOICES)
    link = models.URLField(null=True)
    media = models.ImageField(null=True, upload_to='ads')
    code = models.TextField(null=True, max_length=500)
    clicks = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)
    expires = models.DateTimeField(null=True)

    def __unicode__(self):
        return self.name

基本上如果类型是Image我想要链接和媒体,但是如果它是Code我需要代码。有没有办法做到这一点或根据某些条件强制验证这些字段?

我目前的处理方法如下:

@login_required
def create(request):
    if request.POST:
        form = AdForm(request.POST)

        if form.is_valid():
            status = 'Success'
        else:
            status = 'Failure'
    else:
        form = AdForm()
        status = 'None'

    template = loader.get_template('ads/create.html')
    context = RequestContext(request, {
        'form': form,
        'status': status
    })

    return HttpResponse(template.render(context))

我查看了文档,但它说要强制保存,还有其他更好的方法吗?非常感谢Django noob。

1 个答案:

答案 0 :(得分:1)

请查看有关验证依赖于其他字段的字段的表单的文档:https://docs.djangoproject.com/en/1.11/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

您的模型需要允许字段为空,这样当某些组合无效时,您不会从模型中获得所需的验证错误。相反,请确保在表单级别存在正确的字段值组合。

希望能帮到你。