0

I can create a form with Django that has a mysql background. I wonder if it is possible to create a code that allows you to delete an object. So supposing I had a client called "Tony", and I wanted to create some python code that allowed me to delete Tony. How would I do that?

#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))
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Shehzad009
  • 1,547
  • 6
  • 28
  • 42

1 Answers1

0
def delete_client(request, client_id): 
    client = Client.objects.get(id=client_id)
    client.delete()
    redirect_to = '/index/'
    return HttpResponseRedirect(redirect_to) 
Seitaridis
  • 4,459
  • 9
  • 53
  • 85
  • Ok this works. One question I would like to ask you. Suppose if you have a form that work but want to write a view that could "edit" this form. How would you write it up? I have had this problem for a long time. – Shehzad009 Dec 17 '10 at 15:30
  • A view that can edit a form. In other words, editing existing forms. – Shehzad009 Dec 17 '10 at 15:43
  • def edit_client(request, client_id): client = Client.objects.get(id=client_id) if request.method == 'POST': client_form = ClientForm(request.POST, instance=client) if client_form.is_valid(): client_form.save() redirect_to = '/index/' return HttpResponseRedirect(redirect_to) else: client_form = ClientForm(instance=client) – Seitaridis Dec 17 '10 at 20:54