我试图让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)
型
1条答案
按热度按时间hrirmatl1#
字符串
你可以通过访问
DJANGO_DATA
变量来使用页面JavaScript中的所有数据,如果你正在集成typescript,你可以按照下面的过程操作型
此
DJANGO_DATA
类型脚本变量将由附加在此之前的脚本标记填充