Django test model with FilerImageField

506 views Asked by At

All new to Django, I want to write tests for an IndexView and a DetailView in analogy to the Django tutorial.

I have a model that contains a FilerImageField as mandatory field (blank=False).

In order to test my views related to that model, I want to create a model instance programmatically.

I am aware of this question addressing how to create a FilerImageField in code. The problem I run into applying the alleged solution is getting the part right about the image's owner.

def create_exhibitor(name, image_path, active):
    filename = 'file'
    user = User.objects.get(username='myuser')
    with open(image_path) as f:
        file_obj = File(f, name=filename)
        image = Image.objects.create(
            owner=user,
            original_filename=filename,
            file=file_obj
        )

        return Exhibitor(name=name, image=image, active=active)

Runnging them tests yields:

Traceback (most recent call last):
...
DoesNotExist: User matching query does not exist.

To me it appears there is no user in the test database.

So my question is twofold really:

Do I need a user there to create an instance of the model containing the FilerImageField?

If so, how do I create one for test purposes?

1

There are 1 answers

0
creimers On BEST ANSWER

I'm finally doing it like so:

from django.test import TestCase
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from .models import Exhibitor

class TestCase():
    su_username = 'user'
    su_password = 'pass'

    def setUp(self):
        self.superuser = self.create_superuser()

    def create_superuser(self):
        return User.objects.create_superuser(self.su_username, '[email protected]', self.su_password)

    def create_exhibitor(self):
       name = 'eins'
       active = True
       image_file = SimpleUploadedFile(
        'monkey.jpg', b'monkey', content_type="image/jpeg"
       )
       return Exhibitor(name=name, image=image_file, active=active)