[Fixed]-Name error: Can not import [model name]

1👍

I am considering that you have indented your code for Post model properly in your file.

Solution : Try to define Topic above Post.

0👍

First, this

topic = models.ForeignKey(Topic, blank=True, null=True)

should be this

topic = models.ForeignKey('Topic', blank=True, null=True)

This way it tells django that you’re setting a foreign key to a model, which isn’t declared yet, but will be declared further in the code.

Second, you should properly indent your Post model and its methods:

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    title = models.CharField(max_length=100)
    summary = models.TextField(blank=True, null=True)
    content = models.TextField()
    draft = models.BooleanField(default=False)
    details = models.CharField(blank=True, null=True, max_length=250)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    topic = models.ForeignKey('Topic', blank=True, null=True)
    thumbnail = models.ImageField(upload_to='media', blank=True, null=True)

    def get_absolute_url(self):
        return reverse('posts:detail', kwargs={'pk': self.pk})

    def __str__(self):
        return self.title

Because as you have it now, django doesn’t understand that the unindented fields belong to the Post model.

Leave a comment