2014-09-02 34 views
1

我使用Django Countries,如下所示。在我看来,它似乎根据英文原始值(例如Deutschland将在G(=德国))找到选择项目,但在管理员中,值根据当前语言排序。这不是由JavaScript(我试图通过禁用JS)完成。我不知道如何解决这个问题。版本:1.5.5 Django的,Django的国家2.1.2Django-Countries:翻译选项中的错误排序(但在管理员中有效)

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 %} 

我可以提供更多的信息如果需要。

另一件事是在管理员中使用非ASCII大写的国家的排序是错误的。但我认为这是another issue

回答

1

覆盖在MyForm__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) 
     #... 

使用选择的第一个项目,以保持空值(---------)。

就我所知,问题在于models.py中的字段的choices在服务器启动时加载,即一次。在表单中,您可以根据请求覆盖它。排序由countries(在同一文件中的Countries的实例)完成。

我打开更好的解决方案。

0

问题在here之前的询问类似。

的回答是:

function sort(a, b) {    
     return (a.innerHTML > b.innerHTML) ? 1 : -1; 
    }; 
$('#select_id option').sort(sort).appendTo('#select_id'); 
+1

我以前读过这篇文章。我正在寻找非JS解决方案。或者我错过了一些东西,它也是由JS在管理中排序的? – yofee 2014-09-02 15:27:15