问题
I use Django Countries like the following. In my view it seems to order the select items according to the english original values (e.g. Deutschland
will be found under G
(=Germany)) but in the admin the values are ordered according to the current language. This isn't done by JavaScript (I tried it by disabling JS). I have no idea how to fix this. Versions: Django 1.5.5, Django Countries 2.1.2
models.py
from django_countries.fields import CountryField
class MyModel(ModelSubClass):
country = CountryField(_('country'), blank=True)
#...
class MyForm(ModelSubForm):
class Meta(object):
model = MyModel
#...
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['country'].required = True
#...
views.py
class MyCreateView(CreateView):
model = MyModel
form_class = MyForm
# overriding `dispatch`, `get_initial`, `form_valid`, `get_context_data`, `get_success_url`
my_template.html
{% extends "base.html" %}
{% load i18n %}
{% block content %}
<form class="form-horizontal" role="form" method="post" action="">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn btn-success">{% trans 'Submit' %}</button>
</form>
{# ... #}
{% endblock content %}
I can provide more information if needed.
Another thing is that the ordering of countries with non-ASCII capitals is wrong in the admin. But I think this is another issue.
回答1:
Override the choices with the original in MyForm
's __init__
:
from django_countries import countries
class MyForm(ModelSubForm):
class Meta(object):
model = MyModel
#...
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['country'].choices = [self.fields['country'].choices[0]] + list(countries)
#...
Use the first item of the choices to keep the empty value (---------
).
As far as I understand it the issue is that the choices
of a field in models.py are loaded at server start, i.e. once. In the form you can override it on a request basis. The sorting is done by countries
(an instance of Countries
in the same file).
I'm open for a better solution.
回答2:
Question has been asked similarly before here.
Answer was:
function sort(a, b) {
return (a.innerHTML > b.innerHTML) ? 1 : -1;
};
$('#select_id option').sort(sort).appendTo('#select_id');
来源:https://stackoverflow.com/questions/25626044/django-countries-wrong-sorting-in-translated-choices-but-works-in-the-admin