7

(sorry for my bad english)

I need to delete an object, but directly from a list of the objects that y have in my template.

I have a work orders, that have spare parts but i don't know how to create the deleteview for the spare parts using only a buton in the detailview of the work order. The idea is that the user make click in the Delete button.

This is the model of the Spare Parts

class OrderSparePart(models.Model):
    # Relations
    workorder = models.ForeignKey(
            WorkOrder,
            verbose_name=_('order'),
        )
    # Attributes - Mandatory
    spare_part = models.CharField(
            max_length=80,
            verbose_name=_('spare part'),
        )
    # Attributes - Optional
    price = models.DecimalField(
            max_digits=6,
            decimal_places=2,
            null=True,
            blank=True,
            verbose_name=_('price'),
        ) 
    # Object Manager
    # Custom Properties
    # Methods
    def get_absolute_url(self):
        return reverse('work_orders:detail', kwargs={'order_id': self.workorder.id})

    # Meta and String
    class Meta:
        verbose_name = _("order spare part")
        verbose_name_plural = _("order spare parts")

This is where is showed in the template

                  {% if spare_parts %}
                  <table class="table">
                    <thead>
                      <tr>
                        <th>{% trans "Spare Part" %}</th>
                        <th>{% trans "Price" %}</th>
                        <th>{% trans "Delete" %}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {% for part in spare_parts %}
                      <tr>
                        <td><i class="fa fa-gear"></i> {{ part.spare_part }}</td>
                        {% if part.price %}
                        <td>$ {{ part.price }}</td>
                        {% else %}
                        <td></td>
                        {% endif %}
                        <td><a href="#"><i class="fa fa-trash"></i></a></td>
                      </tr>
                      {% endfor %}
                    </tbody>
                  </table>
                {% else %}
                <p>NO HAY REPUESTOS ASENTADOS AÚN</p>
                {% endif %}

The the idea is use the to delete the spare part.

how i have to make the deleteview and the link to this???

Thanks!

3 Answers 3

6

here in fa fa-thrash pass the id and the URL as I did it:-

{% if spare_parts %}
              <table class="table">
                <thead>
                  <tr>
                    <th>{% trans "Spare Part" %}</th>
                    <th>{% trans "Price" %}</th>
                    <th>{% trans "Delete" %}</th>
                  </tr>
                </thead>
                <tbody>
                  {% for part in spare_parts %}
                  <tr>
                    <td><i class="fa fa-gear"></i> {{ part.spare_part }}</td>
                    {% if part.price %}
                    <td>$ {{ part.price }}</td>
                    {% else %}
                    <td></td>
                    {% endif %}
                    <td><a href="url:delete_view" part.id><i class="fa fa-trash"></i></a></td>
                  </tr>
                  {% endfor %}
                </tbody>
              </table>
            {% else %}
            <p>NO HAY REPUESTOS ASENTADOS AÚN</p>
            {% endif %}

ur url would be sonething like that:

url(r'^delete/(?P<part_id>[0-9]+)/$', view.function, name='delete_view'),

in ur view:

def function(request,part_id =None):
    object = YourModel.objects.get(id=part_id)
    object.delete()
    return render(request,'ur template where you want to redirect')
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfect, Thanks!
5

In your html template inside for loop use the form tag inside <td> to create delete button as below (css class will work if you are using bootstrap3):

<form action="{% url 'delete_view' pk=part.pk %}" method="POST">
  {% csrf_token %}
  <input class="btn btn-default btn-danger" type="submit" value="Delete"/>
</form>

add urlpattern in urls.py

url(r'^delete-entry/(?P<pk>\d+)/$', views.DeleteView.as_view(), name='delete_view'),

delete view will be like below in views.py

class DeleteView(SuccessMessageMixin, DeleteView):
model = OrderSparePart
success_url = '/'
success_message = "deleted..."

def delete(self, request, *args, **kwargs):
    self.object = self.get_object()
    name = self.object.name
    request.session['name'] = name  # name will be change according to your need
    message = request.session['name'] + ' deleted successfully'
    messages.success(self.request, message)
    return super(DeleteView, self).delete(request, *args, **kwargs)

Note: import necessary imports shown in links or you need not to worry if you are using IDE such as pyCharm it will prompt you which import to make.

3 Comments

This work perfect!!! Thanks and the message is very helpfull but, i can't figure how to redirect to the detailview of the workorder that have the spare parts. i define in the model def get_absolute_url(self): return reverse('work_orders:detail', kwargs={'order_id': self.workorder.id}) And work perfect for the createview, but when i delete if i remove the success_url django give me the error that i need to define a URL.
In django from html template request can be send using ajax,jquery or simple button click. Now in each condition you need to define redirect url in urls.py in that urls.py you have specified view which handles the request from client and views.py process the request. If you need to access database to handle the request you can retrieve,update,delete it using query in views which will hit your database. If it helps you can upvote or accept it as answer. for detail understanding I have attached git link with each structure you may need.
typo? I think you meant to use delete_book instead of delete_view in your form action.
0

My solutions works best for django 4.0.3 and is the combination of gahan and Abi waqas answers. Use this one if you are using django 3 or above

Add the following to views.py

def delete_object_function(request, id):
    # OrderSparePart is the Model of which the object is present

    ob = OrderSparePart.objects.get(id=id)
    ob.delete()
    return redirect('page-delete.html') # for best results, redirect to the same page from where delete function is called

Add the following to urls.py

path('page-delete/<int:id>', views.delete_object_function, name='delete_object'),

Add the following code to the django template from where the delete function is to be called.

Let's say page-delete.html

<form action="{% url 'delete_object' id=part.id %}" method="post">
   {% csrf_token %}
   <button class="btn btn-danger" type="submit" ><i class="fa fa-trash"></i></button>
</form>

This works as I've used this solution in my own code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.