gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:37 25 4
gpt4 key购买 nike

我有一个 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)

关于python - Django:使用 View 和表单复制模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31579082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com