获取“ NoneType对象没有属性<属性名称>”异常

时间:2019-09-19 17:30:26

标签: django

我非常努力地找出问题所在,但失败了。 我收到以下异常:

  

Error-NoneType对象没有属性'membership_type'

我认为问题出在上下文中,就像我将上下文用作None一样,然后发生错误。 我尝试使用外键引用Membership类及其所有对象,但仍然出现此错误。

models.py

from django.conf import settings
from django.db import models
from django.db.models.signals import post_save

import stripe

stripe.api_key = settings.STRIPE_SECRET_KEY

MEMBERSHIP_CHOICES = (
    ('Enterprise','ent'),
    ('Professional','pro'),
    ('Free','free')
)


class Membership(models.Model):
    slug = models.SlugField()
    membership_type = 
models.CharField(choices=MEMBERSHIP_CHOICES,default='Free',max_length=30)
    price = models.IntegerField(default=15)
    stripe_plan_id = models.CharField(max_length=40)

    def __str__(self):
    return self.membership_type


class UserMembership(models.Model):
    user= models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete=models.CASCADE)
    stripe_customer_id = models.CharField(max_length=40)
    membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, 
null=True)

    def __str__(self):
        return self.user.username

def post_save_usermembership_create(sender,instance, created, *args, 
**kwargs):
    if created:
        UserMembership.objects.get_or_create(user= instance)
    user_membership, created = UserMembership.objects.get_or_create(user= 
instance)

    if user_membership.stripe_customer_id is None or 
           user_membership.stripe_customer_id=='':
        new_customer_id = stripe.Customer.create(email= instance.email)
        user_membership.stripe_customer_id = new_customer_id['id']
        user_membership.save()


post_save.connect(post_save_usermembership_create,
                      sender=settings.AUTH_USER_MODEL)




class Subscription(models.Model):
    user_membership = models.ForeignKey(UserMembership, 
                      on_delete=models.CASCADE)
    stripe_subscription_id = models.CharField(max_length=40)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.user_membership.user.username

courses / views.py

from django.shortcuts import render

from django.views.generic import ListView, DetailView,View

from .models import Course, Lesson

from membership_app.models import UserMembership
class CourseListView(ListView):
    model = Course

class CourseDetailView(DetailView):
    model = Course

class LessonDetailView(View):
    def get(self, request, course_slug, lesson_slug, *args, **kwargs):

        course_qs = Course.objects.filter(slug=course_slug)
        if course_qs.exists():
            course = course_qs.first()

        lesson_qs = course.lessons.filter(slug=lesson_slug)
        if lesson_qs.exists():
            lesson = lesson_qs.first()

        user_membership = UserMembership.objects.filter(user = request.user).first()
        user_membership_type = 
       getattr(user_membership.membership,'membership_type',None)
        # print(user_membership_type)

        course_allowed_membership_type = course.allowed_membership.all()

        context = {
           'object': None
        }

        if course_allowed_membership_type.filter(membership_type=user_membership_type).exists():
           context = {'object':lesson}

        return render(request, "courses/lesson_detail.html",context)

模板

 {% if object is not None %}
        {{ object.title }}
        {{ object.description }}
{% else %}
    <h3>Upgrade Membership</h3>
{% endif %}

1 个答案:

答案 0 :(得分:0)

您的问题在这一行。

    user_membership_type = user_membership.membership.membership_type

原因是您允许UserMembership.membership为空值。因此,当您检索UserMembership等于membership的{​​{1}}并尝试从中取出None时,会产生错误。我认为membership_type是解决此问题的最佳方法。

getattr