我是关于编程的新手,所以我的代码有时会显得愚蠢。
我从2天开始就遇到了这个问题而且我在网上寻找但却找不到我想要的东西。 我在stackoverflow上看到了相关的问题,但它似乎只适用于表单,我想在Admin界面中实现它。
我想在下拉菜单中显示选项,具体取决于用户在其他下拉菜单中的选择。
这是我的模特:
class Airport(BaseModel):
airport_code = models.CharField(max_length=50, verbose_name="Airport Code (ICAO)")
airport_name = models.CharField(max_length=50, verbose_name="Airport Name")
country = models.ForeignKey('cities_light.Country', verbose_name='Country')
state = models.ForeignKey('cities_light.Region', verbose_name='Region')
city = models.ForeignKey('cities_light.City', verbose_name='City')
pass
# Afficher dans la partie Admin la valeur au lieu des objets
def __str__(self):
return 'Airport: {}'.format(self.value)
所有这一切,在Admin:)
非常感谢!
答案 0 :(得分:0)
我建议使用不同的数据结构:
{"USA": ["Alabama", "Alaska"], "Canada": ["Ontario", "Quebec"]}
然后在models.py中,你可以用这种方式加载/存储dict:
class Airport(BaseModel):
airport_code = models.CharField(max_length=50, verbose_name="Airport Code (ICAO)")
airport_name = models.CharField(max_length=50, verbose_name="Airport Name")
city = models.CharField(max_length=50, verbose_name="City")
country = models.TextField(blank=True, null=True)
def setlist(self, x):
self.country = json.dumps(x)
@property
def getlist(self):
if self.country:
return json.loads(self.country)
else:
return {}
在view.py中:
@login_required
def show_airport(request):
airport = Airport.objects.first()
return render(
request,
'your_template.html',
{'airport': airport}
)
因此,在模板中将更容易迭代键和值以生成相关菜单:
{% for key, value in airport.getlist.items %}
<p>{{key}}: {{value}} </p>
{% endfor %}
然后,您可以使用javascript管理用户选择客户端,例如:
<form>
<select id="nation">
{% for key, value in airport.getlist.items %}
<option value="{{key}}">{{key}}</option>
{% endfor %}
</select>
<select id="states">
</select>
</form>
<script>
country_list = {{ airport.getlist.items|safe }};
jQuery.each(country_list[$('#nation').val()], function() {
$("#states").append('<option value="' + this + '">' + this + '</option>')
});
$('#nation').on('change', function(event){
$('#states').empty()
jQuery.each(country_list[$('#nation').val()], function() {
$("#states").append('<option value="' + this + '">' + this + '</option>')
});
});
</script>
更新:
在django admin中使用django-autocomplete-light模块的国家示例:
pip install django-autocomplete-light
settings.py
INSTALLED_APPS = [
'dal',
'dal_select2',
'django.contrib.admin',
...
urls.py
from django.conf.urls import url
from django.contrib import admin
from countryTest.views import CountryAutocompleteFromList
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test-country/$', CountryAutocompleteFromList.as_view(), name="country-list-autocomplete")
]
views.py
from dal.autocomplete import Select2ListView
class CountryAutocompleteFromList(Select2ListView):
def get_list(self):
continent = self.forwarded.get('continent', None)
qs = {
'Usa': ['California', 'Kansas'],
'Canada': ['Quebec', 'Ontario']}
if continent:
return qs[continent]
admin.py
from countryTest.models import Country
from django.contrib import admin
from countryTest.forms import CountryForm
class CountryAdmin(admin.ModelAdmin):
form = CountryForm
model = Country
admin.site.register(Country, CountryAdmin)
models.py
from django.db import models
class Country(models.Model):
continent = models.CharField(max_length=250, null=True)
state = models.CharField(max_length=250, null=True)
def __unicode__(self):
return " ".join((str(self.continent), str(self.state)))
forms.py
from dal import autocomplete
from django import forms
CONTINENT_CHOICES = (('Usa', 'Usa'), ('Canada', 'Canada'))
def get_choices_list():
return ['Quebec', 'Ontario', 'Kansas', 'California']
class CountryForm(forms.ModelForm):
continent = forms.ChoiceField(choices=CONTINENT_CHOICES)
state = autocomplete.Select2ListChoiceField(
choice_list=get_choices_list,
widget=autocomplete.ListSelect2(url='country-list-autocomplete', forward=['continent'])
)