2017-03-12 29 views
0

我使用通價值爲{{form.Product_ID}}在HTML的Django

{{ form.Product_PId }} 

,使這個領域

反正是有過這個值

{{ Product.PId }} 

其中PId是來自另一個數據庫的主鍵

和是這樣

<input id="id_Product_ID" min="0" name="Product_ID" type="number" value="{{Product.PId}}" required=""> 

,使得最終結果將是象

<input id="id_Product_ID" min="0" name="Product_ID" type="number" value="1" required=""> 

**總結問題

是有辦法來傳遞{{Product.PId }}轉換爲{{form.Product_PId}} ,以便{{Product.PId}}的值可以變成從另一個數據庫取得的可用數字**

re ference

forms.py

class PlaceOrder(forms.ModelForm): 

    class Meta: 
     model = Order 
     fields = ["Product_ID","HowMany","DateSubmit",] 

HTML

{% for Product in Display_Product %} 
     <form method="post" action="" id="CartInput"> {% csrf_token %} 
      <div> 
       {{ form.Product_ID }} 
       {{ form.HowMany }} 
       {{ form.DateSubmit }} 
      </div> 
      <div> 
       <input name="Cart{{ Product.PId }}" type="submit" value="Add to Cart"> 
      </div> 
     </form> 
{% endfor %} 

views.py

class Catalogue(generic.ListView, ModelFormMixin): 
    template_name = 'Shop/Catalogue.html' 
    model = models.Order 
    form_class = forms.PlaceOrder 

    def get(self, request, *args, **kwargs): 
     Display_Product = Product.objects.all() 
     now = datetime.datetime.now() 
     *** tried this one but failed, it just pass in the string {{Product.PId}} and not turn into number *** 
     form = PlaceOrder(initial= {'Product_ID': "{{Product.PId}}"}) 
     context = { 
      'form': form, 
      'date': now, 
      'Display_Product': Display_Product 
     } 
     return render(request, 'Shop/Catalogue.html', context) 

感謝和抱歉的長期問題

回答

0

使用{{}}引用對象的語法是僅用於模板。 在您的視圖中,您應該在傳遞初始值時使用Object.id。

... 
# Get the object that you need 
product = Product.objects.first() 
# Define your initial values 
form = PlaceOrder(initial= {'Product_ID': product.id }) 
+0

好謝謝你的回答將在稍後嘗試,當我回到我的答案時,我會等待幾個更多的答案,然後我選擇正確的答案: –

0

這就是我一直在尋找,發現我可以用不同的形式,方法,並結合他們

我就會把它在這裏希望有人可能會發現它很有用

<form method="post" action="" id="CartInput"> {% csrf_token %} 
      <div> 
       <input name="Product_ID" type="hidden" value="{{ Product.PId }}" > 
       <input name="HowMany" type="number" value="1" > 
       {{ form.DateSubmit }} 
      </div> 
      <div> 
       <input name="Cart{{ Product.PId }}" type="submit" value="Add to Cart"> 
      </div> 
     </form>