开发者

django: how to change abstract class's field attributes?

I have the following class with some of the attributes:

class ConsentForm(models.Model):
    title = models.TextField()
    body = models.TextField()
    teacher = models.ForeignKey(User)
    deadline = models.DateField(null=True)

and I want to have a second class ConsentFormDraft which has completely the same fields except that the all of the fields are null=True since it is used to represents a draft form.

I thought that instead of creating all the fields, can I use an abstract class to represent all these fields? If tha开发者_Go百科t's so, how do I specify that the null=True in one of my class and null=False in the draft class?


try to change field attributes in your derived form's constructor:

class ConsentFormDraft(ConsentForm):
    def __init__(self, *args, **kwargs):
        super(ConsentForm, self).__init__(*args, **kwargs)
        # make first field optional
        self.fields[0].required = False

this is not tested.


You could set null = True in the base class and perform a check on save() in the other one. This would require to use the ConsentFormDraft class as a base class and the ConsentForm as inherited:

class ConsentForm(ConsentFormDraft):
    def save(self, request=None, *args, **kwargs):
        # Check for null fields and return an exception
        #
        super(Assessment, self).save(*args, **kwargs)

In fairness, you could check the fields' validity by implementing an explicit form either. It may even be easier than overriding save() in the model.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜