0

I am writing a blog application in Django. In the models.py I have two classes: Post and LanguageCategory. In language category I would predefine which languages are applicable such as English, Italian, and this could be created by superuser in admin login. However, inside the Post class I want to use the LanguageCategory class as a property called languages as follows (code for models.py):

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

# Create your models here.
# https://stackoverflow.com/questions/29536180/django-blog-adding-published-date-field-to-new-posts-and-ability-to-login-as-non
class Post(models.Model):
    title = models.CharField(max_length=300)
    keywords = models.CharField(max_length=300, default="some keywords here")
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(auto_now_add=True,
            blank=False, null=False)
    language = LanguageCategory()
    image = models.ImageField(upload_to='blog_images/', default='blog_images/myimage.png')
    body = models.TextField()

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title + ' | ' + str(self.author)


class LanguageCategory(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

When I try to make migrations I get the following error:

line 15, in Post language = LanguageCategory() NameError: name 'LanguageCategory' is not defined

How to fix this issue and how can I use LanguageCategory in the Post such that the blog posts has a field which selects the languages?

1 Answer 1

1

You could foreign key. And instead of direct reference, you could quote it like following.

language = models.ForeignKey('LanguageCategory', on_delete=models.CASCADE)

The full code as follows:

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

# Create your models here.
# https://stackoverflow.com/questions/29536180/django-blog-adding-published-date-field-to-new-posts-and-ability-to-login-as-non
class Post(models.Model):
    title = models.CharField(max_length=300)
    keywords = models.CharField(max_length=300, default="some keywords here")
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(auto_now_add=True,
            blank=False, null=False)
    language = models.ForeignKey('LanguageCategory', on_delete=models.CASCADE)
    image = models.ImageField(upload_to='blog_images/', default='blog_images/myimage.png')
    body = models.TextField()

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title + ' | ' + str(self.author)


class LanguageCategory(models.Model):
    name = models.CharField(max_length=100, default='english', primary_key = True)

    def __str__(self):
        return self.name

Reference:

https://docs.djangoproject.com/en/3.1/ref/models/fields/#lazy-relationships

Sign up to request clarification or add additional context in comments.

4 Comments

btw when I am doing makemigrations it is saying: ValueError: Field 'id' expected a number but got 'english'. what should be the default value in language in Post?
Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column) However, your code should never have to deal with the database column name, unless you write custom SQL. You’ll always deal with the field names of your model object.
should it be something like this--> class LanguageCategory(models.Model): name = models.CharField(max_length=100, default='english', primary_key = True)
Could you post your whole error traceback? for Django Model, it adds id field as default.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.