How to fill author or user name using python shell

Yash Marmat :

I was trying to fill my author field using python shell, in shell i was typing this:

Post.objects.create(title='second blog post', author="yashm",
        body='done via python shell')

I already created a superuser named as 'yashm', but still im getting this error (see picture)

enter image description here

Models.py file

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length = 120)
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    body = models.TextField()


    def __str__(self):
        return self.title[:50]
Lemayzeur :

You need to create the user instance first.

from django.contrib.auth.models import User
user = User.objects.create_user(username='yashm',first_name='yashm',
           last_name='yashm', email='')

And then you will be able create your post object:

Post.objects.create(title='second blog post', author=user, body='done via python shell')

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398797&siteId=1