我正在尝试使用DateField创建SearchForm,但是当我发送data method =“post”时,表单看不到属性'get'。哪里出错?
forms.py
class SearchForm(forms.Form):
datee = forms.DateField(input_formats=['%Y-%m-%d'],
widget=forms.widgets.DateInput(format="%Y-%m-%d"))
views.py
def index(request):
search_form = search(request)
context = {'search_form': search_form}
return render(request, 'name/index.html', context)
def search(request):
if request.method == 'POST':
form = SearchForm(data=request.POST)
if form.is_valid():
#Do something for examlpe
HttpResponseRedirect(reverse("name:second"))
else:
form = SearchForm()
search_form = form
return search_form
的index.html
<form method="post" action="{% url 'name:search' %}">
{% csrf_token %}
{{ search_form.as_p }}
<button name="submit">Search</button>
</form>
但是我得到了这个日志,并且不明白哪里出错:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/search_result
Django Version: 2.0.5
Python Version: 3.6.3
Traceback:
File "C:\Users\Александр\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\Александр\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\deprecation.py" in __call__
97. response = self.process_response(request, response)
File "C:\Users\Александр\AppData\Local\Programs\Python\Python36\lib\site-packages\django\middleware\clickjacking.py" in process_response
26. if response.get('X-Frame-Options') is not None:
Exception Type: AttributeError at /search_result
Exception Value: 'SearchForm' object has no attribute 'get'
答案 0 :(得分:5)
Django视图应该返回httpresponse对象。但是您的搜索视图会返回表单对象。您可以将serch视图重写为类似的内容以修复错误:
def search(request):
if request.method == 'POST':
form = SearchForm(data=request.POST)
if form.is_valid():
#Do something for examlpe
HttpResponseRedirect(reverse("name:second"))
else:
form = SearchForm()
context = {}
context['search_form'] = form
return render(request, 'name/index.html', context)
答案 1 :(得分:0)
Form
不应该有get
,post
或其他dispatch
ed动词匹配方法,因为它代表数据并对其进行操作(更具体地说,方便地将任何有意义的操作 - 即除了验证和清理之外的任务 - 委托给底层基础架构),而不是满足HTTP请求 - 后者是视图的责任。
当search
视图必须返回SearchForm
兼容对象时,HttpResponse
视图会返回if response.get('X-Frame-Options') is not None:
个实例,这就是错误发生的地方(注意return render(request, 'name/index.html', {'form': search_form})
)
要解决此问题,请务必search
视图中的function checkIsNull(obj){
let isNull=true;
for(let key in obj){
if (obj[key] && typeof obj[key] !== 'function') {
isNull = false;
}
}
return isNull;
}
var objectWithFunctionEmpty={
"name":undefined,
"surname":null,
"fun": function (){ alert('ciao'); }
}
var objectWithFunctionFull={
"name":undefined,
"surname":"bla bla",
"fun": function (){ alert('ciao'); }
}
checkIsNull(objectWithFunctionEmpty); //true
checkIsNull(objectWithFunctionFull); //false
。