1

I am trying to learn Django and have a very simple question that I am not able to get around with. I have coded my Django model as:

class Work(models.Model):
    STATES = (
        ('STARTED', 'started'),
        ('IN_PROGRESS', 'running'),
        ('FINISHED', 'completed'),
        ('ERROR', 'Error'),
    )
    owner = models.ForeignKey("auth.User")
    temp  = models.CharField(max_length=50, null=True, blank=True)
    current_run = models.CharField(max_length=50, null=True, blank=True)
    completion_percentage = models.IntegerField(blank=True, null=True)
    status = models.CharField(choices=STATES, max_length=50, blank=True, null=True)

I have regenerated the db and now I want to use it Django views. But, before that is there a way to test it using python manage.py shell?

I am trying to do:

d_ = Work.objects.create(owner='admin')

I get the error

ValueError: Cannot assign "'admin'": "Work.owner" must be a "User" instance.

Currently, I have userid as 'admin' in Users. I have tried doing few things to get around the error but I keep getting some kind of error because of the owner field (which is set to foreign key of auth.User).

Any help will be appreciated here. Thank you!

yguw
  • 856
  • 6
  • 12
  • 32
  • What's confusing you about that message? You need an actual User instance, not a username. – Daniel Roseman Jul 06 '17 at 19:34
  • @DanielRoseman you're right. I tried user instance but i was doing something wrong. Now, I get it and below answer also helps me. Thanks! – yguw Jul 06 '17 at 19:49

1 Answers1

1

You need to use an actual user object. Try this

from django.contrib.auth.models import User
admin = User.objects.get(username='admin')
d_ = Work.objects.create(owner=admin)
spooky
  • 106
  • 1
  • 5