Giter VIP home page Giter VIP logo

django-select2's Introduction

django-select2's People

Contributors

andrewdodd avatar annefly avatar apalazon avatar applegrew avatar bcail avatar bogdal avatar bubenkoff avatar cleitondelima avatar codingjoe avatar crccheck avatar darbula avatar emorozov avatar fjcapdevila avatar geyser avatar graingert avatar hartwork avatar hotet avatar jbigatti avatar jieter avatar jonatascastro12 avatar jsenecal avatar mfrasca avatar mociepka avatar predatell avatar pyup-bot avatar rizumu avatar scotteadams avatar stephane avatar superqwer avatar tisdall avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-select2's Issues

Can't pass option to select2 w/o giving data_view

I didn't find examples in tests which set select2 options.

class FooSelect2Field(django_select2.AutoModelSelect2Field):
    queryset = Foo.objects
    search_fields = ['name__icontains, ]

    station = StationSelect2Field(widget=django_select2.AutoHeavySelect2Widget(select2_options={
        'width': '32em',
        'placeHolder': _(u"Search foo")
    })

will raise an error about missing view so I need to add data_view='django_select2_central_json' to widget init.

Mutiple Select has fixed width

Mutiple Select has fixed width of 300 px. This is killing some of my css. It makes it so I can no longer use the template_tags to load static files. Either a way to kill the extra.css or removing those fixed numbers would be awesome.

Python 3 support

Not really an issue, for now…

Do you plan to port django-select2 to python 3?

Pip doesn't install template tags

I tried installing django_select2 3.0.2 using pip, but it appears that the template tags directory isn't included in the installation.

AutoSelect2MultipleField does not bind GET value on page render

I have developed a search form using an AutoSelect2MultipleField field and it works great, however, when you submit the form using GET and render the search results and the completed form, the AutoSelect2MultipleField stays empty.

It is something similar to the resolved issue #1, the difference is that this is not a "Model" field.

This is the code for my field, I think that I have overriden the required methods:

class NombreGrupoInvestigacionField(AutoSelect2MultipleField):
    """
    Selects a research group
    """
    def security_check(self, request, *args, **kwargs):
        user = request.user
        if not user.is_authenticated():
            return False
        return True
    def get_results(self, request, term, page, context):
        res = [('group1',u'group1'),('group2',u'group2'),]
        return (NO_ERR_RESP, False, res) 

On the same form I have an AutoModelSelect2MultipleField (overriden by me), and it works perfectly. Do I need to implement any extra method on my field class?

I'm using django 1.4.8 and the latest django_select2 version on github.

I have debuged the code, and found that the methods django_select2.widgets.HeavySelect2MultipleWidget.render_texts_for_value() and django.forms.fields.Field.bound_data() does not get called for this field when the form renders with the results.

Thank you very much for your responses, regards,

Show green plus icon for popup after django-select2 field

Is it possible to add green plus icon for adding new items as it is in original ForeignKey fields? If not by settings, maybe some hints on bringing plus icons back?

It was really useful feature, that i liked a lot in django admin. But i also love these select2 dropdowns and this package. Since select2 has perfect API functions to manage/populate/reload etc. it should be possible.
Thank you.

createSearchChoice

Hey I'm sorry to file an issue. But I can't figure out how to override the createSearchChoice option. I searched myself dead in your code. There and even when I found the correct super class (multiple inheritance doesn't make it easier) I wasn't able to override it.

I hope this is me doing something wrong, but to be honest, this would be an important thing to add to you documentation. Adding options in place is important considering this being used for tags.

4.2.2 bug... AttributeError using AutoModelSelect2Field / AutoHeavySelect2Widget

Hi Applegrew!

This code below worked until 4.2.1... using 4.2.2, a error is trowed:

  • 'CityChoices' object has no attribute 'empty_values'

class CityChoices(AutoModelSelect2Field):
queryset = City.objects
search_fields = ['name__icontains']

class SomeForm(ModelForm):
city = CityChoices(widget=AutoHeavySelect2Widget())

Trouble deploying to heroku

For some reason I'm not completely sure, when I deploy to Heroku I get random 404 errors. On my dev machine everything works fine. In heroku I'm working with just one instance if thats any help.

Try hitting the following url many times and see the outcome I'm talking about (sometimes it works)
http://www.marketily.com/select2/fields/auto.json?term=santiago&page=1&context=&field_id=0%3A2012-10-27+00%3A31%3A33.956297

This is the code for that field:
class CityChoices(AutoModelSelect2Field):

queryset = City.objects
search_fields = ['name__icontains']

field_id = 'id_city'

def get_results(self, request, term, page, context):

    terms = re.split(' |,',term)
    cities = City.objects
    full_query = None

    for t in terms:
        q = Q(name__icontains=t) | Q(country__name__icontains=t)
        full_query = q if not full_query else full_query & q
    cities = cities.filter(full_query).all()[:10]

    res = [ (city.pk, "%s, %s" % (city.name, city.country.name),) for city in cities ]
    return NO_ERR_RESP, False, res

Error while saving a field without value

I'm using an AutoModelSelect2Field in django's admin site, and works fine except when I try to submit a form without any value for this field. The complete traceback is here: (http://dpaste.com/1392138/)

It seems to be a problem while rendering the widget, maybe it assumes it has a value.

The AutoModelSelect2Field does not work for new added form when used with admin.StackedInline

I want to use the AutoModelSelect2Field in django admin within a inline form like this:

forms.py

class ProductChoices(AutoModelSelect2Field):
    queryset = Product.objects
    search_fields = ['name__icontains', ]

class OrderItemAdminForm(forms.ModelForm):
    product = ProductChoices(required=False, label=_("Product"))
    performlist = forms.DateTimeField(required=False, widget=PerformList)
    pricelist = forms.IntegerField(required=False, label=_("Price List"), widget=PriceList)
    class Meta:
        model = OrderItem

admin.py

class OrderItemInline(admin.StackedInline):
    form = OrderItemAdminForm
    model = OrderItem
    extra = 1
    fields = ('product', 'performlist', 'pricelist', 'price', 'quantity', 'receivable', 'received')
    raw_id_fields = ['price',]

it is all ok but when I click the add another inline form, the AutoModelSelect2Field of the new added form does not work, I think I should use jquery live method to bind new add element, but I don't know how to do? Can you give me some hints, thanks

Performance issue on large data set

Hello,

I use django-select2 on a quietly large table (40000 entries). The unicode method of this model requieres to get data from 2 other tables. Then almost 120 000 queries to get data to populate the choices attr.

Is there any mean to bypass this ?

Regards,

Laurent

Unable to get initial value to work with ForeignKeys

I'm using a HeavySelect2Widget to select an entry from a list on a related table. I've got the ajax lookup working fine, and data is being saved correctly, but when I edit the entry I just made the Select2 field shows no initial value.

Does anyone have any working examples of using this to connect tables using the Heavy widget and AJAX lookups?

How to have AutoModelSelect2Field prepopulated on edit?

We are using AutoModelSelect2Field like that:

from django_select2.fields import AutoModelSelect2Field


class EmployeeChoices(AutoModelSelect2Field):
    search_fields = ('last_name__icontains', 'first_name__icontains')

    def get_queryset(self):
        current_site = Site.objects.get_current()
        return User.objects.of_site(current_site).employees()

    def set_queryset(self, queryset):
        pass

    queryset = property(get_queryset, set_queryset)


class TicketForm(forms.ModelForm):
    employee = EmployeeChoices(label=_('Employee'), required=False)

    class Meta:
        model = Ticket
        fields = ('employee', 'subject', 'body', 'priority')

But when we load the ModelForm with an instance, the employee field is empty instead of containing the instance value.

Do you have any idea what's wrong?

It could be very nice to be able to define get_queryset() without having to use this awkward trick.

On Internet Explorer, only one value can be saved when using an AutoModelSelect2TagField

This is a very strange one.

I have this field in one of my edition forms:

class SetTagWidget(AutoHeavySelect2TagWidget):
    def init_options(self):
        super(SetTagWidget, self).init_options()
        self.options['minimumInputLength'] = 2
        self.options['tokenSeparators'] = [",",]


class SetTagField(AutoModelSelect2TagField):
    widget = SetTagWidget    
    queryset = Tag.objects
    search_fields = ['name__icontains']

    def security_check(self, request, *args, **kwargs):        
        return True    

    def create_new_value(self, value):
       tag = Tag()
       tag.name = value[:100]
       tag.save()
       return tag.id

Tag is from django-taggit package, but I think that this is not relevant. I'm using latest django-select2 from github.

This works ok on Google Chrome and Mozilla Firefox. But when I use Internet Explorer 9,10 or 11, I can add more than one value to the field, but it only saves the first value.

Do you have any clue? Could it be a javascript problem?

Thank you very much, regards,

Performance

Hello,

While updating from 2.0.1 to 3.1.2 version (or any of the 3.0 versions), I loose a lot of performance, JUST when I first reach a page of my website after restarting the server (on production), or using python manage.py runserver.

For the moment I didn't investigate much, but is there an initialisation process in django_select2 app done a "first loading" ? And which has changed between 3.0 versions and 2.0.1 version ?

Regards,

AutoModelSelect2MultipleField doesn't remove values.

I extend AutoModelSelect2MultipleField:

class CategoriesField(AutoModelSelect2MultipleField):

    search_fields = ('name__icontains',)

    def __init__(self, *args, **kwargs):
        kwargs['queryset'] = Category.objects.all()
        super(CategoriesField, self).__init__(*args, **kwargs)

Scenario:

  1. Add categories to the empty field (ajax works).
  2. Save the form. I am posting:
    • categories 61
    • categories 60
    • categories 66
  3. Categories was saved:

saved
4. Remove two items:

remove
5. Save the form. And again I am posting:

  • categories 66
  • categories 60
  • categories 61.
    Why? It should be only categories 66.
  1. Items after save:

saved2

It looks like js script doesn't remove values only add them.

ModelResultJsonMixin doesn't have a get_queryset method

It could be nice to add a get_queryset method to ModelResultJsonMixin to be able to not create the queryset at application startup (filtering on current_site for instance)

For now I will have to duplicate the get_result method just to be able to generate the queryset.

Will try to do a PR.

'appname.django_select2_keymap' doesn't exist

I used Select2Widget and HeavySelect2MultipleWidget in my admin view and it works well. However, when I use dumpdata command to backup my database, which used to work, it complains that newdc.django_select2_keymap(newdc is the name of my application) doesn't exist

$ python manage.py dumpdata > ../backup/11-26.dump
CommandError: Unable to serialize database: (1146, "Table 'newdc.django_select2_keymap' doesn't exist")

And the version I'm using is 4.2.2

>>> django_select2.__version__
'4.2.2'

django-select2 whit django-cities loops.

Hi

Can't get django-select2 play nice whit django-cities any one have a suggestion?

The problem is that on validation of a submitted from django-select2 loops the entier db off django-cities (22K+ rows) it takes a long time.

form.py

class CityClass(AutoModelSelect2Field):
    queryset=City.objects
    search_fields  = ['name__icontains', 'slug__icontains', 'name_std__icontains', ]

class UserForm(forms.Form):
    BIRTH_YEAR_CHOICES = range((date.today().year - 90), (date.today().year - 15))
    error_messages = {
        'duplicate_pagename': _("A page with that name already exists."),
        'duplicate_email':    _("A user with that email already exists."),
        'sixteen_or_older':    _("You have to be sixteen or older to join"),
    }
    email               = forms.EmailField(label=_('E-mail'),
                                        help_text = _("Required"))
    dob                 = forms.DateField(label=_('Date of birth'),                                       widget=extras.SelectDateWidget(years=BIRTH_YEAR_CHOICES),
                                        help_text = _("Required. Your date of birth"))
    city                = CityClass()

views.py

def newUser(request):
    if request.method == 'POST':
            form = UserForm(request.POST)
            if form.is_valid():
                messages.info(request,  form.cleaned_data)

Duplicate selected choices

Duplicate selected choices cause weirdness. In HeavySelect2Mixin render_texts if in selected_choices multiple equal values are passed in then txts will be a different length than selected_choices since selected_choices gets filtered. In the HTML, this causes

  • 's to have the text 'undefined' in the
      for the widget.

  • Documentation - some clarifying questions

    Hi there,

    I've been trying for most of the morning to work through this and get a basic ajax autocomplete select lookup functioning. For reference I've been using your documentation on your blog (http://blog.applegrew.com/2012/08/django-select2/) and the testapp application.

    FWIW - I've been using https://github.com/crucialfelix/django-ajax-selects and I'm pretty familiar with both django and ajax. Your implementation looks visually much better I'm struggling to just get the basic workflow down. My relevant code is listed below.

    Specific issues:

    1. Do I need to create a view for each of my ajax lookups? The blog it implies that I need to, but it makes no mention of a corresponding url to go with it. I'm assuming I need one so created one. My confusion is around the url(r"^select2/", include("django_select2.urls")), paragraph and what exactly it does?
    2. Once the view is created it's unclear how I tie this view to the form? I made the assumption based on the testapp that I need to use the HeavySelect2ChoiceField with a data_view as an argument. Is this correct?
    class CommunityForm(ModelForm):
        city = HeavySelect2ChoiceField(data_view='city:my_city_select')
    1.  How do I apply the basic allowClear: true to this example?  This doesn't work?
    class CommunityForm(ModelForm):
        city = HeavySelect2ChoiceField(widget=HeavySelect2Widget(
                data_view='city:my_city_select',
                select2_options={
                    'allowClear': True,
                    'placeholder': u"Enter City"
                }))

    Overall this appears to work - my question are as follows:

    1. Is this implementation how you currently would like this to be done? I say this b/c it looks like the test app and the blog differ in the process?
    2. Are there ways to optimize my implementation? Clearly if you aren't using a customized queryset you can use your AutoModelSelect2Field but this has some drawbacks as you still need to implement security_check and get_results unless you want them all?
    3. Why did you choose not to use the standard get_queryset as a method to feeding get results and using (object.id, object.unicode()) followed by filtering object.unicode for the term?

    Reference

    Note: I used our own AuthenticationMixin which trumps your implementation in dispatch

    # views.py
    class MyCitySelectView(AuthenticationMixin, Select2View):
        """Used by django-selects2"""
        permission_required = "geographic.view_city"
    
        def get_results(self, request, term, page, context):
            """Basic city list"""
            cities = City.objects.filter_by_user(user=self.request.user)
            cities = cities.filter(Q(name__icontains=term) |
                                   Q(county__name__icontains=term) |
                                   Q(county__state__icontains=term))
            results = [(city.id, city.__unicode__()) for city in cities]
            return NO_ERR_RESP, False, results
    
    # urls.py - Simplified for brevity..
        url(r'^city/', include(patterns('',
            url(r'^ajax/$', MyCitySelectView.as_view(), name="my_city_select"),
        ), namespace="city")),
    
    # forms.py
    class CommunityForm(ModelForm):
        #city = AutoCompleteSelectField('city_co_restricted', help_text=None, required=True)
        city = HeavySelect2ChoiceField(data_view='city:my_city_select')

    AutoModelSelect2Field initial value

    Hello,

    Your app looks great. (For the moment I made a minor change on my fork for unicode problem, I will ask you for pull request for that).

    I tried to use the AutoModelSelect2Field on a model form, sub-classed it to feat my needs (EquipmentReferenceSelect2Field in my case) and override get_results . Now I can search and select a value for my field.

    The problem is that when I save my form, and reload the page, the value of my field is not displayed in the select2 widget.

    1. to keep the data in the hidden input I have to comment L87 in heavy_data.js
    2. I don't find the good way to 'launch' an ajax call when the form is rendered to fill the select2 widget with the current value

    Is my question enought clear for you, or do you need more details to answer it ?

    Regards

    Assumes the values and choices are in the same order

    I noticed the issue when I tried to delete a selected option. The option I thought I deleted still appeared after I successfully submitted the form. This seems to only happen when I have a lot of selected options (I have ~180 options selected and ~5k choices loaded via ajax).

    The issue occurred because data in heavy_data.js wasn't correct. The ids didn't correctly match the txts.

    I think this is because in heavy_data.js it's assumed that you can zip up txts and vals and this will yield the correct data objects (lines 46-48):

    $(vals).each(function (index) {
        data.push({id: this, text: txts[index]});
    });
    

    But when these values are created in widgets.py vals and texts are not created with the same order. Vals is in it's instantiated order but texts is in the order that the matching val appears in choices.

    In the render_texts method I think these lines:

    for val, txt in chain(self.choices, all_choices):
        val = force_unicode(val)
        if val in selected_choices:
            selected_choices = [v for v in selected_choices if v != val]
            txts.append(txt)
    

    should be changed to something like:

    choices_dict = dict(chain(self.choices, all_choices))
    for val in selected_choices:
        try:
            txts.append(choices_dict[val])
        except KeyError:
            raise KeyError("Value %s not in choices" % val)
    

    Heavy widgets iterate over the whole database table

    When there's an initial value (e.g. in an admin edit page), HeavySelect2Mixin.render_texts gets called which causes the whole dataset to be iterated. This basically makes this nifty library useless when dealing with big tables.

    In this line self.choices is a lazy representation of all possible choices, and accessing it triggers a SQL query without LIMIT.
    https://github.com/applegrew/django-select2/blob/master/django_select2/widgets.py#L414

    I tried to take a stab at it but no luck, not sure where to start fixing this issue.
    Any pointers? Thanks!

    No multi-process support

    It seems that django-select2 is dependent on two global dictionaries for the autoselect fields. The following are in django_select2/util.py

    # Generated Id to field instance mapping.
    __id_store = {}
    # Field's key to generated Id mapping.
    __field_store = {}

    Obviously this is going to fail when you run multi-process. Not sure what would be involved in getting multi-process support, and whether these details could be written back into SQL. That may be a feature request, although breaking multi-process support is certainly a huge issue.

    At the very least this should be highlighted on the front page of the manual, so people are aware of the limitation before bringing this library in.

    Add extra parameters to Select2View dinamically when calling it from ajax

    I have a case where I would like a second select to get the results through ajax (HeavySelect2Widget). I want the view to also receive an ID and consequently construct the queryset according. It is the classic "select the country", and then the second select searches on cities from the selected country.

    Is there an easy way to do this? I guess the way to accomplish this is adding another GET param (along with the 'term' or 'page') while calling auto.json (or a custom Select2View) but I didn't find an easy solution... Or maybe I am missing something?

    Thanks!

    H.

    ModelResultJsonMixin doesn't have a get_queryset method

    It could be nice to add a get_queryset method to ModelResultJsonMixin to be able to not create the queryset at application startup (filtering on current_site for instance)

    For now I will have to duplicate the get_result method just to be able to generate the queryset.

    Will try to do a PR.

    <script>...</script> on Chrome and FF

    I have problem with django_select2.util.render_js_script. It's generate block like:

            <script>
                $(function () {
                    // inner_code here
                });
            </script>

    but it doesn't work on FF and Chrome (on Linux). But when I change it to:

            <script type="text/javascript">
                $(function () {
                    // inner_code here
                });
            </script>

    everything is working properly.

    problem with inline select2

    Hi,
    when i click on "add new" to inline, there is select2 field, but i can't choose anything, no options in it:

    class UnosOperacijeForm(forms.ModelForm):
    
        class Meta:
            model = ModelOperacija
            widgets = {
                'operacija': Select2Widget(attrs={'style': 'width:120px'}),
            }
    
    class ModelOperacijaInline(admin.TabularInline):
        model = ModelOperacija
        extra = 0
        form = UnosOperacijeForm
    
    class ModelOperacijaAdmin(TranslationAdvModelAdmin):
        inlines = [ModelOperacijaInline]

    Any solution?

    Tagging Support?

    Hi,
    I'm trying to implement a field that let the user select or create a new tag.

    Something like :
    http://ivaynberg.github.com/select2/#tags

    In this case I must go through Heavy component and especially HeavySelect2MultipleWidget in order to have an input field in place of a select, otherwise, when 'tags' is added to js options it complains about requiring an input field.

    I try with something like that :

    class TrademarksTagsSelect2MultipleWidget(AutoHeavySelect2Mixin, HeavySelect2MultipleWidget):
        def init_options(self):
             super(TrademarksTagsSelect2MultipleWidget, self).init_options()
            self.options['closeOnSelect'] = 'true'
            self.options['tags'] = '[]' #-- Giving it an array with value changes nothing here...
            self.options['tokenSeparators'] = '[",", " "]' 
    
    class TrademarkTagsField(AutoModelSelect2MultipleField):
         search_fields = ['name__icontains', ]
         queryset = Sale.trademarks_tags
         widget = TrademarksTagsSelect2MultipleWidget
    

    in forms.py

    trademarks_tags = TrademarkTagsField()
    

    The problem is that I can't create a new tag. Autosuggest works, select works but I don't find any way to create a new tag.

    The generated javascript is :

        <script type="text/javascript">
            $(function () {
                $('#id_trademarks_tags').data('field_id', '0:2013-03-19 10:29:16.414892');$('#id_trademarks_tags').change(django_select2.onValChange).data('userGetValText', null);$("#id_trademarks_tags").select2({'tokenSeparators': '[",", " "]', 'initSelection': django_select2.onInit, 'multiple': true, 'minimumInputLength': 2, 'tags': '[]', 'closeOnSelect': 'true', 'ajax': {'dataType': 'json', 'quietMillis': 100, 'url': '/select2/fields/auto.json', 'data': django_select2.runInContextHelper(django_select2.get_url_params, 'id_trademarks_tags'), 'results': django_select2.runInContextHelper(django_select2.process_results, 'id_trademarks_tags')}, 'separator': django_select2.MULTISEPARATOR});
            });
        </script>
    
    

    Questions here are :
    Do I miss something ?
    Does anyone here has already success in such implementation ?
    If not do you have any hints on how to accomplish that ? Does it requires a new specific widget to be written to support tagging feature ?

    Thanks in advance

    Default CSRF validation with django

    In heavy_data.js your overriding the cookie which is used for CSRF in django forms.

    Form submission fails with:
    Forbidden (403)
    CSRF verification failed. Request aborted.

    Reason given for failure:
    CSRF cookie not set.

    Escape html Markup

    Hi there,

    It's not an issue, just a problem I solved and wanted to share with you.

    It's been a long time, and I need to update the django-select2 version I use on some projects.

    I get a problem having html markup in the text key provided via get_results on Select2Field instances.
    It's basically because Select2.js now has a function to escape html markup, named escapeMarkup that you can use as follow for an AutoHeavySelect2Widget (same trick for other fields)

    class EscapeMarkupAutoHeavySelect2Widget(AutoHeavySelect2Widget):
    
        def init_options(self):
            self.options['escapeMarkup'] = JSFunction('function (text) { return text; }')
    

    Next, in the form, you must use this widget with your Select2Field as follow

    class FooForm(forms.Form):
       field_select2 = FooSelect2Field(widget=EscapeMarkupAutoHeavySelect2Widget)
    
    

    Well, to discuss that, it occurs to me that it's a lot to do, to just add 'escapeMarkup':function (text) { return text; }to the javascript select2 instanciation. We could use template to do that. I remember a long time ago when you first release django-select2, that I thought about using django-floppyforms to deal with the template part, and I think it could be great. May be I'll try to test the idea.

    Thanks,

    MultipleSelect2HiddenInput returns bad has_changed value

    MultipleSelect2HiddenInput extends forms.TextInput that widget gets his _has_changed from Widget class: https://github.com/django/django/blob/stable/1.5.x/django/forms/widgets.py#L211.

    That function is not good for many value widgets because for initial values: None, [] it returns True...

    You have to use _has_changed from: https://github.com/django/django/blob/stable/1.5.x/django/forms/widgets.py#L642.

    This problem occurred when I try use that field in formset. Formset validates only changed forms, so now it will validate all forms in formset even extra ones.

    Options given at select2_options are not used

    As exposed in MixedForm test in django-select2 source code, options given to select2_options are not used because width is not an option known of django-select2 and because select2 expects placeholder not placeHolder.

    class FooSelect2Field(django_select2.AutoModelSelect2Field):
        queryset = Foo.objects
        search_fields = ['name__icontains, ]
    
        station = StationSelect2Field(widget=django_select2.AutoHeavySelect2Widget(select2_options={
            'width': '32em',
            'placeholder': _(u"Search foo")
        })

    Add select2 constructor parameters

    I need to add

    createSearchChoice: function(term, data) {
        if ($(data).filter(function() {return this.text.localeCompare(term)===0; }).length===0) {
            return {id:term, text:term};
        }
    }
    

    So that I can add stuff, not only select the already existing. Also, I haven't been able to add an initial value to django-select2 form fields.

    Are this two things supposed to work but I'm not getting, are bugs or are they not possible?

    AutoModelSelect2Field question

    Hello,

    I try to subclass AutoModelSelect2Field for my needs.
    If I subclass it one time, no problem, I get what I wan't. The problem comes when I subclass it 2 times.

    I have now EquipmentSelect2Field and WorkSelect2Field extending AutoModelSelect2Field, and a FirstForm using EquipmentSelect2Field and a SecondForm using WorkSelect2Field. When I render the SecondForm, it returns ajax request for EquipmentSelect2Field and not WorkSelect2Field. The thing is that it depends on 'where' the form is located on my forms.py . It always kept the last instance to get ajax results (in my case I have FirstForm ending the forms.py file).

    My question, how do you pass your 'model' var in select2/fields/auto.json view ?

    Thx

    installation error

    Hello,

    I have a requirements.txt file to install python related packages, and inside I have got your (great) app.
    But, when I run pip install -r requirements.txt, I get :

    File "/srv/brahms/.virtualenvs/test/build/Django-Select2/setup.py", line 111, in <module>
    
        VERSION = __import__(PACKAGE).__version__
    
      File "django_select2/__init__.py", line 3, in <module>
    
        from django.conf import settings
    
    ImportError: No module named django.conf
    

    which is "normal" because, due to the way pip works, django is not allready installed.

    one way to solve this issue would be to have a dedicated version.py file inside your module.

    Regards,

    search_fields are required whereas get_results is overidden

    When I provide my own get_results method to my field, the search_fields arguments still required.

    A test could be added to know if get_results has been overridden and in this case, search_results will be ignored.

    PS: I think prepare_qs_params called by default get_results is the only function to use search_fields attribute.

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google ❤️ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.