如何做一个实时搜索表格ModelChoiceField

时间:2019-04-06 09:43:44

标签: django

如何在模板html中以ModelChoiceField形式进行实时搜索...例如,我写一个数字,而我只会得到具有该数字的数据 我正在使用django 1.9

models.py

class Suivre(models.Model):
formationffF=models.ForeignKey(FormationDispo,on_delete=models.CASCADE)
numcniF=models.ForeignKey(Personne,on_delete=models.CASCADE)
session = models.CharField(max_length=50)

form.py

class Ajout3 (forms.Form):
numcniF=forms.ModelChoiceField(queryset=Personne.objects.all().order_by('-time'))
formationf =forms.ModelChoiceField(queryset=FormationDispo.objects.all().order_by('time') )
session = forms.CharField(required=True, widget=forms.TextInput())

tamplate.html

<form method="post">
{% load crispy_forms_tags %}
{% csrf_token %}
{{con|crispy}}
<button type="submit" class="btn btn-success" > SAVE</button>
</form>

1 个答案:

答案 0 :(得分:0)

我建议您使用django-adminajax_select

在您的应用中创建一个名为admin.py的文件。

admin.py

from django.contrib import admin
from myproject.myapp.models import Suivre
from ajax_select import make_ajax_form

# creates model-centric interface where trusted users can manage content on your site. 
class SuivreAdmin(admin.ModelAdmin):
    model = Suivre
    form = make_ajax_form(
        Suivre,
        {
            'numcniF': 'all_personne',  # ForeignKeyField
             'formationf':'all_formationdispo'
        })

# registers admin
admin.site.register(Suivre, SuivreAdmin)

请注意,我正在使用ajax_select库,该库将创建下图所示的界面。  ajax select

安装ajax_select:

pip install django-ajax-selects

添加应用:

settings.py

# settings.py
INSTALLED_APPS = (
    ...
    'ajax_select',  # <-   add the app
    ...
)
AJAX_LOOKUP_CHANNELS = {
    'all_formationdispo': {
        'model': 'app.FormationDispo',
        'search_field': 'name'
    },
    'all_personne': {
        'model': 'app. Personne',
        'search_field': 'name'
    },
  }

在您的项目中包含网址:

urls.py

# urls.py
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
from ajax_select import urls as ajax_select_urls

admin.autodiscover()

urlpatterns = [

    # place it at whatever base url you like
    url(r'^ajax_select/', include(ajax_select_urls)),