Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage tag with django-select2

We use django-select2 for a project at work for managing tags. So now we use like this:

tags = ModelSelect2MultipleField(queryset=Tag.objects, required=False)

So it only works for existing tags, But it would be closer to the model stackoverflow and if the tag does not exist it adds, I found this link Tagging with AJAX in select2 which allows to manage side js, I'd like to know if it is possible to use an option in django-select2 to add it to the generated js. I would also like to know if instead of using the id it is possible to use a different field and side views in a get_form_kwargs I make a get_or_create.

Thanks

like image 1000
Hobbestigrou Avatar asked Dec 11 '25 05:12

Hobbestigrou


1 Answers

Applegrew make a new release that implements the management of tags with the tag created if it does not exist in the table. So use AutoModelSelect2TagField:

from django_select2 import AutoModelSelect2TagField


class TagChoices(AutoModelSelect2TagField):
    queryset = Tag.objects
    search_fields = ['name__icontains']

    def get_model_field_values(self, value):
        return {'name': value }


class SimpleForm(forms.ModelForm):
    tags = TagChoices(required=False)

Here is a small example of using.

like image 106
Hobbestigrou Avatar answered Dec 13 '25 17:12

Hobbestigrou