开发者

Django ModelForm validation based on certain circumstances?

I have a form:

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

Based off of:

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

and basically if the type is Image I want link and media required, however if it is Code I want code required. Is there any way to do this or force validate those fields based on certain conditions?

My current processing method is below:

@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))

I looked in the documentation but it said to force save, is there any other better way? Thank you so much from a Django noob.


Take a look at the documentation for forms around validating fields that depend on other fields: https://docs.djangoproject.com/en/1.11/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

Your model will need to allow the fields to be blank so you don't get required validation errors from the model when certain combinations are invalid. Instead, ensure the correct combination of field values exists at the form level.

Hope that helps you out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜