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

I want to show two buttons in the same form, the first button that I want to use for the delete object, and the second button to create the object.

For example, I want to create a simple model, for example:

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> 

If I do not have objects in the database, do nothing, the form from the model is simply displayed, and you have only one option for adding a new object to the database.

If I have objects in the database, then list the object as a table, and in the table I have one field field. When I checked one of the objects and clicked the delete button, I want to delete this object.

In the second case, if I fill in the input field from the object and click the "add" button, I want to add the object to the database.

How can i do this?

+4
source share
1 answer

First, add all existing objects to the CreateView context and update the HTML template to display them as a table above the form. Then create a DeleteView and map it a URL.

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"), 

Views

 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) 

Template

 <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> 
+3
source

All Articles