当我尝试使用POST方法使用表单时,我遇到了一个TypeError:无法将字节连接到str。这不仅发生在我使用表单时,而且当我输入管理面板的登录名/密码时。
Environment:
Request Method: POST
Request URL: http://photofresh.site/blog/post_new/
Django Version: 1.8
Python Version: 3.5.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'blog']
Installed Middleware:
['django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
125. response = middleware_method(request, callback, callback_args, callback_kwargs)
File "/usr/local/lib/python3.5/site-packages/django/middleware/csrf.py" in process_view
174. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
File "/usr/local/lib/python3.5/site-packages/django/core/handlers/wsgi.py" in _get_post
137. self._load_post_and_files()
File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in _load_post_and_files
272. self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in body
233. self._body = self.read()
File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in read
292. return self._stream.read(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/core/handlers/wsgi.py" in read
51. result = self.buffer + self._read_limited()
Exception Type: TypeError at /blog/post_new/
Exception Value: can't concat bytes to str
这是我的HTML表单。我知道使用Django Forms会更好,但是当我在计算机上使用runserver命令时,这个特殊的例子运行得非常好。
<form action="{% url 'blog:post_new' %}" method="post">
{% csrf_token %}
Name:<br>
<input type="text" name="name"><br>
Text:<br>
<input type="text" name="text">
<input type="submit" value="Submit">
</form>
view.py:
def post_new(request):
posts = Post.objects.all().order_by('-date')
_name = request.POST['name']
_text = request.POST['text']
_date = timezone.now()
p = Post(name=_name, text=_text, date=_date)
p.save()
return render(request, 'blog/base.html', {'posts': posts})