Reputation: 1297
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.
Upvotes: 1
Views: 581
Reputation: 1297
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.
Upvotes: 1