1
1
1998or22021-04-19 20:43:34
Django
1998or2, 2021-04-19 20:43:34

How to make mandatory one of two fields in Django model?

Such a question in general,

There is a model:

Phone(Model):
iphone = charfield...bla-bla-bla
android = charfield bla bla bla


There will be a form for entering these fields, and at the bottom there is a Submit button. It is necessary that it be so that the user can fill in one of the two fields, or both fields at once. But not empty - with both fields empty, so that there is an error. And one field is empty, the second is filled - so that it is allowed, and both fields are filled - also so that it is allowed.

I guess that this will need to be implemented in forms.py or views.py, but tell me how? Also what to specify in model - blank=True on both fields?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
maksam07, 2021-04-19
@maksam07

1. In the model - blank=True for both fields
2. In forms.py you make a class based on the model. Actually, both fields will be available for you to fill in, and both of them can also be empty.
2.1. In the class, you create a method a la clean() , in which you clear these fields from nasty things, and then you do a type check:

if not iphone and not android:
    raise ValidationError("Укажи хоть что-то")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question