Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with arguments in a template. Django

Tags:

django

In my template, I display a list of users a user follows. I would like the user to be able to delete one of the users he follows thanks to a button. I have a function remove_relationship that deletes a relationship.

Here is the function in my models.py:

  class UserProfile(models.Model):
  (...)

      def remove_relationship(self, person):
        Relationship.objects.filter(
            from_person=self, 
            to_person=person).delete()
        return

I would like to pass this function into my template:

   {% for user in following % }
   <form method="post">
    {% csrf_token %}
   <input type="submit" value="delete" onclick="remove_relationship"/>
   </form>
   {%endfor%}

The thing is that I can't pass argument in my template. So how can I do so that each button deletes the relationship with the right user?

I saw an other question on this topic, abut it looks like it doesn't solve my problem (http://stackoverflow.com/questions/1333189/django-template-system-calling-a-function-inside-a-model)

Thank you for your help.

like image 209
Juliette Dupuis Avatar asked Jan 20 '26 20:01

Juliette Dupuis


1 Answers

It looks as though you are confusing client-side code (JavaScript) with server-side (Django).

To get the relevant user ID submitted you could add an additional hidden field to the form:

{% for user in following % }
<form method="post" action="{% url views.remove_relationship %}">
 {% csrf_token %}
<input type="hidden" name="user_id" value="{{ user.id }}">
<input type="submit" value="delete" />
</form>
{%endfor%}

Then create a remove_relationship view that does the deletion on the server side, based on the user id you'll now find in request.POST['user_id']

like image 107
Steve Mayne Avatar answered Jan 23 '26 04:01

Steve Mayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!