简体   繁体   中英

How do I clone a Django model instance object and show on the Django forms?

So, the first part is pretty clear.

customer = Customer.objects.get(pk=1)
customer.pk = None
customer.save() # Saved a new instance. 
# But i want to modify it

The problem here is that i want to modify that instance, before saving. for that i have to render it on the form in HTML.

How to achieve that?

Suggestions needed.

Greetings.

You modify the pk after the form has been submitted. You pass customer as instance to a CustomerForm and let the form save a new object. Something like:

    class CustomerForm(forms.ModelForm):
        class Meta:
            model = Customer

    def my_view(request):
        customer = Customer.objects.get(pk=1)
        customer.pk = None
        if request.method == 'POST':
            form = CustomerForm(instance=customer)
            if form.is_valid():
                customer = form.save()
                return redirect('...')
        else:
            form = CustomerForm(instance=customer)
        return render(request, 'template', {'form': form})

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