Home > Net >  How can i select multiple tag from tag model in django
How can i select multiple tag from tag model in django

Time:09-18

I'm beginner in Django/Python and I need to create a multiple select form. I know it's easy but I can't find any example. i use django-taggit.i want to select multiple tag in tag form. here is my forms.py

class BlogPostForm(ModelForm):



class Meta:
    model = BlogPost
    fields = ("title","body","tags")



    widgets ={
      'title' : TextInput(attrs={'class':'form-control ' ,'placeholder':'Title'}),
       'body' : TextInput(attrs={'class':'form-control'}),

    }

here is my models.py

class BlogPost(models.Model):
title = models.CharField( max_length=100,unique=True)
body = RichTextField()
date  = models.DateTimeField(default=timezone.now)
slug = models.SlugField()
tags = TaggableManager()
# class Meta:
#     verbose_name = ("BlogPost")
#     verbose_name_plural = ("BlogPosts")

def __str__(self):
    return self.title

CodePudding user response:

You can use ModelMultipleChoiceField to select multiple tag in tag form, like this:

tags = forms.ModelMultipleChoiceField(label='Tags', queryset=Tag.objects.all())

queryset: A QuerySet of model objects from which the choices for the field are derived and which is used to validate the user’s selection. It’s evaluated when the form is rendered.

if you have the model about Tag, it can try the example code.

More information can be found here: https://docs.djangoproject.com/en/4.1/ref/forms/fields/#modelchoicefield

  • Related