Django 老司機

1、admin 後臺,不同field,下拉數據關聯:

https://github.com/digi604/django-smart-selects

models.py

from smart_selects.db_fields import GroupedForeignKey,ChainedForeignKey 

class Asset(models.Model):
    assetLine = models.ForeignKey(Line, verbose_name= u'線路',related_name='asset_line')
    assetStation = ChainedForeignKey(
                    Station, 
                    chained_field="assetLine",
                    chained_model_field="lineName", 
                    show_all=False, 
                    auto_choose=True,
                    verbose_name= u'車站'
    )
    



2、admin 後臺,ajax 搜索:

http://zurb.com/forrst/posts/Django_admin_ajax_search_filter-IlN

保存一下代碼:/static/instantsearch.js

(function($) {
    $(document).ready(function($) {
        $('#changelist-search input[type=submit]').hide();
        $('label[for=searchbar]').html('Filter:');
        $('#searchbar').keyup(function(e) {
            if (e.keyCode === 27) {
                if (!$(this).val()) {
                    return;
                }
                $(this).val('');
            }
            $('#changelist-form').load(window.location.pathname + '?q=' + $(this).val() + ' #changelist-form');
        }).focus();
    });
})(django.jQuery);
在admin.py

class AssetAdmin(admin.ModelAdmin):
    search_fields = ['assetID']
    
    class Media:
        js = ("/static/instantsearch.js",) 
        


3、admin後臺,add對象框框自動補全

https://github.com/sjrd/django-ajax-selects

settings.py

# define the lookup channels in use on the site
AJAX_LOOKUP_CHANNELS = {
    'assetID':( 'asset.lookups', 'AssetLookup' ) ,
}

# magically include jqueryUI/js/css
AJAX_SELECT_BOOTSTRAP = True
AJAX_SELECT_INLINES = 'inline'

INSTALLED_APPS = [
    ...
    'ajax_select',
]

新建 app/lookups.py

from ajax_select import LookupChannel
from django.utils.html import escape
from django.db.models import Q
from asset.models import *

class AssetLookup(LookupChannel):

    model = Asset

    def get_query(self,q,request):
        return Asset.objects.filter(Q(assetID__icontains=q)).order_by('id')

    def get_result(self,obj):
        u""" result is the simple text that is the completion of what the Asset typed """
        return obj.assetID

    def format_match(self,obj):
        """ (HTML) formatted item for display in the dropdown """
        return self.format_item_display(obj)

    def format_item_display(self,obj):
        """ (HTML) formatted item for displaying item in the selected deck area """
        return u"<div><i>%s</i></div>" % (escape(obj.assetID))


admin.py

from ajax_select import make_ajax_form
from ajax_select.admin import AjaxSelectAdmin
from ajax_select import make_ajax_field

class AssetAdmin(AjaxSelectAdmin):
    form = make_ajax_form(Asset,{'assetID':'assetID',})
 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章