Search code examples
djangoautocompletedjango-autocomplete-light

Autocomplete in django and allow creating user if not found


I'm trying to add a search box for users on the webpage to see his profile, and if the user doesn't exist, then I have the option to create it.

In flask, I used a solution that used jquery for the autocomplete, and when no one was found, it would simply put "Create_user" as the text submitted in the form, and then redirect to the url for user creation. I was not able to port this to django(javascript is not my forté and I'm starting django.)

So I tried django-autocomplete-light, but while the autocomplete worked, I found no way to replicate the behavior that would redirect me to the user creation page in the case no one was found. (the create exemple in the docs only allow to create a simple entry, while I need to create a user based on a model)

Any leads on how to accomplish this with django?


Solution

  • That's what i was looking few days ago, i found this

    Example Admin code for autocomplete

    from django.contrib import admin
    from django.contrib.auth.admin import UserAdmin
    from django.contrib.auth.models import User
    from django import forms
    
    from selectable.forms import AutoCompleteSelectField, AutoCompleteSelectMultipleWidget
    
    from .models import Fruit, Farm
    from .lookups import FruitLookup, OwnerLookup
    
    
    class FarmAdminForm(forms.ModelForm):
        owner = AutoCompleteSelectField(lookup_class=OwnerLookup, allow_new=True)
    
        class Meta(object):
            model = Farm
            widgets = {
                'fruit': AutoCompleteSelectMultipleWidget(lookup_class=FruitLookup),
            }
            exclude = ('owner', )
    
        def __init__(self, *args, **kwargs):
            super(FarmAdminForm, self).__init__(*args, **kwargs)
            if self.instance and self.instance.pk and self.instance.owner:
                self.initial['owner'] = self.instance.owner.pk
    
        def save(self, *args, **kwargs):
            owner = self.cleaned_data['owner']
            if owner and not owner.pk:
                owner = User.objects.create_user(username=owner.username, email='')
            self.instance.owner = owner
            return super(FarmAdminForm, self).save(*args, **kwargs)
    
    
    class FarmAdmin(admin.ModelAdmin):
        form = FarmAdminForm
    
    
    admin.site.register(Farm, FarmAdmin)
    

    Source code

    https://github.com/mlavin/django-selectable

    and

    Documentation

    http://django-selectable.readthedocs.org/en/latest/

    Hope this will help you too