django MultiValueDictKeyError 오류, 어떻게 처리합니까
데이터베이스에 객체를 저장하려고하는데 MultiValueDictKeyError
오류가 발생합니다.
문제는 양식 내에 있으며, is_private
확인란으로 표시됩니다. 확인란을 선택하지 않으면 아무 것도 전달되지 않습니다. 오류가 발생하는 곳입니다.
이 예외를 올바르게 처리하고 포착하려면 어떻게해야합니까?
라인은
is_private = request.POST['is_private']
MultiValueDict의 get
방법을 사용하십시오 . 이것은 또한 표준 dicts에 존재하며 존재하지 않는 경우 기본값을 제공하면서 값을 가져 오는 방법입니다.
is_private = request.POST.get('is_private', False)
일반적으로,
my_var = dict.get(<key>, <default>)
가장 적합한 것을 선택하십시오 :
1
is_private = request.POST.get('is_private', False);
경우 is_private
키 request.POST에 존재하는 is_private
변수는 그와 동일 할 것이다 아니라면, 이는 거짓으로 동일 할 것이다.
2
if 'is_private' in request.POST:
is_private = request.POST['is_private']
else:
is_private = False
삼
from django.utils.datastructures import MultiValueDictKeyError
try:
is_private = request.POST['is_private']
except MultiValueDictKeyError:
is_private = False
사전에 키가 없을 때 키를 얻으려고하기 때문에 얻을 수 있습니다. 먼저 있는지 테스트해야합니다.
시험:
is_private = 'is_private' in request.POST
또는
is_private = 'is_private' in request.POST and request.POST['is_private']
사용중인 값에 따라
왜 is_private
모델에서 다음과 같이 정의하지 않았 default=False
습니까?
class Foo(models.Models):
is_private = models.BooleanField(default=False)
기억해야 할 또 다른 사항 request.POST['keyword']
은 지정된 html name
속성으로 식별되는 요소 를 나타냅니다 keyword
.
따라서 양식이 다음과 같은 경우
<form action="/login/" method="POST">
<input type="text" name="keyword" placeholder="Search query">
<input type="number" name="results" placeholder="Number of results">
</form>
이어서, request.POST['keyword']
및 request.POST['results']
입력 요소의 값을 포함 keyword
하고 results
, 각각.
요청 오브젝트에 'is_private'키 매개 변수가 있는지 먼저 확인하십시오. 대부분의 경우이 MultiValueDictKeyError는 사전과 같은 요청 오브젝트에서 누락 된 키에 대해 발생했습니다. 사전은 정렬되지 않은 키이므로 값 쌍 "연관 메모리"또는 "연관 배열"
다른 말로하면 request.GET 또는 request.POST는 모든 요청 매개 변수를 포함하는 사전과 유사한 객체입니다. 이것은 장고에만 해당됩니다.
get () 메소드는 키가 사전에있는 경우 지정된 키의 값을 리턴합니다. 키를 사용할 수 없으면 기본값 None을 반환합니다.
다음을 입력하여이 오류를 처리 할 수 있습니다.
is_private = request.POST.get('is_private', False);
나 에게이 오류는 다음과 같은 이유로 django 프로젝트에서 발생했습니다.
다음과 같이 프로젝트의 템플릿 폴더에있는 home.html에 새 하이퍼 링크를 삽입했습니다.
<input type="button" value="About" onclick="location.href='{% url 'about' %}'">
- views.py에서 count와 about에 대한 다음 정의를 가졌습니다.
def count(request): fulltext = request.GET['fulltext'] wordlist = fulltext.split() worddict = {} for word in wordlist: if word in worddict: worddict[word] += 1 else: worddict[word] = 1 worddict = sorted(worddict.items(), key = operator.itemgetter(1),reverse=True) return render(request,'count.html', 'fulltext':fulltext,'count':len(wordlist),'worddict'::worddict})
def about(request): return render(request,"about.html")
- urls.py에는 다음과 같은 URL 패턴이 있습니다.
urlpatterns = [ path('admin/', admin.site.urls), path('',views.homepage,name="home"), path('eggs',views.eggs), path('count/',views.count,name="count"), path('about/',views.count,name="about"), ]
As can be seen in no. 3 above,in the last url pattern, I was incorrectly calling views.count whereas I needed to call views.about. This line fulltext = request.GET['fulltext']
in count function (which was mistakenly called because of wrong entry in urlpatterns) of views.py threw the multivaluedictkeyerror exception.
Then I changed the last url pattern in urls.py to the correct one i.e. path('about/',views.about,name="about")
, and everything worked fine.
Apparently, in general a newbie programmer in django can make the mistake I made of wrongly calling another view function for a url, which might be expecting different set of parameters or passing different set of objects in its render call, rather than the intended behavior.
Hope this helps some newbie programmer to django.
'IT' 카테고리의 다른 글
gem을 테스트하도록 RSpec 설정 (레일이 아님) (0) | 2020.06.09 |
---|---|
JpaTest를 수행 할 때 @SpringBootConfiguration을 찾을 수 없습니다 (0) | 2020.06.09 |
경고 : 'characters'는 더 이상 사용되지 않습니다 : String 또는 Substring을 직접 사용하십시오 (0) | 2020.06.09 |
docker-compose를 사용하여 항상 새로운 이미지에서 컨테이너를 다시 만드는 방법은 무엇입니까? (0) | 2020.06.09 |
클래스 내에서 정적 메소드를 호출합니까? (0) | 2020.06.09 |