bugZ
bugZ

Reputation: 494

Django on button click call function view

I have a list of matches which I get from my class based view:

class MatchListView(LoginRequiredMixin, generic.ListView)

In template I have a rows with list of matches and in one column I have a button. What I want to do is when I click on this button, another funcation/view is called, that takes that match id, and user, and saves it to database and get back to the list.

I have done something like this:

template

 <td><a href="{% url 'match_register_request' match.id %}" class="btn btn-info btn-sm">Zgłoś się na mecz</a></td>

url

path('match_register_request/<int:pk>', views.MatchRegisterViewRegister.as_view(), name='match_register_request')

and the view:

class MatchRegisterViewRegister(LoginRequiredMixin, generic.View):


    def post(self, request, object_id, *args, **kwargs):
        # Add record to DB
        mr = MatchRegister(match=object_id, ref_reg=self.request.user)
        mr.save()
        return redirect('matches_list')

but it doesn't work. It takes the id, redirects to the url "matches_register_request/{ID}" but does nothing.

Could you please help me with getting this done?

Upvotes: 0

Views: 496

Answers (1)

mfrackowiak
mfrackowiak

Reputation: 1304

You need to make a POST request to this endpoint, not GET. The easiest way to do it would be using form, e.g.:

<td>
  <form action="{% url 'match_register_request' match.id %}" method="post">
    {% csrf_token %}
    <button class="btn btn-info btn-sm">Zgłoś się na mecz</button>
  <form>
</td>

Upvotes: 2

Related Questions