Hi, So I am new to Django-taggit and I am slowly only learning how to implement tags in django. So, My problem is I already have a model named Genre and other model named Book so what i want to do is I want to implement the names of Genre as tags in Book Model in a field named genre which is genre_tag, So any idea that how do i achieve it and i want to use these tags in add or manage book forums as well. Well, I would also like some advice on Django-taggit like whether are there any resources from where i can learn .
models.py:
class Genre(models.Model):
name = models.CharField(max_length=300)
description = models.TextField(blank=True, null=True)
date_created = models.DateField(auto_now=True)
class Meta:
verbose_name_plural = "List of Genres"
def __str__(self):
return str(f"{self.name}")
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across the library")
title = models.CharField(max_length=750)
author = models.CharField(max_length=350)
pages = models.PositiveIntegerField()
genre_tag = TaggableManager()
year_published = models.PositiveIntegerField(validators=[MinValueValidator(1700), MaxValueValidator(datetime.now().year)], default=datetime.now().year, help_text="Use the following format: <YYYY>")
book_format = models.CharField(max_length=50, default='paperback', choices=FORMAT_CHOICES)
is_borrowed = models.BooleanField(default=False)
class Meta:
verbose_name_plural = "List of Books"
def __str__(self):
return str(f"{self.id} - {self.title}")
forms.py:
class SaveBook (forms.ModelForm):
title = forms.CharField(label="Book Title", max_length=750, widget=forms.TextInput(attrs={"class": "form-control rounded = 0"}))
author = forms.CharField(label="Book Author", max_length=350, widget=forms.TextInput(attrs={"class": "form-control rounded-0"}))
pages = forms.IntegerField(label="Number of Pages in Book", widget=forms.NumberInput(attrs={"class": "form-control rounded-0"}))
year_published = forms.IntegerField(label="Year Published", widget=forms.DateInput(format=['%Y'], attrs={"class": "form-control rounded-0"}))
genre_tag = forms.CharField(label="Book Genre", widget=TagWidget(attrs={"class": "form-control rounded-0", "data-tags": ",".join(Genre.objects.values_list('name', flat=True))}))
book_format = forms.ChoiceField(choices=FORMAT_CHOICES, label="Book Format", widget=forms.Select(attrs={"class": "form-control form-select rounded-0"}))
class Meta:
model = Book
fields = ['title', 'author', 'pages', 'year_published', 'genre_tag' ,'book_format']
def clean_genre(self):
genres = self.cleaned_data.get('genre')
if not genres:
raise forms.ValidationError("Please select at least one genre.")
return genres