0

正如您在下面的 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)
4

2 回答 2

0

根据您的代码,我可以看到您正在使用名称为 AddLiquorForm 的 django 形式。
如果您想在表单加载时填充初始数据,您可以使用您为表单( AddLiquorForm )编写的类的_init方法。

类 AddLiquorForm(forms.ModelForm):
    #code 负责创建表单字段
    def __init__(self, user, *args, **kwargs):
        super(AddLiquorForm, self).__init__(*args, **kwargs)
        self.fields['field1'].initial = '随便你'                                        
        self.fields['field2'].initial = '随便你'
        self.fields['field3'].initial = '随便你'
        # 其他字段

 
于 2013-10-30T07:47:04.457 回答
0

要根据模型中存储的值显示计算值Liquor,您可以使用模型属性。

请参阅https://docs.djangoproject.com/en/dev/topics/db/models/#model-methods

例如

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

于 2013-10-30T07:58:13.160 回答