gpt4 book ai didi

Django : Can I use CreateView and DeleteView in same form?

转载 作者:行者123 更新时间:2023-12-02 06:56:53 26 4
gpt4 key购买 nike

我想以相同的形式显示两个按钮,第一个按钮用于删除对象,第二个按钮用于创建对象。

例如,我想创建简单的模型,例如:

models.py:

class UrlStatus_Proxy(models.Model):

urls = models.URLField(u'Site URL', max_length=100, null=True, unique=True)
status_url = models.CharField(u'Site', max_length=20, choices=STATUS_URL)

urls.py

url(r'^url_status/$',ProxyUrlCreateView.as_view(model=UrlStatus_Proxy,
get_success_url=lambda: reverse('proxy_url_status'),template_name='proxy_url_status.html'), name='proxy_url_status'),

proxy_url_status.html

<form action="" method="post">    
{{form.as_p}}
<input type="submit" name="delete" id="delete">
<input type="submit" name="add" id="add">
</form>

如果我在数据库中没有对象,那么什么也不做,只是显示模型中的表单,并且您只有一个选项来在数据库中添加新对象。

如果我在数据库中有对象,则列出像表这样的对象,并且在表中我有一个复选框字段。当我检查其中一个对象并单击“删除”按钮时,我想删除该对象。

在第二种情况下,如果我从对象填充输入字段并按“添加”按钮,我想在基础中添加对象。

我该怎么做?

最佳答案

首先将所有现有对象添加到 CreateView 的上下文中,并更新 HTML 模板以将它们呈现为表单上方的表格。然后创建一个DeleteView并将URL映射到它。

网址

url(r"^url_status/$",
ProxyUrlCreateView.as_view(),
name="proxy_url_status"),

url(r"^url_status/(?P<pk>\d+)/delete/?$",
DeleteProxyURLView.as_view(),
name="delete_proxy"),

观看次数

from django.views.generic import DeleteView
from django.core.urlresolvers import reverse

# add existing objects to the context, making them available to the template
class ProxyUrlCreateView(CreateView):
model = UrlStatus_Proxy
template_name = "proxy_url_status.html"

def get_success_url(self):
return reverse("proxy_url_status")

def get_context_data(self, **kwargs):
kwargs["object_list"] = UrlStatus_Proxy.objects.all()
return super(ProxyUrlCreateView, self).get_context_data(**kwargs)

class DeleteProxyURLView(DeleteView):
model = UrlStatus_Proxy

def get_success_url(self):
"""
Redirect to the page listing all of the proxy urls
"""
return reverse("proxy_url_status")

def get(self, *args, **kwargs):
"""
This has been overriden because by default
DeleteView doesn't work with GET requests
"""
return self.delete(*args, **kwargs)

模板

<table>
{% for proxy_url in object_list %}
<tr>
<td>{{ proxy_url.urls }}</td>
<td><a href="{% url delete_proxy %}">Delete</a></td>
</tr>
{% endfor %}
</table>

<form action="" method="post">
{{form.as_p}}
<input type="submit" name="add" id="add">
</form>

关于 Django : Can I use CreateView and DeleteView in same form?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15122382/

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