3

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.

1 Answer 1

5

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']

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you. When I do as you say, the relationship is deleted as I want. But it redirects the user to the "remove_relationship" view. I would like the user to stay on the same page. Do you have an idea on how to do that?
Yes, just return an HttpResponseRedirect(reverse('your original view here')) from the remove_relationship view.
Or, submit the form via Ajax. But then you'd need some Javascript to post it and remove the now-deleted content from the page.
Thanks, but I get this error: " Reverse for 'myfile.html' with arguments '()' and keyword arguments '{}' not found. " I had to import 'reverse' and I used from django.core.urlresolvers import reverse. Is it correct?
@JulietteDupuis You need to use the view name such as "views.myview" (i.e. the function name) rather than the template file.
|

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.