Как получить доступ к метке из файла view.py - PullRequest
0 голосов
/ 25 сентября 2019

Я пытаюсь получить текст метки метки HTML-кода, но не могу его получить.

На предыдущей работе я получал данные из текстового поля, но теперь я не могу получить текст метки

html-файл

<label name="hello_text">HELLO</label>
<input type="text" name="textbox1"/>

view.py file

if request.method == "POST":
    textbox = request.POST["textbox1"]
    val = request.POST["hello_text"]  #didn't get the value of label here

Я хочу получить текстовое значение метки

1 Ответ

0 голосов
/ 25 сентября 2019

ОБНОВЛЕНИЕ, чтобы все работало

***UPDATE to make everything work***


IN example.html above your js file include a token this will be used to authenticate with csrf using ajax
<script type="text/javascript">
        var token = `{{ csrf_token }}`
 </script>
 
 
 In your .js file
  $.ajax({
    headers: {"X-CSRFToken": token}, //new item added here the csrf token
   url: `${window.location.origin}/example/`, //url changed to be dynamic for all base origins
   type: "POST",
   data: JSON.stringify(param),
   success: function () {
    alert("Success");
       },
   error: function(error) {
       console.log("error: " + error);
       }
  });
}
 
 
 In your views.py
 
 
 from django.http import HttpResponse
 
 
 Class exampleView(TemplateView):
     def post(self, request):
          body = json.loads(request.body.decode('utf-8'))    # I was incorrect in assuming how to parse body params
          value = body['value']
          label = body['label']
          return HttpResponse('')

---------------------------------- Конец обновления ----------------------------------

вот пример использования jquery

в example.html

<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="{% static 'js/example.js' %}" type="text/javascript"></script>


<label id="label1" name="hello_text">HELLO</label>
<input type="text" id="input1" name="textbox1"/>
<button id="submit-btn>submit form</button>

в example.js

//when document is loaded

$(document).ready(function() {
    //create an event listener for a button by id = submit-btn
    $('#submit-btn').click(function() {
        // call a function called submit form.
        submitForm();
    });
 })

 function submitForm() {
     //use jquery id selector to get the text of the label
     // use jquery id selector to get the value attr of an input
    let label = ('#label-1').text();
    let value = ('#input-1').attr('value');
    
    // build an object( dictonary) of items sent to post request
    var param = {
        "value" : value, 
        "label" : label,
    }

    // create an ajax request to submit the form this will call the django view
    // it knows its a post because type == POST
    // data must be turned to json to pass back to view
    // on success a function will alert a message and redirect to a new page
    $.ajax({
    url: `http://127.0.0.1/example`,
    type: "POST",
    data: JSON.stringify(param),
    success: function () {
     alert("Success");
     window.load('http://127.0.0.1/home')
        },
    error: function(error) {
        console.log("error: " + error);
        }
   });
 }

тогда на ваш взгляд

 value = request.POST.get("value", "")
 label = request.POST.get("label", "")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...