Django:我如何修复RelatedOjbectDoesNotExist异常?

时间:2016-01-15 08:26:10

标签: 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.

发票如何没有用户?我在调用i.save()

之前将它添加到Invoices对象中

3 个答案:

答案 0 :(得分:5)

您正在设置发票中的用户错误。由于它是ForeignKey,只需输入:

i.user = u
i.save()

i.user.add(u)将是if,user是ManyToMany字段。 有关您的信息,您可以致电:

访问用户的所有发票
u.invoice_set

答案 1 :(得分:1)

试试这个:

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.invoice_date=datetime.now() #if you want to add current date
        i.user=u
        i.save()

答案 2 :(得分:0)

实际上你不能用add添加ForeignKey,要么设置整个对象:

i.user = u
i.save()

或者设置引用ForeignKey的字段:

i.user_id = u.id
i.save()
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 = u # modification should be here
        i.save()