Django:如何修复 RelatedOjbectDoesNotExist 异常?

标签 django

型号:

class Users(models.Model):
    first_nm = models.CharField('First Name', max_length=100)
    last_nm = models.CharField('Last Name', max_length=100)
    email = models.EmailField('Email Address', max_length=200, unique=True )

class Invoices(models.Model):
    invoice_date = models.DateField('created date', auto_now=True)
    user = models.ForeignKey(Users)

查看:

    def post(self, request):
    bound_form = UsersForm(request.POST)

    if bound_form.is_valid() and lineItemsForm.is_valid() and formset.is_valid():
        u = Users()
        u.first_nm = bound_form.cleaned_data['first_nm']
        u.last_nm = bound_form.cleaned_data['last_nm']
        u.email = bound_form.cleaned_data['email']
        u.save()
        i = Invoices()
        i.user.add(u)
        i.save()

在我调用 i.save() 之后,我得到了这个:

Request Method: POST
Request URL:    http://gpga-hrguys.rhcloud.com/players/create_user/
Django Version: 1.8.4
Exception Type: RelatedObjectDoesNotExist
Exception Value:    
Invoices has no user.

Invoices怎么可能没有用户呢?我在调用 i.save() 之前将它添加到 Invoices 对象

最佳答案

您在发票中设置的用户有误。因为它是一个ForeignKey,所以简单地说:

i.user = u
i.save()

i.user.add(u) 如果用户是 ManyToMany 字段。 为了您的信息,您可以通过调用访问用户的所有发票:

u.invoice_set

关于Django:如何修复 RelatedOjbectDoesNotExist 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34806915/

相关文章:

生产环境中尝试登录时出现 Django "500 internal server error"

django - 将文件从一个模型复制到另一个模型

django - 是否有一个可插入的 Django 树应用程序,具有良好的管理能力?

python - 限制 Django 中内联表单集的外键查询集

python - 如何从 Django 模型创建双长文本字段

django - Django 平面页面的 View ?

python - Django:基于类的 View 注销用户(如果不是员工)

jquery - 链接停止工作——jquery 问题?

python - Django 不收集静态文件

python - django __init__ 方法导致参数错误