【发布时间】:2019-08-26 20:30:40
【问题描述】:
我是 Python/Django 的新手,但工作很努力
为了训练自己,我正在开发一个简单的视图,它会
- 通过表单获取输入 (DecimalField)
- 将其传递给视图,在视图中根据我的类方法执行计算
- 将其显示在我的模板上,在 InputForm 本身下方和我的其他类/对象属性旁边
++CODE UPDATE++ 表单中的值被截获并通过 {data} 传回模板,但我无法将其传递给 Model 方法...我应该将函数实例化放在视图中的什么位置?或者我的身份有问题...
最后,我的模板看起来像:
<br>
{% for list in list %}<br>
<div> {{ list.price }} <div> <div> {{ list.newprice}} <br><br>
当然是我已经在使用的 css
型号:
class Product(models.Model):
name = models.CharField(max_length=20)
cost = models.DecimalField(decimal_places=2, max_digits=5)
price = models.DecimalField(decimal_places=2, max_digits=5)
def __str__(self):
return self.name
def newprice(self, input):
newprice = self.price * input
return newprice
表格:
class MultiplierForm(forms.Form):
multiplier = forms.IntegerField(label='Your cost')
查看:
def multi(request):
list = Product.objects.all()
data = 0
if request.method == "POST":
form = MultiplierForm(request.POST or None)
if form.is_valid():
data = request.POST.get('value_from_form')
else : form = MultiForm(request.POST or None)
p = Product.newprice() ##this code crash the server.
##If you I it above the else :form the template display
## but crashes when I submit a value with a
## Function is Missing Argument error
p(data)
return render(request, 'viewinventory/multi.html', {'form': form, 'list': list, 'data': data})
++CODE UPDATE++ 表单中的值被截获并通过 {data} 传回模板,但我无法将其传递给 Model 方法...我应该将函数实例化放在视图中的什么位置?或者我有身份问题...... 我希望保持简单,避免进入过滤器等未知领域
【问题讨论】:
-
您要保存该值还是只想显示它?编辑:另外,您是想根据相同的乘数将列表中的所有价格相乘,还是希望人们能够为不同的产品设置不同的乘数?
-
我不需要保存输入值。我只需要从 MultiplierForm 中截取它,将其传递给 Model 方法函数(因此它返回一个 list.newprice 值,我可以在模板中显示列表中所有产品的循环)我想我有点迷失了我必须在视图中使用的语法来捕获输入值并将其传递给乘法器方法函数
标签: django model calculation