castbound
castbound

Reputation: 51

NameError: name 'MyModel' is not defined. Why?

I dont really understand what is happening in my code but it says the my Book model is undefined. Below is my code:

This is my forms.py

from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']


class BooksForm(forms.ModelForm):

    class Meta:
        model = Books
        fields=('book_id',)

my models.py

class Books(models.Model):
    book_id = models.CharField(primary_key=True, max_length=50)
    book_title = models.CharField(max_length = 100)
    book_author_id = models.ForeignKey(Author, on_delete=models.CASCADE)
    book_cover = models.ImageField(upload_to='media/')
    book_file = models.FileField(upload_to='media/')
    book_year = models.DateField(default = timezone.now)
    book_tags = models.CharField(max_length = 100)
    book_summary = models.CharField(max_length = 100)
    book_category_no = models.ForeignKey(Category, on_delete=models.CASCADE)
    book_info = models.CharField(max_length = 100, default="")
    is_bookmarked = models.BooleanField()
    is_downloaded = models.BooleanField()
    is_read = models.BooleanField()

    class Meta:
        db_table = "Books"

Upvotes: 2

Views: 1142

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

You need to import the model into the scope of the forms module:

from app_name.models import Books

where app_name is the name of the app.


Note: normally a Django model is given a singular name, so Book instead of Books.

Upvotes: 1

Related Questions