Skip to main content
 首页 » 编程设计

python之Django:使用 View 和表单复制模型对象

2025年05月04日30小虾米

我有一个 Django (1.8) 模型,它有一些基于类的通用 View :列表、更新、删除、详细信息、创建。 https://docs.djangoproject.com/en/1.8/ref/class-based-views/

在详细信息或 ListView 中,我有一个要执行此操作的按钮:

  1. 创建对象的副本
  2. 将数据加载到表单中并显示给用户以编辑/保存新对象(可以使用现有的更新或创建 View ,还是新的?)

我可以使用以下信息克隆模型: How do I clone a Django model instance object and save it to the database?

但我无法通过从 View 开始到具有复制的对象数据的表单结束来实现这一飞跃。

谢谢!

局部 View .py

class List(ListView): 
  model = Announcement 
  template_name = 'announcements/list.html' 
 
class Create(CreateView): 
  model = Announcement 
  form_class = AnnouncementForm 
  template_name = 'announcements/form.html' 
 
  def form_valid(self, form): 
    data = form.save(commit=False) 
    data.author = self.request.user 
    data.save() 
    return super(Create, self).form_valid(form) 
 
class Update(UpdateView): 
  model = Announcement 
  form_class = AnnouncementForm 
  template_name = 'announcements/form_update.html' 
 
  @method_decorator(login_required) 
  def dispatch(self, *args, **kwargs): 
    return super(Update, self).dispatch(*args, **kwargs) 

部分forms.py

class AnnouncementForm(forms.ModelForm): 
    class Meta: 
        model = Announcement 
        exclude = ['author'] 

部分list.html

{% for object in object_list %} 
      <p>object.title</p> 
      <a class="btn btn-danger" href="{% url 'announcements:delete' object.id %}" role="button">Delete</a> 
      <a class="btn btn-info" href="{% url 'announcements:update' object.id %}" role="button">Edit</a> 
      <a class="btn btn-primary" href="" role="button">Copy</a> 
{% endfor %} 

我点击了 list.html 中的“复制”按钮,我想复制对象并在表单中打开新的副本进行编辑。

请您参考如下方法:

它认为我想通了!

网址.py

#eg: myapp/5/copy/ 
#where 5 is the item I want to copy 
url(r'^(?P<id>[0-9]+)/copy/$', views.item_copy, name='item_copy'), 

views.py:

def item_copy(request, id): 
    new_item = get_object_or_404(MyModel, pk = id) 
    new_item.pk = None #autogen a new pk (item_id) 
    new_item.name = "Copy of " + new_item.name #need to change uniques 
 
    form =  MyForm(request.POST or None, instance = new_item) 
 
    if form.is_valid(): 
        form.save() 
        return redirect('my_view') 
 
    context = { 
        "form": form, 
        #other context 
    }  
 
    return render(request, "form.html", context)