【问题标题】:TypeError: 'NoneType' object is not subscriptable followed by AttributeError: 'NoneType' object has no attribute 'split'TypeError:“NoneType”对象不可下标,后跟 AttributeError:“NoneType”对象没有属性“split”
【发布时间】:2017-09-22 02:38:23
【问题描述】:

使用 django。我有以下型号:

class Postagem(models.Model):
id = models.AutoField(primary_key=True, editable=False)
descricao = models.CharField(max_length=50)
area = models.ForeignKey('core.Area', null=True)
user = models.ForeignKey('User')
categoria = models.CharField(max_length=50, null=True)
post = models.FileField(upload_to='posts/', null=True)
thumbnail = models.FileField(upload_to='posts/', null=True)


def __str__(self):
    return self.descricao

以下形式:

class PostForm(forms.ModelForm):
categoria = forms.ChoiceField(choices=[("Video","Vídeo"),("Audio","Aúdio"),("Imagem","Imagem"),("Musica","Música")], required=True)
thumbnail = forms.FileField(required=False)

class Meta:
    model = Postagem
    fields = ['descricao', 'area', 'user', 'post']

查看:

def profileView(request):
context = getUserContext(request)

if request.method == 'POST':
    exception=None
    userDict = {}
    userDict["user"] = context["user"].id    
    if "categoria" in request.POST:
        newPost = request.POST.copy()
        newPost.update(userDict)
        form = PostForm(newPost,request.FILES)
        print("postform POST: ",newPost, " File ",request.FILES)
        if form.is_valid():
            print("valid")
            try:
                form.save()
                print("saved")
                return HttpResponseRedirect(reverse_lazy('accounts:profile'))
            except IntegrityError as e:
                print("Integrity Error")
                exception=e            
        else:
            print("PostForm error")
            print(form.errors)

    form.non_field_errors=form.errors
    if exception is not None:
        form.non_field_errors.update(exception)
    context['form']=form

posts = Postagem.objects.get_queryset().order_by('id')
paginator = Paginator(posts, 12)
page = request.GET.get('page')
context["areas"] = Area.objects.all()   
try:
    posts = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    posts = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    posts = paginator.page(paginator.num_pages)

context["posts"]=posts

return render(
    request,
    'accounts/profile.html',
    context
)

最后是模板:

 {% for post in posts %}
        {% if forloop.counter0|divisibleby:4 or forloop.counter0 == 0 %}    
        <div id="grid-profile" class="row grid">
            <div class="col-md-1"></div>
        {% endif %}

            {% ifnotequal post.categoria "Imagem"%}
            <iframe id=post{{forloop.counter}} width="420" height="315"
                src={{post.post.url}}>
            </iframe>
            {% else %}
            <div class="col-md-2">
                <button type="button" id="modal1trigger" data-toggle="modal" data-target="#modal1"><img class="img-responsive" src={{post.post.url}}></img></button>
            </div>
            {% endifnotequal %}

        {% if forloop.counter|divisibleby:4 or forloop.counter == posts|length %} 
            <div class="col-md-1"></div>
        </div>
        {% endif %}
        {% endfor %}
        <div class="pagination">
            <span class="step-links">
                {% if posts.has_previous %}
                    <a href="?page={{ posts.previous_page_number }}">previous</a>
                {% endif %}

                <span class="current">
                    Page {{ posts.number }} of {{ posts.paginator.num_pages }}.
                </span>

                {% if posts.has_next %}
                    <a href="?page={{ posts.next_page_number }}">next</a>
                {% endif %} 
            </span>
        </div>

我剪掉了一些模板...无论如何,我希望能够添加各种帖子。歌曲、视频、图像、文档等。它正在工作。正在添加帖子。但是,我有一个反复出现的错误,我不知道为什么。这可能非常危险,所以我开始研究它,但没有找到可接受的答案。 该错误仅在尝试获取歌曲或视频时发生。

    [21/Sep/2017 23:32:44] "GET /media/posts/13567830_1641362072853439_1924036772_n.mp4 HTTP/1.1" 200 1171456
Traceback (most recent call last):
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
    self.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
    self._write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write

    result = self.stdout.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
    self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
[21/Sep/2017 23:32:44] "GET /media/posts/13567830_1641362072853439_1924036772_n.mp4 HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 53113)
Traceback (most recent call last):
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
    self.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
    self._write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write

    result = self.stdout.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
    self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 141, in run
    self.handle_error()
  File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_erro
r
    super(ServerHandler, self).handle_error()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 368, in handle
_error
    self.finish_response()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
    self.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 331, in send_h
eaders
    if not self.origin_server or self.client_is_modern():
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 344, in client
_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 639, in process_re
quest_thread
    self.finish_request(request, client_address)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 361, in finish_req
uest
    self.RequestHandlerClass(request, client_address, self)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 696, in __init__
    self.handle()
  File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 155, in handle
    handler.run(self.server.get_app())
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 144, in run
    self.close()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in cl
ose
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
----------------------------------------
[21/Sep/2017 23:32:44] "GET /media/posts/03_-_The_Mute.mp3 HTTP/1.1" 200 1179648
Traceback (most recent call last):
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
    self.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
    self._write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write

    result = self.stdout.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
    self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
[21/Sep/2017 23:32:44] "GET /media/posts/03_-_The_Mute.mp3 HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 53114)
Traceback (most recent call last):
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
    self.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
    self._write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write

    result = self.stdout.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
    self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 141, in run
    self.handle_error()
  File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_erro
r
    super(ServerHandler, self).handle_error()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 368, in handle
_error
    self.finish_response()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
    self.write(data)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 331, in send_h
eaders
    if not self.origin_server or self.client_is_modern():
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 344, in client
_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 639, in process_re
quest_thread
    self.finish_request(request, client_address)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 361, in finish_req
uest
    self.RequestHandlerClass(request, client_address, self)
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 696, in __init__
    self.handle()
  File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 155, in handle
    handler.run(self.server.get_app())
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 144, in run
    self.close()
  File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in cl
ose
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
---------------------------------------

编辑:

使用 Django 1.11.3, 视窗 10, 通过 Opera 和 Chrome 测试, 使用 gulp 运行服务器

**编辑2:**

嘿,错误只有在 html 中有 iframe 标记时才会发生

【问题讨论】:

    标签: python django split attributeerror nonetype


    【解决方案1】:

    看来这是一个python错误:

    Django 票:https://code.djangoproject.com/ticket/26995 Python票:https://bugs.python.org/issue14574

    暂时还没有解决,如果可以的话,我会编辑这个答案,详细解释如何解决它。

    编辑

    这似乎是 chrome 上的错误。我没有想到,因为我使用的是 Opera,但 Opera 也使用了 Chromium。在 Internet Explorer 中没有显示错误。

    https://code.djangoproject.com/ticket/21227#no1

    这是错误跟踪器

    【讨论】:

    • 我根本没想到,这是有道理的,它看起来确实像 WSGIref 的问题。您是否考虑过不使用 iframe?
    【解决方案2】:

    第一个错误 self.environ['SERVER_PROTOCOL'].upper() 失败,因为 self.environ['SERVER_PROTOCOL'] 是 None,你不能做 None.upper() 你只能在字符串上做 .upper() (据我所知)。

    第二个错误 self.status.split(' ',1)[0], self.bytes_sent AttributeError: 'NoneType' object has no attribute 'split' 这是失败的,因为你 self.status 是 None 并且你不能做 None.split(),这应该是一个字符串。

    所以看起来这些类的一些必需值没有被初始化或传递。

    看来问题出在 Django.core 和 WSGIref 上,所以要么配置不正确,要么你安装的版本有问题?

    您运行的是哪个版本的 Django? 你也是从./manage.py runserver 运行服务器吗?

    [2017-09-28 更新]

    我已经修改了一些东西,首先我没有将 request.POST 复制到一个新的字典中,在传递它之前,这可能是一些值在尝试处理时消失的原因发帖。

    我还将用户作为 kwarg 传递给您的表单,而不是尝试将其注入到复制的 POST 中。

    我只是更新了一些代码,使其更易于阅读,让我们看看情况如何。

    # forms.py
    class PostForm(forms.ModelForm):
        categoria = forms.ChoiceField(choices=[("Video","Vídeo"),("Audio","Aúdio"),("Imagem","Imagem"),("Musica","Música")], required=True)
        thumbnail = forms.FileField(required=False)
    
        class Meta:
            model = Postagem
            fields = ['descricao', 'area', 'user', 'post']
    
        def __init__(self, *args, **kwargs):  # handle user kwarg
            if 'user' in kwargs.keys():
                self.user = kwargs.pop('user')
            super(PostForm, self).__init__(*args, **kwargs)
    
    # views.py
    def profileView(request):
        form = None    
        if request.method == 'POST':
            exception=None
            if "categoria" in request.POST:
                if request.user:
                    form = PostForm(request.POST,request.FILES, user=request.user)  # pass user as a kwarg
                    print("postform POST: ",newPost, " File ",request.FILES)
                    if form.is_valid():
                        print("valid")
                        try:
                            form.save()
                            print("saved")
                            return HttpResponseRedirect(reverse_lazy('accounts:profile'))
                        except IntegrityError as e:
                            print("Integrity Error")
                            exception=e            
                    else:
                        print("PostForm error")
                        print(form.errors)
                    #form has been indented as previously it would have been called before being initialised
                    form.non_field_errors=form.errors
                    if exception is not None:
                        form.non_field_errors.update(exception)
        posts = Postagem.objects.get_queryset().order_by('id')
        paginator = Paginator(posts, 12)
        page = None
        if request.GET:
            page = request.GET.get('page')
        areas = Area.objects.all()   
        try:
            posts = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            posts = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            posts = paginator.page(paginator.num_pages)
        #return values    
        return render(
            request,
            'accounts/profile.html',
            {
                'form': form,
                'areas': areas,
                'posts': posts,
            }
        )
    

    【讨论】:

    • 问题是 self.environ 和 self.status 不是我项目中的具体内容。我正在使用 gulp 运行服务器。我正在运行 Django 1.11.3
    • 你在使用 ./manage.py runserver 运行django服务器的时候有这个问题吗?
    • 是的...... Gulp 基本上是做 runserver ,然后再观察变化来做 runserver ......
    • self.status 和 self.environ 看起来像是来自 django 使用的 WSGIref 模块。我不确定 gulp 做了什么来使服务器运行,但也许它正在剥离一些预期的标头?
    • 如果不将 userContext 添加到上下文列表会发生什么?可能是 userContext 包含了意外的值吗?您应该能够从 request.user 获取所有这些数据,因此您不需要将任何这些值传递回渲染函数。
    【解决方案3】:

    您使用的是 PostgreSQL 吗?这可能是由code page error 引起的。

    C:\>psql -U postgres
    psql (10.5)
    WARNING: Console code page (850) differs from Windows code page (1252)
             8-bit characters might not work correctly. See psql reference
             page "Notes for Windows users" for details.
    Type "help" for help.
    
    postgres=#
    

    在启动 Django 之前尝试设置代码页。

    cmd.exe /c chcp 1252
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      • 2016-09-11
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      相关资源
      最近更新 更多