【问题标题】:Call function when click button django单击按钮django时调用函数
【发布时间】:2019-11-23 14:00:24
【问题描述】:

我想调用我的python函数,当用户点击此页面上的按钮“提交”http://junjob.ru/accounts/login/

我该怎么做?

我的代码:

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 %}

【问题讨论】:

    标签: python django


    【解决方案1】:

    你可以挂钩到父类LoginViewform_valid方法:

    class BBLoginView(LoginView):
        template_name = 'vacancy_list/login.html'
    
        def form_valid(self, form):
            # Put your code here
            return super().form_valid(form)
    

    如果只有表单有效但在用户身份验证之前它将触发。

    如果您在任何情况下都需要执行您的代码,请使用post 方法:

    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)
    

    你可以找到LoginViewhere的源代码

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2013-02-26
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多