我正在尝试制作一个简单的库存应用程序,但是我在重新库存逻辑上遇到了麻烦,例如,如果我购买的新股票的价格与第一只股票的价格不同,我只想获得全部股票的平均价格Shell工作正常,但是当我进入表单时,我总是得到表单输入而不是所需的值,经过一番调查,我发现我正在使用request.POST.get甚至在保存数量= item之前获取实例数据。 。数量!!我现在的问题是如何才能分别获取输入和实例
##models
class Supply(models.Model):
name = models.CharField(max_length=100, unique=True)
quantity = models.PositiveIntegerField()
price = models.DecimalField(max_digits=11, decimal_places=2)
created = models.DateField(auto_now_add=True)
last_modefied = models.DateField(auto_now=True)
def __str__(self):
return self.name
##form
class SupplyForm(forms.ModelForm):
class Meta:
model = Supply
fields = ["name", "quantity", "price"]
#view
def add_supply(request):
form = SupplyForm()
if request.POST:
# getting form input data
name = request.POST.get("name")
quantity = request.POST.get("quantity")
price = request.POST.get("price")
# getting Supply instance
item = Supply.objects.get(name=name)
# instantiating the form
form = SupplyForm(request.POST, instance=item)
if form.is_valid:
# Logic
old_supply = item.quantity * item.price
new_supply = int(quantity) * int(price)
new_quantity = item.quantity + int(quantity)
item.price = (old_supply + new_supply) / new_quantity
item.quantity = new_quantity
form.save()
return redirect("project_list")
return render(request, "restock.html", {"form": form})
答案 0 :(得分:0)
找到了可能需要它的答案: 首先删除modelform并创建一个表单。带有2个新字段的表单
#forms
class RestockForm(forms.Form):
name = forms.CharField(max_length="30")
quantity = forms.IntegerField(min_value=0)
price = forms.DecimalField(max_digits=11, decimal_places=2)
new_quantity = forms.IntegerField(min_value=0)
new_price = forms.DecimalField(max_digits=11, decimal_places=2)
#views
def add_supply(request, pk):
#getting the object
item = get_object_or_404(Supply, pk=pk)
# instantiating the form on using initial since its not a model form
form = RestockForm(initial={"name": item.name, "quantity": item.quantity, "price": item.price})
if request.POST:
# getting form extra input data
quantity = request.POST.get("new_quantity")
price = request.POST.get("new_price")
form = RestockForm(request.POST,)
if form.is_valid():
old_supply = item.quantity * item.price
new_supply = int(quantity) * int(price)
_quantity = item.quantity + int(quantity)
item.price = (old_supply + new_supply) / _quantity
item.quantity = _quantity
# important need to save the object
item.save()
return redirect("project_list")
return render(request, "restock.html", {"form": form})
#urls
path('restock/<int:pk>', stock_views.add_supply, name="restock"),