save() failing during first test

At least that's what I think is happening. When I run the first test in the tutorial, I get an assertion fail saying that my post.slug is not equal to slugify(post.title). It says my post.slug is blank. According to the terminal: " AssertionError: u' ' != u'test-blog-post' ". From my knowledge, my code is identical to yours, but I am running on Django 1.5. Could that be the issue?

Sorry You must be a logged in, registered user to answer a question.

Answers

models.py

from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
# Create your models here.
class PostManager(models.Manager):
    def live(self):
        return self.model.objects.filter(published="True")
class Post(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True, editable=False)
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, blank=True, default='')
    content = models.TextField()
    published = models.BooleanField(default=True)
    author = models.ForeignKey(User, related_name="posts")
    objects = PostManager()
    class Meta:
        ordering = ["-created_at", "title"]
    def __unicode__(self):
        return self.title
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)
    @models.permalink
    def get_absolute_url(self):
        return ("blog:detail", (), {"slug": self.slug})

views.py

# Create your views here.
from .models import Post
#from django.shortcuts import render
from django.views.generic import ListView, DetailView
class PublishPostMixin(object):
    def get_queryset(self):
        return self.model.objects.live()
        #queryset = super(PublishPostMixin, self).get_queryset()
        #return     queryset.filter(published=True)
class PostListView(PublishPostMixin, ListView):
    model = Post
class PostDetailView(PublishPostMixin, DetailView):
    model = Post

test_models.py

from django.contrib.auth.models import User
from django.test import TestCase
from django.template.defaultfilters import slugify
from ..models import Post
class BlogTests(TestCase):
    def setUp(self):
        self.user = User.objects.create(username='test')
    def test_model_creation(self):
        post = Post.objects.create(
            title = 'Test Blog Post',
            author = self.user
        )
        self.assertTrue(isinstance(post, Post))
        self.assertEqual(post.__unicode__(), post.title)
        self.assertEqual(post.slug, slugify(post.title))
I get nothing but a blank when printing it out.
bphan1 on
Your code looks correct but obviously something is acting up. Put `print post.slug` before the `self.assertTrue(` line in the test and check the output when you run your tests.
kennethlove (Staff) on