Tutorial :Django: Only one of two fields can be filled in



Question:

I have this model:

class Journals(models.Model):      jid = models.AutoField(primary_key=True)      code = models.CharField("Code", max_length=50)      name = models.CharField("Name", max_length=2000)      publisher = models.CharField("Publisher", max_length=2000)      price_euro = models.CharField("Euro", max_length=2000)      price_dollars = models.CharField("Dollars", max_length=2000)  

Is there a way to let people fill out either price_euro or price_dollars?

I do know that the best way to solve the problem is to have only one field and another table that specify the currency, but I have constraints and I cannot modify the DB.

Thanks!


Solution:1

I'd agree with T. Stone that customizing the form is the best way to go. If you can't do that, or in addition to that, you can enforce the rule with a custom clean() method on your form. Just bear in mind that any validation errors you throw in the clean() method won't be attached to specific fields, but to the form itself.


Solution:2

It's not necessary that the interface reflects the data structure. You could simply have your UI present them with 1 currency field and then a selection between USD and Euro, then when the data is committed back to the Journals model, you simply assign it to the correct field and clear the other.


Solution:3

I would do it on the model clean() method. That way it will work with the Admin site as well.

https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.clean


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »