2012-10-10 20 views
1

我是一個django新手。在Django中更新表單。如何設計?

我有這樣的模式:

class Item(models.Model): 
    name = models.CharField(max_length=255) 
    quantity = models.IntegerField() 

如何創建視圖來更新我的所有項目的數量是多少?

觀點:

def item_list(request): 
    item = Product.objects.all()[:6] 
    return render_to_response('item.html',{'item':item},context_instance=RequestContext(request)) 

形式:

from django import forms 

class QuantityForm(forms.Form): 
    quan = forms.IntegerField() 

模板:

{% for i in item %} 
    {{ i.name }} 
    {{ i.quantity }} 
{% endfor %} 

我試圖做這樣的事情(點擊 「更新」 值quantity後我模型應該實現):

enter image description here

請任何幫助。由於

+0

看看'formsets'。 https://docs.djangoproject.com/en/dev/topics/forms/formsets/ – karthikr

+0

這是唯一的出路?我需要一個簡單的解決方案 – user1732461

+0

formsets很簡單。或者,你可以爲每個創建表單,並做一個ajax提交 – karthikr

回答

3

首先,您需要一個視圖,其中檢索項目標識和數量值,更新相關的Item實例並將您重定向回頁面。這裏有一個例子:

from django.views.decorators.http import require_http_methods 
from django.shortcuts import redirect, get_object_or_404 

@require_http_methods(["POST"]) 
def update_item(request) 
    id = request.POST.get('id', None) #retrieve id 
    quantity = request.POST.get('q', None) #retrieve quantity 
    item = get_object_or_404(Item, id=id) #if no item found raise page not found 
    if quantity: 
     #updating item quantity 
     item.quantity = quantity 
     item.save() 

    return redirect('my-item-list-view-name') 

而且你需要在你urls.py創造URLPATTERN的視圖。例如:

... 
url(r'^update-item/$', 'update_item', name='update_item'), 
... 

然後你就可以在模板的形式爲每個項目:

{% for i in item %} 
    <form action="{% url 'update_item' %}" method="post"> 
     {% csrf_token %} 
     {{ i.name }} 
     <input name="id" type="hidden" value="{{ i.id }}" /> 
     <input name="q" type="text" value="{{ i.quantity }}" /> 
     <input type="submit" value="update" /> 
    </form> 
{% endfor %} 

我想提供一個解決方案儘可能簡單。你應該知道,Django提供了很多很酷的東西,可以幫助你更有效地解決你的問題,比如窗體,模型,表單集...

2

views.py

if request.method=='POST': 
     if 'txt1' in request.POST: 
     if request.POST['txt1']!='': 
      obj=Item.objects.get(pk=request.POST['item1']) 
      obj.quantity=request.POST['txt1'] 
      obj.save() 
     if 'txt2' in request.POST: 
     if request.POST['txt2']!='': 
      obj=Item.objects.get(pk=request.POST['item2']) 
      obj.quantity=request.POST['txt2'] 
      obj.save() 
     if 'txt3' in request.POST: 
     if request.POST['txt3']!='': 
      obj=Item.objects.get(pk=request.POST['item3']) 
      obj.quantity=request.POST['txt3'] 
      obj.save() 
     #continue this code for all 6 items 

更新:

當然

U可以把它放進一個循環:

for i in range(1,6): 
    if 'txt'+str(i) in request.POST: 
     if request.POST['txt'+str(i)]!='': 
     obj=Item.objects.get(pk=request.POST['item'+str(i)] 
     obj.quantity=request.POST['txt'+str(i)] 
     obj.save() 

template

<form method='POST' action=''> 
{% for i in item %} 

     {{ i.name }}:<input type='text' id='txt{{forloop.counter}}' value='{{ i.quantity }}' /><input type='hidden' id='item{{forloop.counter}}' value='{{item.pk}}' /><input type='submit' value='increase' id='sbm{{forloop.counter}}' /> 

{% endfor %} 
</form> 

更新:forloop.counter是櫃檯,1,2,3當前...

2

您可以爲您的item創建ModelForm然後用Formsets,或者如果你可以使用jQuery提交Ajax請求到所選模型

$('<yourbuttonclass').onClick(function(e){ 
    e.preventdefault() 
    $.post(urlToPost, dataFromTextField&csrfmiddlewaretken={{csrf_token}}) 
    .success('Successfully Updated') 
    .... 

In your view: 

#Get the item id from urlconf 
@ajax_request 
def update_view(request, item_id) 
    #Update your item 
    return {'Success': 'Updated to blah'} 

我喜歡用ajax_request裝飾從here發送AJAX響應更新項Django視圖。你也可以發送一個HTTPResponse('Successfully updated')

如果你想創建一個Restful資源將是一個很好的方式,然後你得到一個接口來創建,更新,讀取和刪除一個模式。請閱讀Django Tastypie

+1

謝謝。如何正確使用formset做到這一點?我學習Django。 我需要一個示例 – user1732461

+1

您是否獲得了ModelForm的概念?如果是,那麼只需在您的python django shell中ItemFormSet = formset_factory(ItemForm,extra = 6)並在ItemFormset:print(form.as_table())中打印表單。這應該有助於理解。實際上,我不喜歡這樣一個事實,即超出某個特定點使用自定義小部件在django中定製表單會使其變得雜亂,並且更喜歡使用jQuery來實現相同的效果。你並沒有真正失去很多。 –