![](/img/trans.png)
[英]React: update a field value based on another field in dynamically generated form
[英]Update Field With Another Field Value Dynamically in Django
我有兩個模型ModelA和ModelB
class ModelA(models.Model):
amount_per_product=models.PositiveIntegerField(default='', help_text="e.g 10000")
class ModelB(models.Model):
no_of_product_needed=models.PositiveIntegerField()
amount_to_pay=models.PositiveIntegerField()
modela=models.ForeignKey(ModelA)
現在,每當用戶在no_of_product_needed
字段中輸入數字(例如2
時,Django都應在保存之前在amount_to_pay
字段中顯示用戶將支付的總金額。 因此,用戶可以看到總金額,如果他/她想購買,則用戶將單擊“購買”,而Django會將總金額保存在amount_to_pay
字段中。
我寫了一個pre_save鈎子,但是沒有用。 每當我在no_of_product_needed
字段中插入數字時,它都不會在amount_to_pay
字段中顯示總金額。
鈎子
class ModelB(models.Model):
no_of_product_needed=models.PositiveIntegerField()
amount_to_pay=models.PositiveIntegerField()
modela=models.ForeignKey(ModelA)
def __init__(self, *args, **kwargs):
super(ModelB, self).__init__(*args, **kwargs)
pre_save.connect(self.before_buying, sender=ModelB)
def before_buying(self, sender, instance, *args, **kwargs):
initial= self.modela.amount_per_product
amt_needed= self.no_of_product_needed
final_amt=int(initial) * int(amt_needed)
self.amount_to_pay= self.final_amt
我想念什么? 可以在JS中完成嗎?
“ Django應該在保存之前在amount_to_pay字段中顯示用戶將支付的總金額”
django的目標不是更新客戶端視圖。 您的pre_save方法不會更新模板。
如果您想通知用戶有關amount_to_pay的信息,則需要在客戶端使用Javascript來完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.