Django试试,除了和ObjectDoesNotExist

时间:2018-07-21 15:05:47

标签: django

我正在尝试实现三种打印消息之一,以便继续执行我的代码。现在我总是收到

  

RelatedObjectDoesNotExist用户没有ambassador_profile。

我实际上期望的是print(“没有amb配置文件”)。有人知道我在这里做错了吗?

views.py

   user = request.user

        try:
            ambassador = user.ambassador_profile
            selected_event = get_object_or_404(Event, slug=event, organizer__slug=organizer)
            connected_events = ambassador.events.all()
            if selected_event in connected_events:
                print("You have an ambassador profile and you are connected.")
            else:
                print("You are not connected.")
        except user.ambassador_profile.ObjectDoesNotExist:
            print("No amb profile")

models.py

class AmbassadorProfile(models.Model):
    slug = models.CharField(
        max_length=10,
        unique=True,
    )
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='ambassador_profile',
    )

2 个答案:

答案 0 :(得分:0)

您的用户似乎不存在。 试试这个:

PostEvent

答案 1 :(得分:0)

实际上解决问题的方法是将except user.ambassador_profile.ObjectDoesNotExist:更改为except AmbassadorProfile.DoesNotExist: