applegrew / django-select2

This is a Django integration for Select2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Only one possible selection in city contextual dropdown in Admin

pmeleney opened this issue · comments

First of all, thank you so much for maintaining, this is a repo
Goal
Show city contextual dropdown with "enter first two characters" search field in admin window

Problem
My admin location_city selector shows only one possibility, the currently selected city. I would like the ability to change a profile's location from the admin.

Code Snippet
Please provide a code snippet of your problem.
accounts.admin.py

class ProfileAdminForm(ProfileCreationForm, ModelSelect2Widget):
    location_region = forms.ModelChoiceField(queryset=USRegion.objects.all().order_by('name'), label="US Region", required=False), widget=ModelSelect2Widget(model=USRegion, search_fields=['name__istartswith'])
    location_city = forms.ModelChoiceField(queryset=USCity.objects.all().order_by('name'), label="US City", required=False, widget=ModelSelect2Widget(model=USCity, dependent_fields={'location_region':'region_id'}, search_fields=['name__icontains'], max_results=100))


class ProfileAdmin(UserAdmin):
    model = get_user_model()
    add_form = ProfileAdminForm
    form = ProfileAdminForm
    list_display = ['username', 'email', "is_active", "is_staff", "is_superuser"]

    fieldsets = (
        (None, {'fields': ('username',)}),
        ( ('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'phone_number', 'bio', 'location_region', 'location_city')}),
        ( ('Permissions'), {
            'fields': ('is_public', 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        ( ('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )

City contextual dropdown shows only Seattle in its list:
github_city_dropdown_admin

Hello again!

Let's see if we can't solve this too. I might need some more information though. Can you try to replace the dependent_fields attribute with {'location_region':'region', so that the lookup no longer includes the _id.

If that doesn't do the trick, can you please provide me with the USRegion and USCity model?
As a little side note, I would recommend to checkout django-cities and django-cities-light.

Best
-Joe

BTW, I've just been to Washington and Seattle. Beautiful state!

removing _id and changing the order of the forms doesn't seem to have done the trick.

class USRegion(models.Model):
    name = models.CharField(max_length=255, unique=True)
    region_code = models.CharField(max_length=30, unique=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Region"
        verbose_name_plural = "Regions"


class USCity(models.Model):
    name = models.CharField(max_length=255)
    lat = models.FloatField(default=0.0)
    long = models.FloatField(default=0.0)
    region = models.ForeignKey(USRegion, to_field='id', on_delete=models.CASCADE, related_name='city_region_id')
    population = models.PositiveIntegerField(blank=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'City'
        verbose_name_plural = "Cities"

Thanks for pointing me to django-cities and django-cities-light, might be a good alternative since I'll eventually be looking to expand to countries other than the US.

And, Seattle IS beautiful - thanks!

Hey @pmeleney can you please also check the browser console logs? Especially the network logs? What requests are being send when you click focus the inputs?

Sorry for the slow response on my end -

Oh Interesting, console log:

django_select2.js:51 Uncaught TypeError: Cannot read property 'fn' of undefined
    at django_select2.js:51
    at django_select2.js:9
    at django_select2.js:11

I hope this is what you were looking for, a .har file. I could open it using https://toolbox.googleapps.com/apps/har_analyzer/

127.0.0.1.har.zip

@pmeleney I don't have time right now look into your test project, but I appreciate you putting in so much effort. Really helps. The error you are seeing in the logs usually appears if jQuery isn't loaded. Can you make sure to inject jQuery before you form media is rendered?

I'll be back from a hike in a couple of days. I'll have a closer look into your project afterwards.

OK! We fixed the problem. JQuery wasn't loading because I forgot that the admin files weren't loading my standard base.html file, so I had to add references to jquery and select2 in the admin/base.html override file in my project, and BAM - works like a charm. Thanks for all your help and have a great hike!

OK! We fixed the problem. JQuery wasn't loading because I forgot that the admin files weren't loading my standard base.html file, so I had to add references to jquery and select2 in the admin/base.html override file in my project, and BAM - works like a charm. Thanks for all your help and have a great hike!

Hi pmeleney !!

If I tried to add the references in the admin/base.html override file, It doesn't produce any impact

Note: I'm using https://github.com/wuyue92tree/django-adminlte-ui/tree/1.4.0 package too

Can you share me the code !! I am too facing the same issue

Hi iamadhihere, Unfortunately I cannot share the code base with you, but I can tell you that I solved the problem by adding the lines:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>

to my templates/admin/base.html file. I would suggest adding these lines (or their modern equivalents) to either the adminlteui/templates/admin/base.html or the adminlteui/templates/admin/base_site.html file.