【问题标题】:django - AttributeError: 'NoneType' object has no attribute 'first_name'django - AttributeError:“NoneType”对象没有属性“first_name”
【发布时间】:2016-10-21 02:32:03
【问题描述】:

每当我尝试设置我的client 时,我会收到以下错误:AttributeError: 'NoneType' object has no attribute 'first_name'。

这是日志:

Environment:


Request Method: GET
Request URL: http://192.168.33.10:8000/podfunnel/clientsetup/

Django Version: 1.9
Python Version: 2.7.6
Installed Applications:
('producer',
 'django.contrib.admin',
 'django.contrib.sites',
 'registration',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'storages',
 'django_extensions',
 'randomslugfield',
 'adminsortable2',
 'crispy_forms')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')



Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/home/vagrant/fullcast_project/producer/views/pod_funnel.py" in get
  110.         initial_values['first_name'] = client.first_name

Exception Type: AttributeError at /podfunnel/clientsetup/
Exception Value: 'NoneType' object has no attribute 'first_name'

它必须在我的ClientSetupView 下 y views.py:

class ClientSetupView(View):
form_class = ClientSetupForm
template_name = 'pod_funnel/forms.html'

# In the get we manage the request to get the form and prefill it if necessary
def get(self, request, *args, **kwargs):
    # We need to check first if the current user has a client and podcast setup,
    # if so, prepopulate. Otherwise get empty form.
    initial_values = {}
    user = request.user

    if Client.objects.filter(user=user).exists():

        client = CLient.objects.filter(user=user).first()

        initial_values['first_name'] = client.first_name
        initial_values['last_name'] = client.last_name

        podcast = Podcast.objects.filter(client=client).first()
        request.session['client_id'] = client.id

        if podcast:
            initial_values['podcast_name'] = podcast.name
            # lets store podcast_id in session so we can retrieve it directly in post
            request.session['podcast_id'] = podcast.id

    form = self.form_class(initial=initial_values)
    return render(request, self.template_name, {'form': form})

# In the the post we manage updates to the data
def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)

    if form.is_valid():
        # lets get the data
        first_name = form.cleaned_data.get('first_name')
        last_name = form.cleaned_data.get('last_name')
        podcast_name = form.cleaned_data.get('podcast_name')

        # First we see if we have a client_id in session, if so we retrieve and update
        # otherwise we create a new one.
        client_id = request.session.get('client_id', None)
        if client_id is not None:
            request.session.delete('client_id')
            client = Client.objects.get(id=client_id)
        else:
            client = Client()
        client.first_name = first_name
        client.last_name = last_name
        client.company_name = podcast_name
        client.save()

        # Now we update or create the associated podcast.
        podcast_id = request.session.get('podcast_id', None)
        if podcast_id is not None:
            request.session.delete('podcast_id')
            podcast = Podcast.objects.get(id=podcast_id)
        else:
            podcast = Podcast()
        podcast.client = client
        podcast.name = podcast_name
        podcast.save()

        success, message_list = update_or_create_preset_for_podcast(podcast)

        # in any case we can continue with additional podcast setup, but we need
        # to attempt to create the preset one more time at some point before the
        # user can create the first productions.
        return HttpResponseRedirect(reverse('podfunnel:podcastsetup'))

    return render(request, self.template_name, {'form': form})

【问题讨论】:

  • 你应该包括 ClientSetupForm 和你的客户端模型

标签: python django django-models django-views django-class-based-views


【解决方案1】:

您检查的行if client is not None 应该在从数据库读取后立即出现,因为如果没有项目,first 可能会返回None:

client = Client.objects.filter(user=user).first()
if client is not None:
    initial_values['first_name'] = client.first_name
    initial_values['last_name'] = client.last_name

或者您可以在获取first之前使用exists测试该用户是否至少有一个客户端:

if Client.objects.filter(user=user).exists():
    client = Client.objects.filter(user=user).first()
    initial_values['first_name'] = client.first_name
    initial_values['last_name'] = client.last_name

exists 方法更有效:

如果 QuerySet 包含任何结果,则返回 True,否则返回 False。 这试图以最简单和最快的方式执行查询 可能,但它确实执行与普通查询几乎相同的查询 QuerySet 查询。

【讨论】:

  • 感谢您的帮助!现在我收到另一个与IntegrityError: null value in column "user_id" violates not-null constraint 相关的错误。我已经用错误日志和新版本的 my`views.py 更新了我的问题。
【解决方案2】:

根据文档first() 将返回None,如果没有匹配项:

返回查询集匹配的第一个对象,如果没有匹配的对象,则返回 None。

换句话说,client 在执行此行后有一个None 值:

client = Client.objects.filter(user=user).first()

这意味着当前用户没有客户端。

【讨论】:

  • 感谢您的帮助,您的问题和上一个问题非常好!但是现在我遇到了另一个与IntegrityError: null value in column "user_id" violates not-null constraint 相关的错误。我已经用错误日志和新版本的 my`views.py 更新了我的问题。
猜你喜欢
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 2018-03-16
  • 2018-04-11
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
相关资源
最近更新 更多