Choice field from database instead of hardcoded values


(mohammed younus) #1


In the above tutorial choice field for BookTypes is populated with hardcoded values , how to achieve same from backend(i.e from database).

In models.py file i have 2 database tables Book and BookTypes

class BookTypes(models.Model):
Name = models.CharField(max_length=30)

class Book(models.Model):
title = models.CharField(max_length=20)
publication_date = models.DateField(blank=True, null=True ,max_length=20)
author = models.CharField(max_length=20, blank=True)
price = models.DecimalField(max_digits=5, decimal_places=2)
pages = models.IntegerField(blank=True, null=True)
book_type = models.ForeignKey(BookTypes)

In forms.py i have a class BookForm

class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = (‘title’, ‘publication_date’, ‘author’, ‘price’, ‘pages’, ‘book_type’, )