[英]Django ModelForm not saving data to database, Form.save is not working?
[英]form.save wont save data and no rows added to database
我有一個模型,如下所示:
class ProductLeastDiscountLog(LoggableModel):
product = models.ForeignKey(ProductType, verbose_name='a', on_delete=models.CASCADE, related_name='least_discount_log')
n_weeks = models.IntegerField('a', null=True, blank=True)
buy_price = models.BigIntegerField('a a', null=True, blank=True)
future_sell_price = models.BigIntegerField('a a', null=True, blank=True)
mean_sell_prediction = models.IntegerField('a a a a a', null=True, blank=True)
discount_factor = models.FloatField('a a a', null=True, blank=True)
least_discount = models.FloatField('a a a', null=True, blank=True)
我想使用一個模型將該模型的對象添加到數據庫:
class LeastDiscountForm(BaseModelForm):
class Meta:
model = ProductLeastDiscountLog
fields = ('n_weeks','buy_price', 'future_sell_price', 'mean_sell_prediction', 'discount_factor')
但是在調用form.save db后仍然為空:
def action_view(self, http_request, selected_instances):
if http_request.method == 'POST':
form = self.modelForm(http_request.POST, http_request.FILES, instance=selected_instances[0],
http_request=http_request)
print('let me see if form is vaid')
if form.is_valid():
print('form is valid')
form.save()
form = None
else:
form = self.modelForm(instance=selected_instances[0], http_request=http_request)
return render(http_request, 'manager/actions/add_edit.html', {'form': form, 'title': self.form_title})
您必須像這樣更改表格:
class LeastDiscountForm(ModelForm):
class Meta:
model = ProductLeastDiscountLog
fields = ('n_weeks','buy_price', 'future_sell_price', 'mean_sell_prediction', 'discount_factor')
...
def action_view(self, http_request, selected_instances):
if http_request.method == 'POST':
form = self.modelForm(http_request.POST, http_request.FILES, instance=selected_instances[0])
print('let me see if form is vaid')
if form.is_valid():
print('form is valid')
form.save()
form = None
else:
form = self.modelForm(instance=selected_instances[0])
return render(http_request, 'manager/actions/add_edit.html', {'form': form, 'title': self.form_title})
表單必須是ModelForm的子級,而不是BaseModelForm。 並且您不能傳遞額外的參數來初始化表單(http_request)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.