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
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
Share Improve this question edited May 23, 2017 at 12:23 CommunityBot 11 silver badge asked Sep 11, 2013 at 13:57 HobbestigrouHobbestigrou 1,8871 gold badge14 silver badges16 bronze badges 2- 1 This is a new enhancement - github./applegrew/django-select2/issues/33. This is on TODO list but I cannot promise about the timeline. I would really appreciate if someone can lend a help regarding this. – AppleGrew Commented Sep 11, 2013 at 14:08
-
1
You could have a look at
django-select2-forms
with thejs_option
parameter. Mixed with stackoverflow./a/14841968/186202 it should be a good start. Or you can make a PR ondjango-select2
– Natim Commented Sep 11, 2013 at 14:17
2 Answers
Reset to default 3Applegrew 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.
This is what worked for me with django-select2==7.1.1
#models.py
from django.db import models
class Tag(models.Model):
name = models.CharField(('Name'), max_length=255, unique=True)
def __str__(self):
return self.name
class Article(models.Model):
title = models.CharField(max_length=255)
tags = models.ManyToManyField('Tag', blank=True)
#forms.py
from django_select2.forms import ModelSelect2TagWidget
class ArticleTagSelect2TagWidget(ModelSelect2TagWidget):
"""
Widget class for auto populate, edit & add tags.
"""
queryset = Tag.objects.all()
search_fields = ('name__icontains',)
@property
def empty_label(self):
return 'Type in tags'
def value_from_datadict(self, data, files, name):
'''Create objects for given non-pimary-key values. Return list of all names as name is the to_field_name.'''
values = set(super().value_from_datadict(data, files, name))
# This may only work for Tag, if Tag has title field.
# You need to implement this method yourself, to ensure proper object creation.
names = self.queryset.filter(**{'name__in': list(values)}).values_list('name', flat=True)
cleaned_values = list(names)
for val in values - set(list(names)):
cleaned_values.append(self.queryset.create(name=val).name)
return cleaned_values
class AddArticleForm(forms.ModelForm):
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all(),
widget=ArticleTagSelect2TagWidget(data_view='dashboard:auto-json'),
required=False, to_field_name='name',)
class Meta:
model = Article
#views.py
AutoResponseView is overriden for making the ajax return name instead of id.
from django_select2.views import AutoResponseView
class TagAutoResponseView(AutoResponseView):
def get(self, request, *args, **kwargs):
"""
This method is overriden for changing id to name instead of pk.
"""
self.widget = self.get_widget_or_404()
self.term = kwargs.get('term', request.GET.get('term', ''))
self.object_list = self.get_queryset()
context = self.get_context_data()
return JsonResponse({
'results': [
{
'text': self.widget.label_from_instance(obj),
'id': obj.name,
}
for obj in context['object_list']
],
'more': context['page_obj'].has_next()
})
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745587051a4634604.html
评论列表(0条)