Django-autocomplete-light: Not showing create new button

Created on 18 Nov 2018  路  7Comments  路  Source: yourlabs/django-autocomplete-light

Hello. I am using Django 2.1 and when I set create_field it now showing the create item .

class Skills(models.Model):
    name = models.CharField(primary_key=True,max_length=150)
    def __str__(self):
        return self.name`
class  Advertisement(models.Model):
skills = models.ManyToManyField(Skills)`
class AdsForm(forms.ModelForm):
    class Meta:
        model = models.Advertisement
        fields = ('__all__')
        widgets = {
            'skills': autocomplete.ModelSelect2Multiple(
             'main:skills'
            )
        }

urls.py

 path('skills-autocomplete',
        SkillsAutocomplete.as_view(create_field='name'),
        name='skills',
        ),

views.py

class AddAdsView(generic.CreateView):
    model=models.Advertisement
    form_class = forms.AdsForm

image

All 7 comments

Thanks for your report, can you use triple backticks to present code please

I was also having issues with the create item function. I believe I have found a solution. Hopefully it works for you:

https://stackoverflow.com/questions/53353161/django-autocomplete-light-create-new-choice/53361751#53361751

Friends, the problem for me to understand I think is that I cannot reproduce your issue with my own debugger, so you will need to paste your ajax request/response body or something to find a clue ... Maybe the problem is that the user doesn't have the add permission that get_create_option checks ?

Does it work if you add this to your view ?

def has_add_permission(self, request):
    return True

If so, perhaps you would like to contribute to the documentation about this ? It seems many users get stuck on this.

It's a permission error as @jpic said above.

However, if by a weird condition we do not know (and do not want to know) you do not add permissions and/or are not allowed to add permissions - what I've found to make it work is:

Define the field in the form class directly like this:

    sills = forms.ModelMultipleChoiceField(
        queryset=Skills.objects.all(),
        widget=autocomplete.ModelSelect2Multiple(
            url='skill-autocomplete',
            attrs={
                'data-placeholder': 'Search for skills',
                'data-autocomplete-minimum-characters': 1,
                'data-maximum-selection-length': 3,
            }
        ),
    )

Of course, use the right form field and the right autocomplete field for your problem (aka do not copy paste)

My solition is I overrided the function like this

class SkillsAutocomplete(autocomplete.Select2QuerySetView):
    def has_add_permission(self, request):
        auth = request.user.is_authenticated
        if not auth:
            return False
        return True

Thanks for sharing ! would you like to contribute your solution to
documentation ?

Was this page helpful?
0 / 5 - 0 ratings