Why do I receive a django error when trying to create a model instance with a foreign key?

爱⌒轻易说出口 提交于 2019-12-12 03:31:14

问题


I am receiving the following error:

ValueError: Cannot assign "u'ben'": "Entry.author" must be a "MyProfile" instance.

From this line:

form.author = request.session['username']

Note: Entry.author is a foreign key as seen below.

models.py

class MyProfile(models.Model):
    user = models.CharField(max_length=16)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

    def __unicode__(self):
        return u'%s %s %s' % (self.user, self.firstname, self.lastname)

class Entry(models.Model):
    headline= models.CharField(max_length=200,)
    body_text = models.TextField()
    author=models.ForeignKey(MyProfile, related_name='entryauthors')

    def __str__(self):
        return u'%s %s %s' % (self.headline, self.body_text, self.author)

The error says Entry.author must be a "MyProfile" instance, but when I go into the django shell and run a query, I see an instance exists with username ben.

<QuerySet [<MyProfile: ben ben    97201  None>]>

I am now wondering if request.session['username'] is maybe not returning a correctly formatted username and I have no way to test this (that I know of) in the django shell because I don't think you can access the request object from the shell.

In my login form, I have this line which is passing the username to the request.session.

if form.is_valid():
    username = form.cleaned_data['username']
    request.session['username'] = username

回答1:


form.author must be a MyProfile instance while request.session['username'] is a string. You may need to do a query selecting the Author such as form.author = MyProfile.objects.get(user=request.session['username'])

To prevent DoesNotExist error, you can do as follow:

try:
   form.author = MyProfile.objects.get(user=request.session['username'])
except MyProfile.DoesNotExist:
    form.author = None

Side Note: There is no username in MyProfile model so I assume it matches with the name




回答2:


As far as i have used it, the "foreign key" is to be a shared object location in each class (please excuse the pore terminology I am self-taught).

An example code is like this:

class One():
    key1 = models.CharField(max_length=150)

class Two():
    key1 = models.ForeignKey(key1)

I hope this helps.

https://github.com/Ry10p/django-Plugis/blob/master/courses/models.py line 52

-Cheers



来源:https://stackoverflow.com/questions/42755818/why-do-i-receive-a-django-error-when-trying-to-create-a-model-instance-with-a-fo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!