Django:如何在提交表单后呈现相同的网页

时间:2018-06-07 18:14:43

标签: django django-models django-forms django-views render

我有一个index.html文件,其中包含提交按钮。我想要的功能,当我点击提交按钮时,python函数应该在后台调用,但index.html的渲染视图应保持不变。现在,每次我点击提交按钮时,都会加载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)  

我是django的新手。我可以得到一些指针或答案如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

使用相同的视图执行这两个操作。

<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并未完全涵盖,但请查看formsgeneric views