简体   繁体   English

如何克隆 Django 模型实例对象并在 Django 表单上显示?

[英]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.为此,我必须将它呈现在 HTML 的表单上。

How to achieve that?如何做到这一点?

Suggestions needed.需要的建议。

Greetings.你好。

You modify the pk after the form has been submitted.您在提交表单后修改 pk。 You pass customer as instance to a CustomerForm and let the form save a new object.您将客户作为实例传递给 CustomerForm 并让该表单保存一个新对象。 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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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