Django Pytest - Injecting User instance

Hi,

I’m in a pickle. I’m working through my first app and have decided to be disciplined and create tests as I go for each new feature.

As far as this goes, I’m stuck on what I feel should be a basic fundamental thing… I haven’t been able to grasp it…

I have a field ‘created_by’ in my model which is automatically populated by the current logged in user. Works fine…

But how on earth do I put this instance into my tests? I’m building from Mosh’s testing tutorials in the course but it only covers authenticated user or not… not actually passing an instance into the endpoint.

The error I get is:
ValueError: Cannot assign “<User: >”: “Catalogue.created_by” must be a “User” instance.

Thanks in advance!

Post code related to your issues please

Thanks TinMan, here is what I think is relevant.

core.models

class User(AbstractUser):
    email = models.EmailField(unique=True)

workshop.models

class Catalogue(models.Model):
    STATE_DRAFT = 'DRAFT'
    STATE_PUBLISHED_PRIVATE = 'PUBPRIV'
    STATE_PUBLISHED_PUBLIC = 'PUBPUB'

    STATE_CHOICES = [
        (STATE_DRAFT, 'Draft'),
        (STATE_PUBLISHED_PRIVATE, 'Published (Private)'),
        (STATE_PUBLISHED_PUBLIC, 'Published (Public)')
    ]
    company = models.ForeignKey(Company, on_delete=models.PROTECT)
    title = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    state = models.CharField(
        max_length=10, choices=STATE_CHOICES, default=STATE_DRAFT)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self) -> str:
        return self.title

conftest.py

@pytest.fixture
def authenticate(api_client):
    def do_authenticate(is_staff=False):
        return api_client.force_authenticate(user=User(is_staff=is_staff))
    return do_authenticate

test_catalogues.py

@pytest.fixture
def create_catalogue(api_client):
    def do_create_catalogue(catalogue):
        return api_client.post('/companies/1/catalogues/', catalogue)
    return do_create_catalogue

@pytest.mark.django_db
class TestCreateCatalogue:
    def test_if_data_is_valid_returns_201(self, authenticate, create_catalogue):

        authenticate(is_staff=True)
        user = 'this is where i guess i need to get the user instance'
        response = create_catalogue({'title': 'a', 'created_by':user})

        assert response.status_code == status.HTTP_201_CREATED
        assert response.data['id'] > 0

Resulting error:
ValueError: Cannot assign “<User: >”: “Catalogue.created_by” must be a “User” instance.

You would just have to query the default user table for the user.

If you do not know the specific user instance id to query, you can just call User.objects.all().first() which will get the first user instance it finds in the table.