简体   繁体   English

Django表单的HTTP响应问题

[英]HTTP Response problems with Django form


at the moment, I try to make a search form for a small database. 目前,我尝试为小型数据库创建搜索表单。

This is a part of my models.py file: 这是我的models.py文件的一部分:

from django.db import models
from django import forms
#...
class searchForm(forms.Form):
   searchField = forms.CharField(max_length = 100)
#...

This is a part of my views.py file: 这是我的views.py文件的一部分:

from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
#...
def index(request):
   template = loader.get_template('index.html')
   context = Context({})
   return HttpResponse(template.render(context))

def search(request):
   if request.method == 'POST': # If the form has been submitted...
     form = searchForm(request.POST)# A form bound to the POST data
     if form.is_valid():
        searchData = form.cleaned_data['searchField']
        return HttpResponseRedirect('search.html') # Redirect after POST #???
   else:
     searchData = searchForm() # an unbound form

   return render(request, 'search.html', {'form': form,}) #???
#...

This is a part of my index.html, where I want to implement that form: 这是我的index.html的一部分,我想在那里实现该表单:

<label for="Search">Search:</label>
<form action = "/search/" method = "post">
    {% csrf_token %} {{ form.as_p }}
    <input type = "submit" value = "Go" />  
</form>

What I'm trying to do: 我正在尝试做什么:
When I submit the form I would like to redirect to the result file called search.html, where for the beginning, is the input from the search textfield showing up. 当我提交表单时,我想重定向到名为search.html的结果文件,其中开头是来自搜索文本字段的输入。 The link struktur should be something like that: 链接struktur应该是这样的:
Landing-Page is: http://127.0.0.1:8000/ 登陆页面是: http://127.0.0.1:8000/http://127.0.0.1:8000/http://127.0.0.1:8000/
after a submitted form: http://127.0.0.1:8000/search.html 提交表格后: http://127.0.0.1:8000/search.htmlhttp://127.0.0.1:8000/search.htmlhttp://127.0.0.1:8000/search.html

I think there might be an error in the search method, where I marked the lines with the '???'. 我认为搜索方法可能存在错误,我用'???'标记了这些行。 The next problem is, that my search textfield isn't showing up. 接下来的问题是,我的搜索文本字段没有显示出来。

Would be great, if someone could give me some advice. 如果有人可以给我一些建议,那会很棒。

thanks, eljobso 谢谢,eljobso

First: The form isn't showing up because as you say, you want it to appear in index.html but the index view isn't passing any form to the template. 第一:表单没有显示,因为正如您所说,您希望它出现在index.htmlindex视图不会将任何表单传递给模板。 Is in search view where you pass the form the template. search视图中您传递表单的模板。

If you want the behavior described you should reorganize the code like this: 如果您想要描述的行为,您应该重新组织代码,如下所示:

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template.context import RequestContext

#...
def index(request):
   # this will only render the template with the form
   searchData = searchForm() # an unbound form
   return render_to_response(
        'index.html',
        context_instance=RequestContext(
            request,{'form':searchData,}
        )
    )

def search(request):
   if request.method == 'POST': # If the form has been submitted...
     form = searchForm(request.POST)# A form bound to the POST data
     if form.is_valid():
        searchData = form.cleaned_data['searchField']
        # do whatever you want to process the search with
        # searchada, maybe populate some variable
        return render_to_response(
            'search.html',
            context_instance=RequestContext(
                request,{'form':searchData,} # maybe add here the populated variable with the search
            )
        )
   else:
     # request.GET, just show the unbound form
     searchData = searchForm() # an unbound form

   return render_to_response(
        'search.html',
        context_instance=RequestContext(
            request,{'form':searchData,}
        )
    )

Then your templates should be: 然后你的模板应该是:

index.html 的index.html

<!-- is not good to have a label outside form -->
<label for="Search">Search:</label>
<form action = "/search/" method = "post">
    {% csrf_token %} {{ form.as_p }}
    <input type = "submit" value = "Go" />  
</form>

And also that text included inside search.html template because there you render the form as well. 此外,该文本还包含在search.html模板中,因为您也可以渲染表单。

I hope this may bring some light! 我希望这可能带来一些亮点!

With django FormView you can do that: 使用django FormView,您可以这样做:

class Index(FormView):
    form_class = SearchForm
    template_name = 'index.html'
    success_template = 'search.html' # I've added this attr

    def form_valid(self, form): #That return a your form, validated
      # Here you can do something with you VALID form.
      searchData = form.cleaned_data['searchField']
      context = dict(
            searchData=searchData,
        )
      return render_to_response(self.success_template, {}, RequestContext(self.request, context))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM