2012-05-03 90 views
1

我在一個基於django的網站上有一個文本區域,用於顯示數據庫字段的內容。 我希望能夠編輯此字段並將其提交給更新數據庫中字段的函數。在不改變url的情況下在Django頁面上提交表單

我知道如何在views.py中調用一個函數,然後將使用render_to_response的查詢結果發回給新的網頁。

總之,我如何在不需要引用其他url的情況下使用html表單在django/python腳本中調用函數?

回答

2

它通常推薦使用Post/Redirect/Get模式,例如:

def myview(request, **kwargs): 

    if request.POST: 
     # validate the post data 

     if valid: 
      # save and redirect to another url 
      return HttpResponseRedirect(...) 
     else: 
      # render the view with partial data/error message 


    if request.GET: 
     # render the view 

     return render_to_response(...)  
+0

右鍵 - 儘管如果該信息是無效的,你要確保重新呈現部分數據的視圖。 – Dougal

+0

@Dougal,好點 - 我已經更新了我的答案。 – BluesRockAddict

2

使用Ajax:

1)創建一個視圖來處理表單提交:

def my_ajax_form_submission_view(request): 
    if request.method == 'POST': 
     form = MyForm(request.POST) 
     if form.is_valid(): 
      # save data or whatever other action you want to take 
      resp = {'success': True} 
     else: 
      resp = {'success': False} 

     return HttpResponse(simplejson.dumps(resp), mimetype='application/json') 

    else: 
     return HttpResponseBadRequest() 

然後,紮緊查看你的urlpatterns

2)通過AJAX提交表單(使用s jQuery):

$('#my-form-id').submit(function(){ 
    var $form = $(this); 
    $.post('/url/to/ajax/view/', $form.serialize(), function(data, jqXHR){ 
     if (data.success) { 
      alert('Form submitted!'); 
     } else { 
      alert('Form not valid'); 
     } 
    }); 
    return false; 
}); 

這就是基礎知識。您可以並應該提供更詳細的回覆響應,錯誤處理,表單驗證/檢查等。

1

這是我一直使用的標準視圖代碼模式。

def payment_details(request, obj_id): 
    yourobj = get_object_or_404(Obj, pk=obj_id) 
    form = TheForm(instance=yourobj) 

    if request.method == 'POST': 
     form = TheForm(request.POST, instance=yourobj) 
     if form.is_valid(): 
      yourobj = form.save() 
      messages.success(request, 'Yourobj is saved!') 
      url = reverse('SOMEURL') 
      return redirect(url) 

    template = 'SOMETEMPLATE' 
    template_vars = {'TEMPLATEVARS': TEMPLATEVARS} 
    return render(request, template, template_vars) 

看着自己的Advanced Forms talk在DjangoCon,人們可以重新寫這樣的上述觀點:

def payment_details(request, obj_id): 
    yourobj = get_object_or_404(Obj, pk=obj_id) 
    form = TheForm(request.POST or NONE, instance=yourobj) 

    if request.method == 'POST' and form.is_valid(): 
     yourobj = form.save() 
     messages.success(request, 'Yourobj is saved!') 
     url = reverse('SOMEURL') 
     return redirect(url) 

    template = 'SOMETEMPLATE' 
    template_vars = {'TEMPLATEVARS': TEMPLATEVARS} 
    return render(request, template, template_vars) 
相關問題