如何在Django中接收和发送表单数据到JavaScript?

cuxqih21  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(66)

我试图让Django从表单中接收数据,然后处理它并将其输出到JavaScript。
我试着按照Django的教程制作一个表单,它似乎工作,但是当我点击提交按钮时,我只是被转移到http://127.0.0.1:8000/your-name/。我想我必须在视图中做些什么,但我不完全确定到底是什么。

如何处理数据并将其发送到JS?
HTML

<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">

字符串

Views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect

from .forms import NameForm

def home(request):
    return render(request, 'index.html')

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == "POST":
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            print("yesss")
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect("/thanks/")

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, "index.html", {"form": form})

Forms.py

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label="Your name", max_length=100)

hrirmatl

hrirmatl1#

<script>
    console.group("Index.djt logs")
    
    // collect all data supplied by DJANGO into this object
    const DJANGO_DATA = {}

    // all CAPITAL CASE variables will be used in index.js js which are given by django server
    const DEVICE_IDS = {{device_ids | safe}}
    const DEVICE_HANDSHAKE_TIMES = {}

    // urls which are supplied by django server
    const CLEAR_WIFI = "{% url 'iot_control:clear_wifi' %}"
    const ADD_DEVICE = "{% url 'iot_control:add_device' %}"
    const POWER_CONSUMPTION = "{% url 'iot_control:power_consumption' %}"

    const CSRF_TOKEN = '{{ csrf_token }}'
    var POWER_SUPPLY = "{{power_supply}}" == "True"?true:false;
    var device_ids = DEVICE_IDS.join(','); // just for selenium testing
    // only `var` type variables are accessed by selenium

    const switch_data = {{switch_data | safe}}
    let timezone = null
</script>
<script src="index.js"></script>

字符串
你可以通过访问DJANGO_DATA变量来使用页面JavaScript中的所有数据,如果你正在集成typescript,你可以按照下面的过程操作

import $ from "jquery";
import {DeviceTimers, PowerStates, DjangoDataInterface} from "./types"

declare const DJANGO_DATA: DjangoDataInterface;


DJANGO_DATA类型脚本变量将由附加在此之前的脚本标记填充

相关问题