2016-12-28 71 views
0

我創建了一個表單來創建一個客戶端,另一個來修改它,但問題是修改表單不會帶來數據庫的信息。django從數據庫中提取數據進行編輯

帶一個沒有數據字段的基本表單。

觀點:

def cliente_update(request, id=None): 
    queryset = get_object_or_404(Cliente, id=id) 
    if request.method == 'POST': 
     form = ClienteForm(request.POST or None, instance=instance) 
     if form.is_valid(): 
      instance = form.save(commit=False) 
      instance.save() 
      # return HttpResponseRedirect(instance.get_absolute_url()) 
    else: 
     form = ClienteForm() 
    context = { 
     "titulo": "Editar informacion del Cliente", 
     "queryset": queryset, 
     "form": form, 
    } 
    return render(request, "clientes/form.html", context) 
+0

** ClienteForm **的代碼在哪裏。請分享你的forms.py。 –

回答

2

您需要通過instance參數來傳遞你的Cliente對象在你的ModelForm在else塊。

def cliente_update(request, id=None): 
    instance = get_object_or_404(Cliente, id=id) # renamed from queryset to instance 
    if request.method == 'POST': 
     form = ClienteForm(request.POST or None, instance=instance) 
     if form.is_valid(): 
      instance = form.save(commit=False) 
      instance.save() 
      # return HttpResponseRedirect(instance.get_absolute_url()) 
    else: 
     form = ClienteForm(instance=instance) 

    context = { 
      "titulo": "Editar informacion del Cliente", 
      "form": form, 
     } 
    return render(request, "clientes/form.html", context) 
+1

該實例看起來在名爲變量的非常容易混淆的變量queryset中,該變量肯定應該重命名。 –

+0

我同意,重命名變量。 – ruddra