Elyasomer
Elyasomer

Reputation: 113

how to change status by a link or a button in django

So I want to make a link or a button that should be able to change status from 1 to 0 in the database actually I have the link like this <a href="{% url 'articles:delete' slug=article.slug %}" class="btn btn-danger mr-1 float-left">Delete</a> and in url.py path('delete-article/<slug:slug>/', views.delete_article, name='delete'), now I want to make a function in views.py that change the status to 0 whenever the link is clicked

models.py

class Category(models.Model):
    title = models.CharField(max_length=100)
   
    def __str__(self):
        return self.title

class Articles (models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField()
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    thumb = models.ImageField(blank=True, default='{% static "Images/default.jpg" %}',)
    Category = models.ForeignKey(Category, null=True, on_delete=models.PROTECT)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
    status = models.BooleanField(default=False)

    def __str__(self):
        return self.title

    def snippet(self):
        return self.body[:120]

Upvotes: 2

Views: 1073

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477608

You can work with .update(…) [Django-doc]:

from django.views.decorators.http import require_http_methods

@require_http_methods(['POST'])
def delete_article(request, slug):
    Articles.objects.filter(slug=slug).update(status=0)
    # …

But you should not work with a link. This is a GET request, and GET requests should, by the HTTP standard be used to retrieve data, not change data [w3.org]:

In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered "safe".

You thus make a POST request, for example with a mini-form:

<form method="post" action="{% url 'articles:delete' slug=article.slug %}">
    {% csrf_token %}
    <button type="submit" class="btn btn-danger mr-1 float-left">Delete</button>
</form>

Upvotes: 2

Related Questions