GithubHelp home page GithubHelp logo

jazzband / django-smart-selects Goto Github PK

View Code? Open in Web Editor NEW
1.1K 51.0 348.0 309 KB

chained and grouped selects for django forms

Home Page: https://django-smart-selects.readthedocs.io/

License: BSD 3-Clause "New" or "Revised" License

Python 83.36% JavaScript 16.64%

django-smart-selects's Introduction

Django Smart Selects

Jazzband Build Status Coverage Status PyPI

This package allows you to quickly filter or group "chained" models by adding a custom foreign key or many to many field to your models. This will use an AJAX query to load only the applicable chained objects.

Works with Django version 3.2 to 5.0.

Warning: The AJAX endpoint enforces no permissions by default. This means that any model with a chained field will be world readable. If you would like more control over this permission, the django-autocomplete-light package is a great, high-quality package that enables the same functionality with permission checks.

Documentation

For more information on installation and configuration see the documentation at:

https://django-smart-selects.readthedocs.io/

Reporting issues / sending PRs

You can try the test_app example using:

python manage.py migrate
python manage.py loaddata test_app/fixtures/*
python manage.py runserver

Then login with admin/admin at http://127.0.0.1:8000/admin/

TODO

  • Add permission checks to enable users to restrict who can use the chained fields.
  • Add a ChainedCheckboxSelectMultiple widget and adjust chainedm2m.js and chainedfk.js to build checkboxes in that case

django-smart-selects's People

Contributors

acdha avatar applecat avatar blag avatar d9pouces avatar darkdeymon avatar desecho avatar digi604 avatar erozqba avatar flimm avatar gearheart avatar goinnn avatar halfnibble avatar igr-santos avatar jezdez avatar jimkutter avatar jimmykobe1171 avatar joelcrocker avatar johtso avatar jorgecorrea avatar leibowitz avatar manelclos avatar millin avatar nuwang avatar petrdlouhy avatar rantecki avatar rooterkyberian avatar salahaddin avatar sean-wallace avatar serhiyromanov avatar viniciuscainelli 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-smart-selects's Issues

i am using django-smart-selects but ChainedForeignKey fields not rendering nothing in admin or template

i have three application in django
Application : country
models.py

class Country(TranslatableModel):

    translations = TranslatedFields(
    country_name = models.CharField(max_length=100,verbose_name = _('Country Name')),
        )

Application : state
models.py

class State(TranslatableModel):

    translations = TranslatedFields(
    country = models.ForeignKey('country.Country'),
    state_name = models.CharField(max_length=100,verbose_name = _('State Name')),
        )

Application:city
models.py

class City(TranslatableModel):

    translations = TranslatedFields(
    state = models.ForeignKey('state.State'),
    city_name = models.CharField(max_length=100,verbose_name = _('City Name')),
        )

i have foreign key relation in product application and i want to use chain combo in product form
like if i am select "country"-> "India" so in "state" list it only display states related to india and in "city" list it only display cities related to that state only how can do that

i try like this but not get success

i am using
django == 1.7.4
django-smart-selects==1.0.9.3

in my models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
import datetime
from hvad.models import TranslatableModel, TranslatedFields, TranslationManager
import re
from django.core.urlresolvers import reverse
from smart_selects.db_fields import ChainedForeignKey
from state.models import State



class ProductManager(TranslationManager):

    def lang(self, request, language, check_language=True):
        #language = get_language_from_request(request)
        print ""
        language = request.LANGUAGE_CODE
        qs = self.get_query_set().filter(translations__language_code=language)
        print "qssss",qs
        print language
        return qs.distinct()



class Product(TranslatableModel): 
    translations = TranslatedFields(
    user = models.ForeignKey('auth.User', verbose_name=_('User'), null=True, blank=True),
    product_name = models.CharField(max_length=100,verbose_name = _('Product Name')),
    cat = models.ForeignKey('category.Category',default="1"),
    subcategory = models.ForeignKey('subcategory.Subcategory',default="1"),
    country = models.ForeignKey('country.Country',default="1"),
    state = ChainedForeignKey('state.State',chained_field="country", chained_model_field="country"),
    city = models.ForeignKey('city.City',default="1"),
    pro_image1 = models.FileField(upload_to='products/',blank=True, null=True, verbose_name = _('Product Image1')),
    pro_image2 = models.FileField(upload_to='products/',blank=True, null=True, verbose_name = _('Product Image2')),
    pro_image3 = models.FileField(upload_to='products/',blank=True, null=True, verbose_name = _('Product Image3')),
    pro_image4 = models.FileField(upload_to='products/',blank=True, null=True, verbose_name = _('Product Image4')),

    price = models.CharField(max_length=15,verbose_name = _('Price')),
    negotiable = models.BooleanField(default=False),
    des = models.TextField(verbose_name = _('Product Description')),
    dis_code = models.CharField(max_length=10,verbose_name = _('Discount Code')),
    pub_date = models.DateTimeField(auto_now_add=True, blank=True, null=True, verbose_name = _('Publish Date')),
    modified_date = models.DateTimeField(auto_now=True, blank=True, null=True, verbose_name = _('Modified Date')),
        )
    objects = ProductManager()
    def __unicode__(self,):
        return str(self.product_name)

my form.py id

class ProductForm(TranslatableModelForm):
    class Meta:
        model = Product
        fields = ('product_name','cat','subcategory','country','state','city','pro_image1','pro_image2','pro_image3','pro_image4','price','negotiable','des','dis_code')

in my template

{{ form | crispy}}

my main urls.py is

from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.conf import settings
from ajaxuploader.views import AjaxFileUploader
uploader = AjaxFileUploader()

urlpatterns = i18n_patterns('',
    url(r'^chaining/', include('smart_selects.urls')),
    url(r'^helper/ajax-upload/$', uploader, name="ajax_uploader"),
    url(r'^$', 'products.views.products_list_home', name='home'),
    url(r'^admin/', include(admin.site.urls)),
    (r'^accounts/', include('allauth.urls')),
    url(r'^ind_profiles/',include('individual_profiles.urls')),
    url(r'^bus_profiles/',include('business_profiles.urls')),
    url(r'^profiles/',include('profiles.urls')),
    url(r'^page/',include('business_page.urls')),
    url(r'^product/',include('products.urls')),
    url(r'^help/$','helpdesk.views.help',name='help'),
    url(r'^helper/ajax-upload/$', uploader, name="ajax_uploader"),
    (r'^ajax-upload/', include('ajax_upload.urls')),

)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

it render forms but can't display any value in "state" field in template and also not in admin side
pls help!!!
Thanks in Advanced!!!

Chained selection not working in admin

There is a little problem with third-level(?) models (or many times related models) in admin area with django-smart-selects plugin. I don't know what does matter :)

This my colors models

from django.db import models

class Colors(models.Model):
color_name = models.CharField(max_length=50)

def __unicode__(self):
    return self.color_name

This my Cars models

from django.db import models

class Cars(models.Model):
car_model = models.CharField(max_length=50)
car_colors = models.ManytoManyField(Colors, related_name='Car Colors')

def __unicode__(self):
    return self.car_model

O.K. Let's see my CarsData Model.

This my CarsData models

from django.db import models

class CarsData(models.Model):
car_barcode= models.CharField(max_length=50)
available_color = ChainedForeignKey(
Cars,
chained_field="car_model",
chained_model_field="car_colors",
show_all=False,
auto_choose=True
)

def __unicode__(self):
    return self.car_barcode

My admin.py looks like that:

from django.contrib import admin
from django import forms
from myapp.models import *

class CarsDataAdminForm(forms.ModelForm):

class Meta:
    model = CarsData
def __init__(self, *arg, **kwargs):
    super(CarsDataAdminForm, self).__init__(*arg, **kwargs)
    self.fields['available_color'].choices =  [(csc.id,csc.car_colors) for csc in Cars.objects.all()]

class CarsDataAdmin(admin.ModelAdmin):
form = CarsDataAdminForm

admin.site.register(CarsData,CarsDataAdmi
n)
Is there anyway to show in the ChoiceField 'just' color_name field datas? I see just car_model because i have to set it :

def unicode(self):
return self.car_model
Can you please give me an example?

Many thanks!

Can you cross more than one model boundary?

class CustomerDroplist(models.model):
    customer = models.ForeignKey(Customer)
    display = models.CharField(max_length=32)

class EmailAddressType(CustomerDroplist):  # reversion
    ....

class EmailAddress(models.Model):
    address_type = ChainedForeignKey(EmailAddressType,
                                     chained_field='address_type__customer',
                                     chained_model_field='customer',
                                     show_all=False,
                                     auto_choose=True)
    ....

Trying to use this in Admin with TabularInlines, but it appears there is no way to trigger the list of EmailAddressTypes based on the customer field of the main model that EmailAddress is linked to.

Am I just missing something?

empty_label is ignored

On ModelChoiceFields you can set an empty_label instead of the default '---------'. On smart-selects the '---------' is hardcoded and empty_label is ignored

Error running syncdb

Hi!

I have python 3.3 and django 1.6. When I'm running syncdb this error occurs;

File "C:\Python33\lib\site-packages\django_smart_selects-1.0.9-py3.3.egg\smart_selects\db_fields.py", line 19, in init
NameError: global name 'basestring' is not defined

I'm following this example:
http://nickbewley.com/development/chained-select-boxes-in-django/

In other machine, with python 2.7 and django 1.6 this runs fine.

Chained Selects is not working

Hi, I'm newbie with Django and I was looking for an example of how to implement a validation to show cities from a selected country, I found your example and it looks pretty cool and easy, unfortunately I'm sure I did something wrong but I am not able to see it, I followed the readme example but it doesn't work, it didn't show anything. Using the runserver script I can see this line, but I'm not sure how debug it

[02/May/2011 18:42:00] "GET /chaining/filter/catalogos/Departamento/pais/1/ HTTP/1.1" 500 82076

Would you please help me? I'm trying to implemented in the model "Municipio", this model has to be chained to "Departamento" model, below are my files:

models.py

from django.db import models
from sicfi.smart_selects.db_fields import ChainedForeignKey

...

class Municipio(models.Model):
    nombre = models.CharField(max_length = 64)
    pais   = models.ForeignKey(Pais)
    departamento = ChainedForeignKey(
        Departamento,
        chained_field="pais",
        chained_model_field="pais",
        show_all=False,
        auto_choose=True
    )
    estado = models.ForeignKey(Estado)

forms.py

from django import forms
from django.forms import ModelForm

...

class MunicipioForm(ModelForm):

    class Meta:
            model = Municipio

urls.py

from django.conf.urls.defaults import patterns, include, url
from django.conf.urls.defaults import *
from django.conf import settings

...

urlpatterns = patterns('',
    (r'^$', 'sicfi.views.index'),
    (r'^catalogos/', include('sicfi.catalogos.urls')),
    url(r'^chaining/', include('smart_selects.urls')),

settings.py

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.flatpages',
    'django.contrib.markup',
    # Uncomment the next line to enable the admin:
     'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)+apps.SICFI_APPS

apps.py

SICFI_APPS = (
    'sicfi.catalogos',
    'sicfi.usuarios',
    'sicfi.smart_selects'
)

Edit (by blag): Updated to use GFM.

Exception Value: need more than 1 value to unpack

Hello, i have a some stange issue:

Django Version: 1.3
Exception Type: ValueError
Exception Value: need more than 1 value to unpack
Exception Location: /home/combatcode/www/somehere/smart_selects/db_fields.py in init, line 16
Python Executable: /usr/local/python2.6/bin/python
Python Version: 2.6.1

Model:

class Somemodel(models.Model):
    kategoriagl = models.ForeignKey('self')
    kategorianext = ChainedForeignKey(
        'self', 
        chained_field="kategoriagl",
        chained_model_field="kategoriagl", 
        show_all=False, 
        auto_choose=True
    )

app is installed, and imported to models. Can u tell me what is wrong?

Edit (by blag): Updated to use GFM.

limit_choices_to on ChainedForeignKey?

Hello,

Is it possible to use limit_choises_to on a ChainedForeignKey?

My model:

datacenter = models.ForeignKey(Datacenter)
rack = ChainedForeignKey(
    Rack, 
    chained_field="datacenter",
    chained_model_field="datacenter", 
    show_all=False, 
    auto_choose=True
)
device = ChainedForeignKey(
    Device, 
    chained_field="rack",
    chained_model_field="rack", 
    show_all=False, 
    auto_choose=True
)   
interface = ChainedForeignKey(
    Interface, 
    chained_field="device",
    chained_model_field="device", 
    show_all=False, 
    auto_choose=True,
    limit_choices_to={'cable': None},
)

Im trying to limit the interfaces to only show interfaces without a cable (FK). But this does not appear to be working.

Gr,

Jasper

Problems with Django Admin

My code in models is :

#Model
class Person(models.Model):
    name = models.CharField(max_length=20, help_text="Tipo de Persona que se inscribe", verbose_name="Nombre del Tipo")

    class Meta:
        verbose_name = "Tipo de Persona"

    def __str__(self):
        return self.name

class MemberShip(models.Model):
    title = models.CharField(max_length=255, help_text="Nombre del tipo de afiliación.",verbose_name="Título")
    #type_person = models.CharField(max_length=255, choices=AFFILIATION_PERSON_TYPE, verbose_name='Tipo de Persona',)
    type_person = models.ForeignKey(Person, verbose_name="Tipo de Persona", related_name="membership")
    descript = models.CharField(max_length=500, help_text="Descripción del tipo de afiliación.", verbose_name="Descripción")
    value = models.DecimalField(decimal_places=2, max_digits=10, verbose_name='Cuota', help_text="Cuota de afiliación.")

    class Meta:
        #description = 'Modelo Membresía'
        verbose_name = "Membresía"

    def __str__(self):
        return self.title

#Afiliacion
class Affilliation(models.Model):
    person = models.ForeignKey(Person, verbose_name="Tipo de Persona", related_name="person")
    affiliation = ChainedForeignKey(
        MemberShip,
        chained_field="person",
        chained_model_field="name",
        show_all=False,
        auto_choose=True,
        verbose_name='Membresía',
        #related_name='affiliation'
    )

And my admin code is very simple:

class AffilliationAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Afiliación', {
            'fields': ['person', 'affiliation', 'affiliates', 'is_active'],
        }),
        ('Fechas', {
            'fields': ['date_in', 'date_renew'],
        }),
    ]
    list_display = ('affiliation', 'affiliates', 'is_active', 'date_prein', 'date_in', 'date_renew', 'date_end')
    list_filter = ('affiliation', 'affiliates', 'is_active')
    list_editable = ('affiliation',)
    search_fields = ('affiliation', 'affiliates', 'is_active', 'date_in',)

    def date_end(self):
        return self.date_in + timedelta(days=365)

    date_end.short_description = "Fecha de Expiración"
    date_end.allow_tags = True

admin.site.register(Affilliation, AffilliationAdmin)

As you can see all is well, but, if i try use ChainedField, well, in the django-admin i give this:
problemasconsmarts

In Juridica i have four MemberShips child's, but in this select box they aren't.

In a form this field works?

I'm trying to use ModelForm ChainedForeignKey and use of my models...

This works in admin, but when I send to the template through the ModelForm in this way in the template:

form

#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from django import forms
from django.forms import ModelForm
from validoc.certificacao.models import *

class Cadastro_certificado_ecpfForm(forms.ModelForm):
    class Meta:
        model = Cadastro_certificado_ecpf

views

from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.simple import direct_to_template
from validoc.certificacao.forms  import Cadastro_certificado_ecpfForm as ECPFForm

def create_ecpf_post(request):
    if request.method == 'POST':
       form = ECPFForm(request.POST)
       if form.is_valid():
            return HttpResponseRedirect('/add_ecpf/')
    else:
        form = ECPFForm()

    return direct_to_template(request,
                              template='certificacao/add_ecpf.html',
                              extra_context={'form':form} )

template

<form method='post' action='.'>{% csrf_token %}
       {{ form.as_p }}
<input type='submit'>
</form>

Does not work as the admin, what am I doing wrong?

Exit (by blag): Updated formatting to use GFM.

__init__() got multiple values for keyword argument 'queryset'

Hi,
I am using monkey patch (as here: models.ForeignKey(Country).contribute_to_class(Offer, 'country'))

After commit 98eae1c I have a error (Django version 1.3 pre-alpha SVN-14400):

Traceback (most recent call last):
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/core/management/commands/runserver.py", line 51, in inner_run
self.validate(display_num_errors=True)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/utils/importlib.py", line 35, in import_module
import(name)
File "/var/lib/pinax-env/lib/python2.6/site-packages/django_openid/models.py", line 118, in
user_model = models.get_model('auth', 'User')
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/loading.py", line 190, in get_model
self._populate()
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/utils/importlib.py", line 35, in import_module
import(name)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/swaps_custom/models.py", line 50, in
from forms import OfferForm
File "/media1/home/ivan/django_sites/pinax_industrial/apps/swaps_custom/forms.py", line 15, in
from swaps.forms import OfferForm
File "/var/lib/pinax-env/lib/python2.6/site-packages/swaps/forms.py", line 6, in
class OfferForm(forms.ModelForm):
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/forms/models.py", line 227, in new
opts.exclude, opts.widgets, formfield_callback)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/forms/models.py", line 181, in fields_for_model
formfield = f.formfield(**kwargs)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/smart_selects/db_fields.py", line 39, in formfield
return super(ChainedForeignKey, self).formfield(**defaults)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/fields/related.py", line 897, in formfield
return super(ForeignKey, self).formfield(**defaults)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/fields/init.py", line 444, in formfield
return form_class(**defaults)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/smart_selects/form_fields.py", line 13, in init
queryset = get_model(app_name, model_name).objects.all()
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/loading.py", line 190, in get_model
self._populate()
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/utils/importlib.py", line 35, in import_module
import(name)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/bookmarks_custom/models.py", line 59, in
from forms import BookmarkInstanceForm
File "/media1/home/ivan/django_sites/pinax_industrial/apps/bookmarks_custom/forms.py", line 15, in
from bookmarks.forms import BookmarkInstanceForm
File "/var/lib/pinax-env/lib/python2.6/site-packages/bookmarks/forms.py", line 8, in
class BookmarkInstanceForm(forms.ModelForm):
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/forms/models.py", line 227, in new
opts.exclude, opts.widgets, formfield_callback)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/forms/models.py", line 181, in fields_for_model
formfield = f.formfield(**kwargs)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/smart_selects/db_fields.py", line 39, in formfield
return super(ChainedForeignKey, self).formfield(**defaults)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/fields/related.py", line 897, in formfield
return super(ForeignKey, self).formfield(**defaults)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/django/db/models/fields/init.py", line 444, in formfield
return form_class(**defaults)
File "/media1/home/ivan/django_sites/pinax_industrial/apps/smart_selects/form_fields.py", line 15, in init
super(ChainedModelChoiceField, self).init(queryset=queryset, initial=initial, _args, *_defaults)
TypeError: Error when calling the metaclass bases
init() got multiple values for keyword argument 'queryset'

Don't sort the results in the views

As it stands right now, smart_selects' views sort the result queryset lexicographically before sending it to the browser. This behavior cancels any custom ordering defined in the model's Meta.ordering.

You could stop sorting the queryset in the view, since anyone who wants the above behavior could specify so in Meta.ordering

This would break backwards compatibility for people depending on smart_selects' sorting, so it could be controlled by a setting.

South error with GroupedForeignKey

It looks like "add_introspection_rules" is wrong for GroupedForeignKey. See http://stackoverflow.com/questions/4475377/django-south-with-django-audit-log and http://south.aeracode.org/docs/tutorial/part4.html. Without diving into the source of South, this patch made the problem go away.

    Index: smart_selects/db_fields.py
===================================================================
--- smart_selects/db_fields.py    (revision 6101)
+++ smart_selects/db_fields.py    (working copy)
@@ -62,5 +62,13 @@
         return super(ForeignKey, self).formfield(**defaults)

 if has_south:
+    rules_grouped = [(                                          
+        (GroupedForeignKey,),                        
+        [],                                             
+        {                                               
+            'to': ['rel.to', {}],        
+            'group_field': ['group_field', {}],        
+        },                                              
+    )]
     add_introspection_rules([], ["^smart_selects\.db_fields\.ChainedForeignKey"])
-    add_introspection_rules([], ["^smart_selects\.db_fields\.GroupedForeignKey"])
+    add_introspection_rules(rules_grouped, ["^smart_selects\.db_fields\.GroupedForeignKey"])

'generator' object has no attribute 'next'

I'm using Grappelli for my django-admin, when I introduce smart-selects into one of my models I get this error :
'generator' object has no attribute 'next'
any hint on how to deal with this exception ?

Self referential ForeignKeys not defined

I have a requirement where I need to list all the persons belonging to a particular category, I get error while trying to do so.

class Person(models.Model):
category = models.CharField()
parent = ChainedForeignKey(self, chained_field="category", chained_model_field="category", show_all=False, auto_choose=True)

Am I missing anything here?

Inline chained select issues

I am using django 1.6 and django-smart-selects 1.0.9. I don't seem to be able to get the chained select box to get updates without submitting the form.

In models.py I have the following :

class Product(models.Model):
    name = models.CharField(max_length=127,unique=True)

class Component(models.Model):
    name = models.CharField(max_length=126)
    product = models.ForeignKey(Product,blank=False)

class License(models.Model):
    product = models.ForeignKey(Product)
    component = ChainedForeignKey(Component,chained_field="product",
                                  chained_model_field="product",
                                  show_all=False, auto_choose=True)

class LicenseForm(forms.ModelForm):    
    class Meta:
        model = License
        fields = '__all__'

In admin.py I then have:

class LicenseInline(admin.StackedInline):
    model = models.License
    form = models.LicenseForm
    extra = 0

class LicenseAdmin(admin.ModelAdmin):
    list_select_related = True
    list_display = ('product','component')
    list_filter = ['product__name']
    list_display_links = ('product', 'component')

class LicenseFileAdmin(admin.ModelAdmin):
    form = models.LicenseFileForm
    inlines = [LicenseInline]

If I go to add a new license directly in the administration interface, the product and component boxes are correctly chained. If I add a new license in the inline form, selecting the product does not change the selection in the component box (in fact, it remains empty). If I select a product and then click to add another license, a second license form is shown, which has the correct component selection for the product of the previous form. Changing the product does not change the selection in this form either, though.

Selecting a product does cause a GET from the chaining URL, which returns the correct selection of the component for the product, but this selection simply isn't used to update the form. The returned value is identical for the inlined version and the standalone version of the license form.

Edit by blag: Formatted code with Markdown.

NameError: name 'basestring' is not defined

Hi,

I try this modul with Python 3.4.1, Django 1.6.5, django-smart-selects
1.0.9 and got following error:

Validating models...

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x014CA588>
Traceback (most recent call last):
  File "C:\workspace\03-src\lib\site-packages\django\utils\autoreload.py", line 93, in wrapper
    fn(*args, **kwargs)
  File "C:\workspace\03-src\lib\site-packages\django\core\management\commands\runserver.py", line 101, in
inner_run
    self.validate(display_num_errors=True)
  File "C:\workspace\03-src\lib\site-packages\django\core\management\base.py", line 310, in validate
    num_errors = get_validation_errors(s, app)
  File "C:\workspace\03-src\lib\site-packages\django\core\management\validation.py", line 34, in get_valid
ation_errors
    for (app_name, error) in get_app_errors().items():
  File "C:\workspace\03-src\lib\site-packages\django\db\models\loading.py", line 196, in get_app_errors
    self._populate()
  File "C:\workspace\03-src\lib\site-packages\django\db\models\loading.py", line 75, in _populate
    self.load_app(app_name, True)
  File "C:\workspace\03-src\lib\site-packages\django\db\models\loading.py", line 99, in load_app
    models = import_module('%s.models' % app_name)
  File "C:\workspace\03-src\lib\importlib\__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "C:\workspace\03-src\djangoproject\service\models.py", line 34, in <module>
    class Vehicle(models.Model):
  File "C:\workspace\03-src\djangoproject\service\models.py", line 45, in Vehicle
    auto_choose=True
  File "C:\workspace\03-src\lib\site-packages\smart_selects\db_fields.py", line 20, in __init__
    if isinstance(to, basestring):
NameError: name 'basestring' is not defined

I found some advice: oxplot/fysom#1

Error 500 in console, Django 1.7, mimetype TypeError (not visible in console)

Hi, I just spotted this error (after MANY clicks in debug mode of pycharm 🔨) :

TypeError at /chaining/filter/questionnaires/Block/questionnaires/2/
__init__() got an unexpected keyword argument 'mimetype'

Request Method: GET
Request URL: http://localhost:8000/chaining/filter/questionnaires/Block/questionnaires/2/
Django Version: 1.7.2
Python Version: 2.7.6

Traceback:
File "/media/pawantu/Data/VirtualEnvs/genida/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/media/pawantu/Data/VirtualEnvs/genida/local/lib/python2.7/site-packages/smart_selects/views.py" in filterchain
  26.     return HttpResponse(json, mimetype='application/json')
File "/media/pawantu/Data/VirtualEnvs/genida/local/lib/python2.7/site-packages/django/http/response.py" in __init__
  318.         super(HttpResponse, self).__init__(*args, **kwargs)

Exception Type: TypeError at /chaining/filter/questionnaires/Block/questionnaires/2/
Exception Value: __init__() got an unexpected keyword argument 'mimetype'

This results in the field in admin not populating with querysets values (just displaying the "-------").
What do you think? It might be because of Django 1.7 not accepting mimetype argument anymore.

Temporary solution: just comment the mimetype part of the HttpResponse

how about ManyToManyField filtering

Could we extend this to support filtering of ManyToManyFields as well? For example a class Wine could be related to grapes via a ManyToManyField and if the user selects a winetype, it will automatically filter the grapes in the multi-select field to show only those of the given winetype (red, white, etc)..

I love this component - thanks for your great work!

Greetings from Switzerland,

Gabe

Compatibility issue with django-ajax-selects

I'm currently using django-ajax-selects for the chained_field. When I change the value of the chained_field, the ChainedForeignKey isn't updated. Would it be possible to have it working ?
Thank you.

Releasing updated version to PyPi

Just want to point out that a lot of the bug fixes in 2014 has not been officially release to PyPi yet.

I have to remember to get from the latest branch everytime, "pip install git.xx.xxx.". This is ok. But it may prevent developers that are new to the library from adopting.

Any reason that is preventing the release? How can we help?

Deprecation warning in Django 1.8

Now, we have the next warning:

/home/tulipan/Proyectos/TiempoTurco/lib/python3.4/site-packages/smart_selects/views.py:10: RemovedInDjango19Warning: django.db.models.get_model is deprecated.
  model_class = get_model(app, model)

Can anyone fix it?

Reverse relationship undefined?

It seems there is no reverse relationship manager defined..

class A
    brel =  ChainedForeignKey(B, ...)

class B

    def test(self)
        self.a_set.all()  #  <--- undefined

If I change it to models.ForeignKey it works...

Edit (by blag): Formatted with GFM.

Support for foreign characters???

I have just installed django-smart-selects...and have found two
immediate issues:

  1. On your example for GroupedForeignKey, you precede this with model.GroupedForeignKey,
    this needs to be just GroupedForeignKey.
  2. Your chaining doesn't like foreign characters it seems....I have a
    region in Turkey in a select box. On selection of a region I want to
    change the content of the cities select box. But regions with foreign
    characters, such as Muğla, although they show up in the regions select
    box, on selection, do not change the contents of cities, however, Mugla
    (with a normal 'g') does.

Chained selection not working in admin

class Continent(models.Model):
    continent=models.CharField(max_length=20)

class Country(models.Model):
    country= models.CharField(max_length=20)
    continent=ChainedForeignKey(Continent,chained_field="continent", chained_model_field="continent")

class State(models.Model):
    state=models.CharField(max_length=20)
        country = ChainedForeignKey(Country,chained_field="country", chained_model_field="country")

class City(models.Model):
    city=models.CharField(max_length=20)
        state=ChainedForeignKey(State,chained_field="state", chained_model_field="state")

class District(models.Model):
    district = models.CharField(max_length=20)
        city=ChainedForeignKey(City,chained_field="city", chained_model_field="city")

Hello.
Above is my code using your app. I now have 2 issues

  1. When I add country in admin. I can't assign the continent to each country because the continent is not in the list
  2. If I select United States, all states don't show in the dropdown list. Can you take a look?

THanks from Canada

Edit (by blag): Formatted with GFM.

I have a question

in the javascript file on widgets.py, when do you use the dismissRelatedLookupPopup method?

Many to Many

Does django-smart-selects support Many-to-Many? If yes where can I find that information?

Thanks

Smart Selects outside Admin?

Hi, I've been trying to use smart selects outside the admin site but with no luck. It works on the admin site btw.

Was this designed to work outside the admin or I am trying to force it?

Thanks!

Remove JQuery from Widget media

I see that you are loading JQuery with the widget media. I wonder if this is the ideal thing to do because, I think, there is a huge possibility that JQuery have already been loaded before on the template and therefore JQuery would be downloaded multiples times. What do you think?, maybe saying in the docs that JQuery must be loaded before the widget would be enough.

Empty dropdowns when ModelForm is Edited

The dependant dropdowns are not populated when the queryset of the ModelForm is changed - or the ModelForm is used for Editing(i.e, an instance is loaded for editing).

ie., if person is the chained_field in my form and I changed its queryset before rendering as follows, then the dependent dropdowns do not get populated while the form is rendered.

form.fields['person'].queryset = this_dept.get_persons()

Edit (by blag): Formatted code with GFM.

Select Field Filtered By More than one Field

I think it could be interesting fielter a select field by more than one model, i.e., I have a model that can be filtered by n models, because it have n foreign keys and it could be usefull filter it by more than one model.

Problem in using django-smart-selects the TabularInline or StackInline

For example, when using django-smart-selects the TabularInline in the admin.py class is inline with the "extra = 3" when I add a new account will appear three lines to be filled in these lines django-smart-selects will work, but if you add a new row it does not work anymore. This is the way you are doing bind the event in JS.

Add option to allow None for the chained field

In our case we have customers, domain handles and domains. A handle has a customer, so does a domain. A domain has a handle (actually more, but that's not relevant now) and the choices should be limited to those relevant for that customer. For us, that's all handles that have the same customer (which ChainedForeignKey handles), but also some shared handles which have no customer.

Use in inline forms

This is not a problem, it's a new functionallity.
I think if whe can do the same with field in inline forms, filtered by field in parent form.
When field parent change, sons fields could be inizialized and filtered again.

Thanks.

GroupedModelSelect: Last group not shown occasionally

When the last group only have one item, the last group is not shown. This patch fixes that problem in a very procedural way. Could it find its way upstream?

Index: libs/smart_selects/form_fields.py
===================================================================
--- libs/smart_selects/form_fields.py   (revision 6379)
+++ libs/smart_selects/form_fields.py   (working copy)
@@ -40,16 +40,20 @@
         # accessed) so that we can ensure the QuerySet has not been consumed. This
         # construct might look complicated but it allows for lazy evaluation of
         # the queryset.
-        final = [("", self.empty_label or "---------"), ]
-        group = None
+        group_indexes = {}
+        choices = [("", self.empty_label or "---------")]
+        i = len(choices)
          for item in self.queryset:
-            if not group or group[0] != unicode(getattr(item, self.order_field)):
-                if group:
-                    final.append(group)
-                group = [unicode(getattr(item, self.order_field)), []]
-            group[1].append(self.make_choice(item))
-        return final
-
+            order_field = getattr(item, self.order_field)
+            group_index = order_field.pk
+            if not group_index in group_indexes:
+                group_indexes[group_index] = i
+                choices.append([unicode(order_field), []])
+                i += 1
+            choice_index = group_indexes[group_index]
+            choices[choice_index][1].append(self.make_choice(item))
+        return choices
+    
     def make_choice(self, obj):
         return (obj.pk, "   " + self.label_from_instance(obj))

Edit (by blag): Updated to use GFM.

Checkbox for ManyToMany

It would be really useful if with a ManyToMany field (related to a ForeingKey) choices can be updated according with FK...

Problem with the new release

Today i updated this app, and when i try to init the server, i have this problem:

  File "/home/tulipan/Proyectos/TiempoTurco/tiempoturco/news/models.py", line 35, in New
    verbose_name=_('Subtopic'), related_name='news',
  File "/home/tulipan/Proyectos/TiempoTurco/lib/python3.4/site-packages/smart_selects/db_fields.py", line 19, in __init__
    if isinstance(to, basestring):
NameError: name 'basestring' is not defined

Javascript is not generated correctly when using custom form prefixes

When a Django model has a ChainedForeignKey, and the Django form used for displaying a uses a custom prefix via a prefix keyword argument, the javascript output for the form's ChainedModelChoiceField does not take this prefix into account. Thus the generated javascript fails as the id of the "chained_field" does not match with the id used in the javascript.

not work on django admin list filter

Evn : django-suit, django 1.7 ,python 2.7
django-smart-selects works perfect in add form view but list view.

code:

class Location(models.Model):
    province = models.ForeignKey(Province)
    city = ChainedForeignKey(
        City,
        chained_field="province",
        chained_model_field="province",
        show_all=False,
        auto_choose=True
    )
    name = models.CharField(max_length=20,)
    priority = models.IntegerField(null=True, blank=True)


class LocationAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ('name',)
    list_filter = ('province', 'city')

ChainedForeignKey doesn't support abbreviated ForeignKey model name syntax

The standard Django ForeignKey field allows you to reference models which have not yet been defined using either the name of the model (e.g. models.ForeignKey("Author")) but ChainedForeignKey requires the full <app>.<model> syntax to avoid a ValueError in db_fields.py on line 16 when it attempts to split the field name.

Since the shorter form is actually recommended by default in the Django documentation (see http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey) this difference should at least be documented.

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.