2014-09-02 41 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