Hello I am making django to-do list and I have a question. Am i able to delete and create elements in one view? Personally I would not use CreateView for that and make it like in 'def post' and ignore 'get_success_url' but is it good and djangonic practice? views.py
class Home(CreateView):
model = Item
template_name = 'home/todo.html'
form_class = itemCreationForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['items'] = Item.objects.all()
return context
def get_success_url(self):
return reverse('home-page')
def post(self, request):
form = itemCreationForm()
if 'delete' in self.request.POST:
print('deleted')
return redirect('home-page')
if 'add' in self.request.POST and form.is_valid():
form.save()
return HttpResponse('home-page')
HTML
<div class="card__items-list">
{% for item in items %}
<div class="card__item-row">
<p class="card__item">{{ item.name }}</p>
<form action="{% url 'home-page' %}" class="card__delete" method="POST"> {% csrf_token %}
<button class="card__delete__button" name="delete" type="submit">✘</button>
</form>
</div>
{% endfor %}
</div>
<form name="add" method="POST"> {% csrf_token %}
{{ form }}
<button name="add" class="submit-button" type="submit">Submit</button>
</form>
</div>
CodePudding user response:
It is possible to handle both the deletion and creation of objects in a single Django view function. However, it is arguably a better practice to handle these operations in separate HTTP action verbs (POST vs DELETE).
For example, your Home
view could handle both of these operations, but separate them into different if
blocks based on the HTTP action verb of the request. Then, from your web page, the create operation would send an HTTP POST request, and the delete operation would send an HTTP DELETE request.
This could be done in a single Django view function using the following sample code:
def my_sample_view(request):
if request.method == "POST":
# Handle create logic here.
elif request.method == "DELETE":
# Handle delete logic here.