Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Widgets not showing up in and out of Admin panel #699

Closed
mihaelfi opened this issue Jun 20, 2016 · 22 comments
Closed

Widgets not showing up in and out of Admin panel #699

mihaelfi opened this issue Jun 20, 2016 · 22 comments

Comments

@mihaelfi
Copy link

I've just installed Django-Autocomplete-Light and followed the guide on their site. I've setup the autocomplete-view and it works as intended (returning a JASON of autocomplete options). I can't seem to get the widgets to show up, though. in and out of the admin panel.

Everything compiles without errors but instead the widget I get an empty drop down selection box.

Image of empty selection box in admin panel

This is my settings.py:

INSTALLED_APPS = [
    'dal',
    'dal_select2',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'selectable',
    'videos.apps.VideosConfig',
]

This is views.py:

class ActorAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        # Don't forget to filter out results depending on the visitor !

        qs = Actor.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

urls.py:

url(r'^actor-autocomplete/$', views.ActorAutocomplete.as_view(), name='actor-autocomplete'),
forms.py:

class ActorForm(forms.ModelForm):
    class Meta:
        model = Actor
        fields = ('name',)
        widgets = {
            'name': autocomplete.Select(url='videos/actor-autocomplete')
        }

It feels like I'm missing something simple, but I don't know what it is. Perhaps it can't access the static files, but adding 'dal' to installed_app in settings.py should have solved that according to the documentation. I'll appreciate any help!

I forgot to mention that Actor.name is of type CharField. Perhaps I'm not using the correct widget, but I haven't found one that is specific for CharField.

@jpic
Copy link
Member

jpic commented Jun 20, 2016

Did you install from pypi or git ? If fit, jave you synced submodules?
On Jun 20, 2016 7:51 AM, "mihaelfi" notifications@github.com wrote:

I've just installed Django-Autocomplete-Light and followed the guide on
their site. I've setup the autocomplete-view and it works as intended
(returning a JASON of autocomplete options). I can't seem to get the
widgets to show up, though. in and out of the admin panel.

Everything compiles without errors but instead the widget I get an empty
drop down selection box.

Image of empty selection box in admin panel
http://i.imgur.com/RlNDgET.jpg

This is my settings.py:

INSTALLED_APPS = [
'dal',
'dal_select2',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'selectable',
'videos.apps.VideosConfig',
]

This is views.py:

class ActorAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !

    qs = Actor.objects.all()

    if self.q:
        qs = qs.filter(name__istartswith=self.q)

    return qs

urls.py:

url(r'^actor-autocomplete/$', views.ActorAutocomplete.as_view(),
name='actor-autocomplete'),
forms.py:

class ActorForm(forms.ModelForm):
class Meta:
model = Actor
fields = ('name',)
widgets = {
'name': autocomplete.Select(url='videos/actor-autocomplete')
}

It feels like I'm missing something simple, but I don't know what it is.
Perhaps it can't access the static files, but adding 'dal' to installed_app
in settings.py should have solved that according to the documentation. I'll
appreciate any help!

I forgot to mention that Actor.name is of type CharField. Perhaps I'm not
using the correct widget, but I haven't found one that is specific for
CharField.


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
#699, or mute
the thread
https://github.com/notifications/unsubscribe/AAFxrGxlth-Vi1wEky4STNlGVlm_-kDOks5qNipwgaJpZM4I5YRZ
.

@mihaelfi
Copy link
Author

Installed using pypi:
pip install django-autocomplete-light

@jpic
Copy link
Member

jpic commented Jun 20, 2016 via email

@mihaelfi
Copy link
Author

That's the thing. I don't know. (Though I don't think so because the widgets don't load properly) How do I check if they are properly loaded ?

@jpic
Copy link
Member

jpic commented Jun 20, 2016 via email

@mihaelfi
Copy link
Author

This is what I get in the network tab
I'm not sure what static files exactly should be loaded.

@jpic
Copy link
Member

jpic commented Jun 20, 2016 via email

@mihaelfi
Copy link
Author

Actor Form:

class ActorForm(forms.ModelForm):
    class Meta:
        model = Actor
        fields = ('name',)
        widgets = {
            'name': autocomplete.Select(url='videos/actor-autocomplete')
        }

Admin:

from .models import  Actor, ActorTag
from .forms import ActorForm


class ActorAdmin(admin.ModelAdmin):
    form = ActorForm


admin.site.register(Actor, ActorAdmin)

The actor itself does not have a Form the Form is autogenerated by a Createview:

class ActorAdd(CreateView):
    model = Actor
    fields = ['name', 'date_of_birth', 'thumbnail', 'gender','biography']


def actors_add(request):
    return render(request, 'videos/actors-add.html')

@jpic
Copy link
Member

jpic commented Jun 20, 2016 via email

@mihaelfi
Copy link
Author

Because it didn't show up in PyCharm's IntelliSense. I tried every widget that was there to no avail. When I try to force autocomplete.Select2 this is what I get:

Unhandled exception in thread started by <function wrapper at 0x037689F0>
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(args, *kwargs)
File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(exception)
File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(args, **kwargs)
File "C:\Python27\lib\site-packages\django__init
.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Python27\lib\site-packages\django\apps\registry.py", line 115, in populate
app_config.ready()
File "C:\Python27\lib\site-packages\django\contrib\admin\apps.py", line 22, in ready
self.module.autodiscover()
File "C:\Python27\lib\site-packages\django\contrib\admin__init
.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "C:\Python27\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "C:\Python27\lib\importlib__init
_.py", line 37, in import_module
import(name)
File "E:\djangoProject\YAPO\videos\admin.py", line 3, in
from .forms import ActorForm
File "E:\djangoProject\YAPO\videos\forms.py", line 7, in
class ActorForm(forms.ModelForm):
File "E:\djangoProject\YAPO\videos\forms.py", line 8, in ActorForm
class Meta:
File "E:\djangoProject\YAPO\videos\forms.py", line 12, in Meta
'name': autocomplete.Select2(url='videos/actor-autocomplete')
AttributeError: 'module' object has no attribute 'Select2'

@jpic
Copy link
Member

jpic commented Jun 20, 2016 via email

@mihaelfi
Copy link
Author

I followed the tutorial that is why my code is almost completely identical to the tutorial.

ModelSelect2 is what I tried at first (Because it's in the tutorial)
But I got

Exception Value:    
'list' object has no attribute 'queryset'

(I tried it again now and got the same exception)
Because Actor.name is a charfield and (as far as I understand) ModelSelect2 is for Foreign key fields.

I tried it with ModelSelect2Multiple with Actor.Scenes which is a M2M field. The same result. An empty widget but this time it's just an empty M2M widget from the admin view.

class ActorForm(forms.ModelForm):
    class Meta:
        model = Actor
        fields = ('scenes',)
        widgets = {
            'scenes': autocomplete.ModelSelect2Multiple(url='videos/actor-autocomplete')
        }

autocomplete.Select is the only widget that didn't cause an exception with a charfield but like I said it's just empty, and from what you said the static files don't load correctly :(

@jpic
Copy link
Member

jpic commented Jun 20, 2016

Well, i didn't know you wouldn't use a relation here, because I don't know your models code.

I really don't get the big picture of what you're trying to do.

Could you perhaps isolate the use case in test_project ?

@mihaelfi
Copy link
Author

Tomorrow I'll try to make a new up from scratch and use the exact code that is in the tutorial.

Though I don't know if it will help, it seems the problem here is that the static files are not loading, no?
My Model is this:

class Actor(models.Model):
    MALE = 'M'
    FEMALE = 'F'


    GENDER_CHOICES = (
        (MALE, 'Male'),
        (FEMALE, 'Female'),
    )

    name = models.CharField(max_length=50, unique=True)
    date_added = models.DateTimeField(auto_now_add=True)
    date_of_birth = models.DateField(null=True, blank=True)
    play_count = models.IntegerField(default=0)
    rating = models.IntegerField(default=0)
    description = models.TextField(default="", blank=True)
    thumbnail = models.CharField(max_length=500, null=True, blank=True)
    gender = models.CharField(max_length=15, choices=GENDER_CHOICES)
    scenes = models.ManyToManyField(Scene, null=True, blank=True)
    imdb_id = models.CharField(max_length=25, null=True, blank=True)
    tmdb_id = models.CharField(max_length=25, null=True, blank=True)
    official_pages = models.TextField(default="", blank=True)

What I'm trying to do is to make a local netflix-like library, and specifically with the autocomplete I want it to help the user add actors to a movie or a tv-show based on already existing actors. But right now I'm just trying to make the autocomplete work with something so I tried all the combinations of fields and wigets I can think of. Sadly it didn't help.

@jpic
Copy link
Member

jpic commented Jun 20, 2016

IT's not loading because it's the vanilla select widget.

ModelSelect2Multiple sounds like the way to go, perhaps checking this example would help ?

I don't think that's right: url='videos/actor-autocomplete'

Can't you use either an absolute url either a url name (prefered) ?

When using autocomplete.ModelSelect2Multiple (whic his the right one in your case), could you check the network tab of the webkit inspector and see if select2's js is properly loaded ?

Thanks !

@mihaelfi
Copy link
Author

I don't think that's right: url='videos/actor-autocomplete'

Can't you use either an absolute url either a url name (prefered) ?

That is a url name. It's just in the 'videos' namespace.

Anyway, I started a new project from scratch and used only code from the tutorial. The same exact results. I wrote all the code here and took screenshots to show you and then I thought I try loading the site on FireFox instead of Chrome, and it F****** works!

Any idea why would it work on Firefox and not Chrome ? I disabled all the adblock plugins this didn't affect anything ...

@jpic
Copy link
Member

jpic commented Jun 21, 2016 via email

@mihaelfi
Copy link
Author

mihaelfi commented Jun 21, 2016

autocomplete.zip
Here is the project source, but like I said it's basically copy paste of the tutorial.

Here it works on chrome:
http://dal-yourlabs.rhcloud.com/select2_outside_admin/

Yes... All the live examples work on my chrome as well that is why I never thought the browser is the problem.

Edit: Ok so Chrome is not the problem. I tested it with a new user in Chrome and it works on the new user profile.

@jpic
Copy link
Member

jpic commented Jun 23, 2016

Here is the project source, but like I said it's basically copy paste of the tutorial.

Awesome, it even worked out of the box for me on chromium and firefox !

Did you consider uploading this on a git repo ?

Edit: Ok so Chrome is not the problem. I tested it with a new user in Chrome and it works on the new user profile.

Same here 🎸

2016-06-24-015033_549x405_scrot
:gui
2016-06-24-014953_645x573_scrot

Should this issue be closed now ? Does it work on your project too ?

Anyway, nice research and communication, welcome home 👯

@jpic
Copy link
Member

jpic commented Jun 24, 2016

I'm going to close it to prevent contributors from re-reading it before you're able to provide feedback, please reopen when you feel like it 🎸

@jpic jpic closed this as completed Jun 24, 2016
@mihaelfi
Copy link
Author

Thanks for your help!
I disabled all of the chrome plugins and now it works in my user as well.
I didn't manage to figure out which plugin exactly caused the problem...

@gvizquel
Copy link

Hello jpic it's a pleasure to say hello. I have been using django-autocomplete-light for a couple of years, it is an excellent implementation of the Select2 library for Dango that I have always recommended. Now I'm using django-autocomplete-light 3.3.2 in a new project with Django 2, Python 3.6 and it just does not work. The view and the url work perfectly, but when rendering the form both in the admin and outside the admin the tag does not work. This is what I have:

settings.py:

INSTALLED_APPS = [
    # ====================================================================== #
    "dal",
    "dal_select2",
    # ====================================================================== #
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # ====================================================================== #
    "prueba",
]

models.py:

class DivisionPoliticoTerritorial(models.Model):
    """Modelo que sirve para gestionar las dicisiones político  territoriales
    de los paises del mundo.
    """
    division = models.CharField(max_length=255, blank=True, null=True)
    nombre = models.CharField(max_length=255, blank=True, null=True)
    division_padre = models.ForeignKey("self", on_delete=models.PROTECT, blank=True, null=True)
    arbol = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.nombre

    class Meta:
        verbose_name = "División político territorial"
        verbose_name_plural = "División político territorial"
        db_table = "globales_division_politico_territorial"

# ========================================================================== #
class Finca(models.Model):
    """Modelo administrativo: Sirve para el registro de las fincas que
    contratan con FincaSoft
    """
    razon_social = models.CharField("Razon Social", max_length=255)
    rif = models.CharField("R.I.F.", max_length=12, unique=True)
    dpt = models.ForeignKey("DivisionPoliticoTerritorial", on_delete=models.PROTECT)

    def __str__(self):
        return "%s %s" % (self.razon_social, self.rif)

    class Meta:
        ordering = ["razon_social"]
        verbose_name = "Finca"
        verbose_name_plural = "Fincas"

views.py

# ========================================================================== #
class AgregarFinca(SuccessMessageMixin, CreateView):
    """Esta clase sirve para agregar las de los fincas de los propietarios
    """

    model = Finca
    form_class = FincaForm
    template_name = 'formulario.html'
    success_message = '¡La finca se agregó de manera exitosa!'

    def get_context_data(self, **kwargs):
        contexto = super(AgregarFinca, self).get_context_data(**kwargs)
        contexto['agregar'] = True

        return contexto

    def form_valid(self, form):
        with transaction.atomic():
            finca = form.save()

        return super().form_valid(form)


# ========================================================================== #
class EstadoAutoComplete(autocomplete.Select2QuerySetView):
    """Servicio de auto completado para el modelo Personas
    """

    def get_queryset(self):
        queryset = DivisionPoliticoTerritorial.objects.filter(arbol='243').order_by('nombre')

        if self.q:
            queryset = queryset.filter(nombre__icontains=self.q)

urls.py

app_name = 'prueba'

urlpatterns = [
     path(
        'agregar',
        AgregarFinca.as_view(),
        name='agregar'),
    # ===================================================================== #
    # Rutas de Auto Completado de la División Político Territorial Personas #
    # ===================================================================== #
    path('estado/', EstadoAutoComplete.as_view(), name='estado'),
]

forms.py

# ========================================================================== #
class FincaForm(ModelForm):
    '''Clase para la gestión del formulario de fincas
    '''

    class Meta:
        model = Finca
        fields = ('__all__')

        widgets = {
            'razon_social': TextInput(attrs={'class': 'form-control'}),
            'rif': TextInput(attrs={'class': 'form-control'}),
            'dpt': autocomplete.ModelSelect2(
                url='prueba:estado',
                attrs={
                    'class': 'form-control select2',
                    'data-placeholder': 'bla bla bla ...',
                },
            ),
        }

formulario.html

{% load i18n static %}
<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- Tell the browser to be responsive to screen width -->
        <link rel="stylesheet" type="text/css" href="/static/admin/css/base.css">
<link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css">

<script type="text/javascript" src="/admin/jsi18n/"></script>
<link href="/static/admin/css/vendor/select2/select2.css" type="text/css" media="screen" rel="stylesheet">
<link href="/static/admin/css/autocomplete.css" type="text/css" media="screen" rel="stylesheet">
<link href="/static/autocomplete_light/select2.css" type="text/css" media="screen" rel="stylesheet">
<script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.js"></script>
<script type="text/javascript" src="/static/admin/js/urlify.js"></script>
<script type="text/javascript" src="/static/admin/js/prepopulate.js"></script>
<script type="text/javascript" src="/static/admin/js/vendor/xregexp/xregexp.js"></script>
<script type="text/javascript" src="/static/autocomplete_light/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/vendor/select2/select2.full.js"></script>
<script type="text/javascript" src="/static/autocomplete_light/autocomplete.init.js"></script>
<script type="text/javascript" src="/static/autocomplete_light/forward.js"></script>
<script type="text/javascript" src="/static/autocomplete_light/select2.js"></script>
<script type="text/javascript" src="/static/autocomplete_light/jquery.post-setup.js"></script>

    <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <link rel="stylesheet" type="text/css" href="/static/admin/css/responsive.css">
</head>
    <body>
    <form role="form" action="" method="post">
    {{ form }}
    </form>
    </body>
    <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>
</html>

Thanks for your time

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants