如果它適合你,整個事情可以用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框架都可以。
非常感謝!我會在這個方向嘗試一些東西! – vmassuchetto 2011-02-18 02:49:04