Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Basics Test Time Model Tests

Testing a User and votes of a Post.

I'm trying to test the User and a Post creation as well as the votes related to each post. When I run python manage.py tests.py The error I'm getting is 'voters' is an invalid keyword argument for this function.

Here is my models.py and tests.py file:

models.py

from django.db import models
from django.contrib.auth.models import User

from datetime import *

class Post(models.Model):
    user = models.ForeignKey(User, related_name='moderated_videos')
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.TextField()
    content = models.TextField()
    points = models.IntegerField(default=1)
    voters = models.ManyToManyField(User, related_name='liked_posts')
    category = models.CharField(max_length=20, choices=categories, default="technology")
    original_poster = models.BooleanField(default=False)
    updated_at = models.DateTimeField(auto_now=True)

tests.py

from django.test import TestCase
from django.utils import timezone

from django.contrib.auth.models import User

from .models import Post

class PostTest(TestCase):
    def test_post_creation(self):
        user = User.objects.create_user(
                username='shon'
        )
        post = Post.objects.create(
            title="My Title",
            content="Some lorem ipsum content",
            points=1,
            voters=user,
            category="gadgets",
            original_poster=False
        )
        now = timezone.now()
        self.assertLess(post.created_at, now)

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

voters is a many-to-many so you'll need to save the Post and then, I think, do post.voters.add(user).

Chris Freeman
Chris Freeman
Treehouse Moderator 68,454 Points

Correct. More specifically, Django automatically creates an addition database table for you to manage the ManyToMany relationship. The Post instance needs to be saved so that it gets a PK generated. This PK can then be used in the ManyToMany table to associate the PK to each voter (user PK).

See reference docs

Thank you guys for your answers. It really helped.