我有一个带有submit按钮的index.html文件。我想要的功能是,当我点击提交按钮时,python函数应该在后台调用,但index.html的渲染视图应该保持不变。现在,每次我点击submit按钮,就会加载一个新的index.html副本。以下是我的代码
index.html
<form action = "submit" method = "post">
<p>latitude <input type = "text" id = "Latbox" name = "Latbox" /></p>
<p>Longitdue <input type = "text" id = "Lonbox" name = "Lonbox" /b></p>
<p><input type = "submit" value = "submit" /></p>
</form>
我的views.py文件如下:
from django.shortcuts import render
from django.views.generic import TemplateView
class HomePageView(TemplateView):
def get(self, request, **kwargs):
return render(request, 'index.html', context=None)
def submit(request):
LAT=request.POST['Latbox']
LON= request.POST['Lonbox']
print (LAT, LON)
return render(request,'index.html',context=None)
我是新来姜戈的。我能得到一些关于如何解决这个问题的指针或答案吗?
发布于 2018-06-08 05:30:25
使用相同的视图执行这两个操作。
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<p><input type = "submit" value = "submit" /></p>
</form>
在forms.py:
class LocationForm(forms.Form):
latitude = form.CharField()
longitude = form.CharField()
然后在views.py
中,你可以这样做:
class HomePageView(TemplateView):
template_name = "index.html"
def get(self, request, **kwargs):
form = LocationForm()
return render(request, self.template_name, {"form": form})
def post(self, request, **kwargs):
form = LocationForm(request.POST)
if form.is_valid():
pass # do something with form.cleaned_data
return render(request, self.template_name, {"form": form})
tutorial中并没有完全介绍这一点,但请看一下forms和generic views。
https://stackoverflow.com/questions/50747703
复制相似问题