2011-06-27 31 views
7

我在編輯表單,它正確加載數據當我點擊時購買保存它在數據庫中創建新條目。在Django中編輯表單創建新實例

這裏是視圖功能

def create_account(request): 


    if request.method == 'POST': # If the form has been submitted... 
     form = AccountForm(request.POST, request.FILES) # A form bound to the POST data 
     if form.is_valid(): # All validation rules pass 
       form.save() 
       return HttpResponseRedirect('/thanks/') # Redirect after POST 
    else: 
     form = AccountForm() # An unbound form 

    return render_to_response('account_form.html', { 
      'form': form, 
    }) 

-

def edit_account(request, acc_id): 

    f = Account.objects.get(pk=acc_id) 
    if request.method == 'POST': # If the form has been submitted... 
     form = AccountForm(request.POST, request.FILES) # A form bound to the POST data 
     if form.is_valid(): # All validation rules pass 
       form.save() 
       return HttpResponseRedirect('/thanks/') # Redirect after POST 
    else: 
     form = AccountForm(instance=f) # An unbound form 

    return render_to_response('account_form.html', { 
      'form': form, 
    }) 

我真的需要有編輯的獨立功能分開,並刪除。我能做的所有功能於一體

模板

<form action="/account/" method="post" enctype="multipart/form-data" > 
    {% csrf_token %} 
    {% for field in form %} 
     <div class="fieldWrapper"> 
      {{ field.errors }} 
      {{ field.label_tag }}: {{ field }} 
     </div> 
    {% endfor %} 
    <p><input type="submit" value="Send message" /></p> 
    </form> 
+0

你的意思是我應該使用diff功能比保存? – user2134226

+0

請忽略S.Lott的評論,這是不準確的。 –

回答

11

你缺少在POST部分instance說法。

取而代之的是:

form = AccountForm(request.POST, request.FILES) # A form bound to the POST data 

你應該使用這樣的:

form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data 

一旦你添加到添加/編輯表格,您將能夠在同一時間添加/編輯。

如果instance=None將被添加並且如果instance是實際帳戶則更新。

def edit_account(request, acc_id=None): 
    if acc_id: 
     f = Account.objects.get(pk=acc_id) 
    else: 
     f = None 

    if request.method == 'POST': # If the form has been submitted... 
     form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data 
     if form.is_valid(): # All validation rules pass 
      form.save() 
      return HttpResponseRedirect('/thanks/') # Redirect after POST 
    else: 
     form = AccountForm(instance=f) # An unbound form 

    return render_to_response('account_form.html', { 
     'form': form, 
    }) 
+0

對不起,我仍然困惑。 1)你可以提供我應該使用的代碼,只有一個編輯功能,並添加 – user2134226

+0

在創建我沒有任何參數,但在編輯我需要傳遞參數,所以我怎麼能結合。我也需要不同的模板編輯becasue然後我需要改變形式的行動edit_account – user2134226

+0

@ bidu:我已經添加了一個例子,應該工作:) – Wolph

1

您是否嘗試過這樣的事情?

# Create a form to edit an existing Object. 
    a = Account.objects.get(pk=1) 
    f = AccountForm(instance=a) 
    f.save() 

# Create a form to edit an existing Article, but use 
# POST data to populate the form. 
    a = Article.objects.get(pk=1) 
    f = ArticleForm(request.POST, instance=a) 
    f.save()