正如您在html下面看到的那样,我的代码根据数据生成一个表,每行中都有一个表单。当您提交表单时,它会根据它所在的行发布数据。这很有效。但是,我需要字段中的初始数据对于每一行是不同的。它必须是基于与行关联的数据的计算值。是否可以使用一些django模板代码来设置它?或者是否有一种方法可以从视图中传递该值?
{% for liquor in filter %}
<tr>
<td>{{ liquor.LiquorCode }}</td>
<td><a href="/liquors/get/{{ a.StoreID }}/{{ liquor.id }}/{{ SPI }}/">{{ liquor.BrandName }}</a></td>
<td>{{ liquor.VendorName }}</td>
<td>{{ liquor.LiquorType }}</td>
<td>{{ liquor.Proof }}</td>
<td>{{ liquor.BottleSize }}</td>
<td>{{ liquor.PackSize }}</td>
<td>{{ liquor.OffPremisePrice }}</td>
<td>{{ liquor.ShelfPrice }}</td>
<td>{{ liquor.GlobalTradeItemNumber1 }}</td>
<td><form action="/stores/quickadd/{{ a.StoreID }}/{{ liquor.id }}/{{ SPI }}/" method="post">{% csrf_token %}
{{form.as_p}}
<input type="submit" name="submit" value="Add to Store"></td>
</tr>
{% endfor %}
以下是我的观点:
def product_list(request, store_id):
store = Store.objects.get(StoreID=store_id)
f = ProductFilter(request.GET, queryset=Liquor.objects.all())
LiqSPI = StoreLiquor.objects.filter(storeID=store_id).count()
AddLiqForm = AddLiquorForm()
args = {}
args['filter'] = f
args['a'] = store
args['SPI'] = LiqSPI + 1
args['form'] = AddLiqForm
return render(request,'UPC_filter.html', args)
def quickadd(request, store_id, liquor_id, SPI):
storeID = Store.objects.get(StoreID=store_id)
liquorID = Liquor.objects.get(id=liquor_id)
if request.method == "POST":
AddLiqForm = AddLiquorForm(request.POST)
if AddLiqForm.is_valid():
StoreLiqID = AddLiqForm.save(commit=False)
StoreLiqID.storeID = storeID
StoreLiqID.liquorID = liquorID
StoreLiqID.StorePrice = request.POST.get('StorePrice', '')
StoreLiqID.SPI = SPI
StoreLiqID.save()
return HttpResponseRedirect('/stores/UPC_Scan/%s' % store_id)
答案 0 :(得分:0)
根据您的代码,我可以看到您正在使用名为AddLiquorForm的django形式 如果要在表单加载时填充初始数据,可以使用为表单(AddLiquorForm)编写的类的 _ init 方法。
class AddLiquorForm(forms.ModelForm): #code responsible to create form fields def __init__(self, user, *args, **kwargs): super(AddLiquorForm, self).__init__(*args, **kwargs) self.fields['field1'].initial = 'whatever you want' self.fields['field2'].initial = 'whatever you want' self.fields['field3'].initial = 'whatever you want' # other fields
答案 1 :(得分:0)
要根据Liquor
模型中的存储值显示计算值,您可以使用模型属性。
请参阅https://docs.djangoproject.com/en/dev/topics/db/models/#model-methods
E.g。
class Liquor(models.Model):
""" Your fields up here.. liquor_code, liquor_type, proof """
def _get_breed_proof(self):
"Returns the liquor type + proof."
return '%s %s' % (self.proof, self.liquor_type)
breed_proof = property(_get_breed_proof)
然后,您可以在模板中使用任何其他模型属性 - liquor.breed_proof
。