简体   繁体   中英

Django Open / Edit record instead of Creating new

I have a CustomerAddForm and a CustomerOverview HTML Table. When i add a new record in the CustomerAddForm it appears in the CustomerOverview HTML table. I also have the functionality to open existing customers from the CustomerOverview HTML by clicking on the customer name.

When i open an existing Customer it opens the Customer fine, but when i hit submit it saves the opened customer to a new record. If i hard code the Customer ID in the view it saves the given ID. So it looks like no id is pushed through when hitting submit.

Normal;

def customeradd(request, id = None)

With hardcoded id;

def customeradd(request, id = 1)

My views.py; where it seems after hitting submit request.method == 'POST' is always true. and the else statement is never run.

def customeradd(request, id = None): 
    if id:
        customer = Customer.objects.get(pk = id)
    else:
        customer = None

    if request.method == 'POST':
        form = CustomerAddForm(request.POST or None, instance = customer)
        if form.is_valid():
            save_it = form.save(commit=False)
            save_it.save()
            messages.success(request, 'Customer added succesfully')
            return HttpResponseRedirect('/customeroverview/')
        else:
            messages.error(request, 'Customer save error, please check fields below')
    else:
        form = CustomerAddForm(instance = customer)
        if form.is_valid():
            form.save()
            messages.success(request, 'Customer edited succesfully')
            return HttpResponseRedirect('/customeroverview/')

    return render_to_response("customer-add.html",
                              {"customer_add_form": form},
                              context_instance=RequestContext(request))

my forms.py (django-crispy-form)

class CustomerAddForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CustomerAddForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_action = '/customeradd/'     

        self.helper.add_input(Submit('submit', 'Submit'))
        self.helper.add_input(Button('cancel', 'Cancel'))

    class Meta:
        model = Customer

my urls.py

url(r'^customeroverview/$', 'customer.views.customeroverview', name='customeroverview'),
url(r'^customeradd/$', 'customer.views.customeradd', name='customeradd'),
url(r'^customeradd/(?P<id>\w+)$', 'customer.views.customeradd', name='customeredit'),

customer-add.html

{% block content %}

{% load crispy_forms_tags %}
{% crispy customer_add_form customer_add_form.helper %}


{% endblock %}

use this:

def customeradd(request, id=None): 
    if id:
        customer = Customer.objects.get(pk = id)
    else:
        customer = Customer()

    if request.method == 'POST':
        form = CustomerAddForm(request.POST, instance=customer)
        if form.is_valid():
            form.save()
            messages.success(request, 'Customer added succesfully')
            return HttpResponseRedirect('/customeroverview/')
        else:
            messages.error(request, 'Customer save error, please check fields below')
    else:
        form = CustomerAddForm(instance = customer)

    return render_to_response("customer-add.html",
                              {"customer_add_form": form},
                              context_instance=RequestContext(request))

and replace

self.helper.form_action = '/customeradd/'

with

self.helper.form_action = ''

in your forms.py

You can use a specific function to edit a customer:

@require_POST
@csrf_protect
def customeredit(request, id=None): 

    edited_customer = CustomerAddForm(request.POST)

    if edited_customer.is_valid():
        customer = edited_customer.save(commit=False)
        customer.id = id
        customer.save()
        messages.success(request, 'Customer edited succesfully')
        return HttpResponseRedirect('/customeroverview/')
    else:
        messages.error(request, 'Customer save error, please check fields below')
        return render_to_response("customer-add.html",
                          {"customer_add_form": edited_customer},
                          context_instance=RequestContext(request))

That means you need to modify urls.py

url(r'^customeredit/(?P<id>\w+)$', 'customer.views.customeraedit', name='customeredit'), 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM