2011-02-17 50 views
1

我需要一個特殊的部分到一個形式,我無法想象現在如何做到這一點。我會盡量讓自己清楚。Django嵌入ManyToMany表格

假設我有一個像「Sale」的模型。這自然是一套正在銷售的產品。我不想選擇像ManyToMany這樣的產品,我只是想要有兩個CharFields,比如「Name」和「Price」,還有一個「Add」按鈕。當我填充這些字段並按下「添加」時,將會有一行ajax動作,將一行放入正下方的框中。如果我想通過單擊此行中的「刪除」按鈕來刪除其中一行,那也是同樣的事情。

這基本上是一個ManyToMany字段,我可以在「即時」插入它們。

我對其他解決方案完全開放。 謝謝。

回答

1

如果它適合你,整個事情可以用JavaScript來完成。創建用於創建/編輯/刪除的處理程序。爲GET創建呈現空白表單並驗證/保存POST,將新項目添加到應該屬於的Sale。編輯/刪除應該相當明顯。

我可能只是讓處理程序呈現html partials,使用javascript將html拉入到DOM的DOM中,並使用POST將數據更改爲服務器。

假設模型,

class Sale(models.Model): 
    items = models.ManyToMany('Item', related_name='sales') 
    # ... 

class Item(models.Model): 
    # ... 

然後,我們可以創建一些處理程序是這樣的:

def create_item(request, saleID=""): 
    sale = get_object_or_404(Sale, <ID>=saleID) # <- get the sale obj 

    if request.method == 'POST': 
    form = ItemForm(request.POST) # <- could take the sale here and do .add() in the save() 
    if form.is_valid(): 
     i = form.save() 
     sale.items.add(i) # <- or, add in the view here 
     if request.is_ajax(): 
     return HttpResponse('ok') 
     # redirect with messages or what have you if not ajax 
    else: 
    # make a blank form and whatnot 
    # render the form 

def edit_item(request, id|pk|slug=None): 
    item = get_object_or_404(Item, slug=slug) 
    if request.method == 'POST': 
    # do the form is_valid, form save, return 'ok' if ajax, redirect if not ajax 
    else: 
    form = EditForm(instance=item) 
    # render the form 

def delete_item(request, id|pk|slug=None): 
    if request.method == 'POST': 
    # delete the item and redirect, or just return "ok" if is_ajax 
    # render confirmation dialog 

針對前端代碼,我會用http://api.jquery.com/load/ HTTP的某種組合://api.jquery .com/jQuery.get /和http://api.jquery.com/jQuery.post/等,但任何JavaScript框架都可以。

+0

非常感謝!我會在這個方向嘗試一些東西! – vmassuchetto 2011-02-18 02:49:04