我正在使用django作为框架来创建库存管理系统。我有一个简单的模型,其中包含product列和order_amount列。我希望用户能够使用modelformset更新的唯一部分是order_amount列。 Django会自动使用字段名称“订单金额”标记每个表单。我想要做的是将每个表单标记为要在“产品”字段中更新的实例。
models.py
class Sysco_Products(models.Model):
Products = models.CharField(max_length = 200)
order_amount = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.Products
class meta:
managed = True
db_table = 'sysco_products'
forms.py
from django import forms
from .models import Sysco_Products
class orderform(forms.ModelForm):
class Meta:
model = Sysco_Products
fields = ('order_amount',)
views.py
class SyscoOrder(TemplateView):
template_name= "SyscoOrder.html"
def get(self, request):
OrderFormSet = modelformset_factory(Sysco_Products, fields=('order_amount',))
context = {
'OrderFormSet' : OrderFormSet,
}
return render(request, self.template_name, context)
def post(self, request):
OrderFormSet = modelformset_factory(Sysco_Products, fields=('order_amount',))
formset = OrderFormSet(request.POST,)
if formset.is_valid():
formset.save()
return redirect('Order')
context ={
'formset' : formset,
}
return render(request, self.template_name, context)
答案 0 :(得分:0)
您的意思是类似field.label = f"{sysco_product_instance.Products} amount:"
吗?
这应该有效:
from django.utils.translation import gettext
class orderform(forms.ModelForm):
class Meta:
model = Sysco_Products
fields = ('order_amount',)
def __init__(self, *args, **kwargs):
super(self, orderform).__init__(*args, **kwargs)
if self.instance.Products.strip():
self.fields['order_amount'].label = gettext("%(product_name)s amount:").format(product_name=self.instance.Products)