开发者

Django: required together?

Do you know this:

unique_together = ("name", "date")

Does something similar exist for required fields?

开发者_如何学C

I have 2 fields: ipv4 and ipv6. There are different wireless networks on the map, we call them "islands" cos they're not connected phisically but through a VPN tunnel.

Some islands use ipv4 and they're implementing ipv6, while others are ipv6 only. If i set ipv4 to required it would be problematic for the ones that are ipv6 only and if I set ipv6 to required the ones that are mainly ipv4 will have troubles.

There are 2 things I could do: set both fields as not required or set it in a way so at least one of the two must be filled.

The first solution is easy but not so nice, while the second is nice but I don't know if it's possible without hacking django.

The app is open source.

Source: https://github.com/ninuxorg/nodeshot/

Demo: http://map.ninux.org


You could write a clean method for your model. This will be called whenever you clean a model form, including the django admin.

from django.core.exceptions import ValidationError

class MyModel(model.Model):
    <field definitions>

    def clean(self):
        """
        Require at least one of ipv4 or ipv6 to be set
        """
        if not (self.ipv4 or self.ipv6):
            raise ValidationError("An ipv4 or ipv6 address is required")

See the docs on Validating objects for more details.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜