2010-12-17 58 views
0

我可以用Django創建一個具有mysql背景的表單。我想知道是否有可能創建一個允許您刪除對象的代碼。假設我有一個名爲「Tony」的客戶端,我想創建一些允許我刪除Tony的Python代碼。我會怎麼做?如何刪除一個入口對象對象

#forms.py 
from django import forms 
from c2duo.accounts.models import * 

class ClientForm(forms.ModelForm): 
    client_number = forms.IntegerField() 
    name = forms.CharField(max_length=80) 
    address = forms.CharField(max_length=250) 
    telephone = forms.CharField(max_length=20) 
    fax = forms.CharField(max_length=20) 
    email = forms.EmailField() 
    alternative_name = forms.CharField(max_length=80, required=False) 
    alternative_address = forms.CharField(max_length=250, required=False) 
    alternative_telephone = forms.CharField(max_length=20, required=False) 
    alternative_email = forms.EmailField(required=False) 

     class Meta: 
     model = Client 
     fields = ('client_number','name','address','telephone','fax','email','alternative_name','alternative_address','alternative_telephone','alternative_email' 

#views.py 
@login_required 
def add_client(request): 
    if request.method == 'POST': 
     form = ClientForm(request.POST or None) 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect('/index/') 
    else: 
     form = ClientForm() 
    return render_to_response('add_client.html', {'form': form}, context_instance=RequestContext(request)) 
+0

寫一個刪除來看。 – 2010-12-17 13:58:23

回答

0
def delete_client(request, client_id): 
    client = Client.objects.get(id=client_id) 
    client.delete() 
    redirect_to = '/index/' 
    return HttpResponseRedirect(redirect_to) 
+0

好的這個作品。我想問你一個問題。假設你有一個表單可以工作,但想寫一個可以「編輯」這個表單的視圖。你會如何寫它?我有這個問題很長一段時間了。 – Shehzad009 2010-12-17 15:30:29

+0

可以編輯表單的視圖。換句話說,編輯現有的表單。 – Shehzad009 2010-12-17 15:43:33

+0

DEF edit_client(請求,CLIENT_ID): 客戶= Client.objects.get(ID = CLIENT_ID) 如果request.method == 'POST': client_form = ClientForm(request.POST,實例=客戶端) 如果client_form。 is_valid(): client_form.save() redirect_to的= '/指數/' 返回HttpResponseRedirect(redirect_to的) 其他: client_form = ClientForm(例如=客戶端) – Seitaridis 2010-12-17 20:54:42