alcoder
alcoder

Reputation: 457

Call function when click button django

I want to call my python function, when user clicked button "submit" on this page http://junjob.ru/accounts/login/

How can I do it?

enter image description here

My code:

views.py

class BBLoginView(LoginView):
    template_name = 'vacancy_list/login.html'

class BBLogoutView(LoginRequiredMixin, LogoutView):
    template_name = 'vacancy_list/vacancy_list.html'
    next_page = reverse_lazy('vacancy_list')

urls.py

urlpatterns = [

    path('accounts/login/', BBLoginView.as_view(), name='login'),
    path('accounts/profile/', profile, name='profile'),
    path('accounts/logout/', BBLogoutView.as_view(), name='logout'),
    ...

login.html

{% block content %}
    <div class="container" style="margin-top:10px">
        <h2>Login</h2>
        {% if user.is_authenticated %}
            <p>You are already registered</p>
        {% else %}
        <form method="post">
            {% csrf_token %}
            {% bootstrap_form form layout='horizontal' %}
            <input type="hidden" name="next" value="{{ next }}">
            {% buttons submit="Submit" %} {% endbuttons %}
        </form>
       {% endif %}
    </div>
{% endblock %}

Upvotes: 0

Views: 215

Answers (1)

Gasanov
Gasanov

Reputation: 3399

You can hook into form_valid method of parent class LoginView:

class BBLoginView(LoginView):
    template_name = 'vacancy_list/login.html'

    def form_valid(self, form):
        # Put your code here
        return super().form_valid(form)

It will trigger if only form is valid but before user auth.

If you need to execute your code in any case, hook into post method:

class BBLoginView(LoginView):
    template_name = 'vacancy_list/login.html'

    def post(self, request, *args, **kwargs):
        # Put your code here
        return super().post(request, *args, **kwargs)

You can find source code for LoginView here

Upvotes: 1

Related Questions