简体   繁体   English

我如何使用脚本在脚本文件或views.py中运行python函数来不加载页面

[英]How Can I run a python function in script file or in the views.py using javascript for not loading the page

I have a Django page that has a form that has a button that calls functions in the views.py, but I want to validate some input text of the form via running a python script function (in views.py or I can separate this function in another file) but I don't want to load the page. 我有一个Django页面,该页面的表单带有一个按钮,该按钮调用views.py中的函数,但是我想通过运行python脚本函数来验证表单的一些输入文本(在views.py中,或者我可以分离该函数在另一个文件中),但我不想加载该页面。 where and How can I make js code to run this function? 我在哪里以及如何使js代码运行此功能?

Create a new url to for a the view function which will validate the input. 为视图功能创建一个新的URL,以验证输入。

path('ajax/validate_input/', views.ValidateInput.as_view(), name='my_ajax_url'),

In views.py do your validation then return a JsonResponse . views.py进行验证,然后返回JsonResponse

from django.views import View
from django.http import JsonResponse

class ValidateInput(View):
    def post(self, request):
        # Do validation
        return JsonResponse({
            'valid': True,
            'message': 'Invalid Characters',
        })

Now in your template write js code that will make ajax requests to that url. 现在,在模板中编写js代码,该代码将对该URL发出Ajax请求。

According to received response make changes to your webpage using js in the success of your ajax. 根据收到的响应,在成功使用ajax时使用js更改您的网页。

// add jQuery
// put the code below inside an event handle, maybe on input change
$.ajax({
    url: {% url 'my_ajax_url' %},
    method: 'POST',
    data: {
        body: body,
        csrfmiddlewaretoken: '{{ csrf_token }}'
    },
    dataType: 'json',
    success: function(data){ 
        console.log(data.valid);
        console.log(data.message);
        // do stuff to change your webpage here
    }
});

I would recommend validating input on input change, but if you want to do it in from submit, then add an event handler for form submit. 我建议验证输入更改时的输入,但是如果您想从Submit中进行输入,则为表单Submit添加一个事件处理程序。 There use event.preventDeafault to prevent form submit, then do the ajax stuff, and according to the received json do something else. 使用event.preventDeafault来阻止表单提交,然后执行ajax的操作,并根据收到的json进行其他操作。 Maybe if valid = true then proceed further or if valid = false then show the message received in json below the input box. 也许如果valid = true则继续操作;或者,如果valid = false则在输入框下方显示json中收到的消息。

You could render the form in a dedicated Python view and invoke it via Ajax from Javascript. 您可以在专用的Python视图中呈现表单,然后通过Javascript中的Ajax调用它。

In this view you should: 在这种情况下,您应该:

  • create the form 创建表格
  • render it to a string 渲染成字符串
  • return rendered form as json 将呈现的表单返回为json

If you invoke it via GET method, you render the form with initial values (no warnings or errors messages). 如果通过GET方法调用它,则使用初始值(没有警告或错误消息)呈现表单。

If used method is POST, you get values from the request and render the form (including validation messages). 如果使用的方法是POST,则可以从请求中获取值并呈现表单(包括验证消息)。

This could be how the Django view looks like: 这可能是Django视图的样子:

import json
from django.http import HttpResponse
from django.template.loader import render_to_string

def my_view(request):

    if request.method == "GET":    
        form = MyForm()
    elif request.method == "POST":
        form = MyForm(data=request.POST)

    form_context = {'form': form}    
    form_html = render_to_string('form.html', form_context)

    json_response = json.dumps(form_html, separators=(',', ':'))
    return HttpResponse(json_response)

In the Javascript side via GET (using JQuery.getJSON): 在Javascript端通过GET(使用JQuery.getJSON):

$.getJSON('/url/path/to/my-view',
          function(data) {
              var form_html = decodeURIComponent(data.form);
              $("form#my-form-css-selector").html(form_html);
});

And in the Javascript side via POST (using JQuery.post): 并通过POST在Javascript端(使用JQuery.post):

$.post('/url/path/to/my-view',
       $("form#my-form-css-selector").serialize(),
       function(data) {
           var form_html = decodeURIComponent(data.form);
           $("form#my-form-css-selector").html(form_html);
       },
       "json"
);

You can check Django views , Django render_to_string , JQuery.getJSON , JQuery.post doc pages for further info. 您可以检查Django视图Django render_to_stringJQuery.getJSONJQuery.post文档页面以获取更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django如何使用JavaScript函数将请求发送到views.py - Django How to send request to views.py using javascript function 如何通过javascript文件中的ajax调用在views.py中调用特定功能? - how do I call specific function in views.py through ajax call in javascript file? 我如何将views.py中的数字列表发送到我在前面使用的chartjs文件? - how can i send a list of numbers from views.py to a chartjs file im using for the front? 如何将javascript变量值传递给django中的views.py函数? - how to pass javascript variable value to views.py function in django? Django:如何从views.py获取字典到javascript函数(html文件) - Django: how to get a dictionary from views.py into javascript function (html file) 如何从 Django 中的 views.py 文件调用 javascript function - How to call a javascript function in from your views.py file in Django 如何将在我的html文件上单击的图像的URL传递给views.py中的python函数 - how to pass the url of image clicked on my html file to my python function in views.py Django 如何从我的 javascript 到当前应用程序的另一个应用程序的 views.py - How can I go from my javascript to views.py of another app from present app 如何在python vue js的views.py中处理GET和POST请求? - How can I able to handle both GET and POST requests in views.py in python vue js? 如何使用$ .post()将Jquery变量发送到我的views.py,以及如何在不刷新页面的情况下检索它们 - How do I send Jquery variable to my views.py using $.post(), and how do i retrieve them without refreshing the page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM