简体   繁体   English

如何在Django中按字母顺序对下拉列表进行排序

[英]How to Sort drop downs in alphabetical order in Django

I am trying to sort a drop down values in a form field in alphabetical order 我试图按字母顺序对表单字段中的下拉值进行排序

Drop down is the field = strategy 下拉是field =策略

I tried using the .order_by to solve this bug but it some how doesn't seems to solve it 我尝试使用.order_by来解决这个bug,但它似乎并没有解决它

Below is the code i tried 以下是我试过的代码

class AddForm(forms.ModelForm):

  class Meta:
    model = Line
    fields = ('analyst','strategy','conviction','startdate','startvalue','target','review','reason','rationale')
  def __init__(self, *args, **kwargs):
      self.user = kwargs.pop('user', None)
      super(AddForm, self).__init__(*args, **kwargs)
      self.fields['Strategy'].queryset = strategy.objects.order_by('name')

I get a indentation error and the server stops running... i also tried using 我收到缩进错误,服务器停止运行...我也试过使用

strategy = forms.ModelChoiceField(queryset=strategy.objects.order_by('name'))

Didn't work!, where am i going wrong? 没工作!,我哪里错了?

class AddForm(forms.ModelForm):

  class Meta:
    model = Line
    fields = ['analyst','strategy','conviction','startdate','startvalue','target','review','reason','rationale']
  def __init__(self, *args, **kwargs):
      super(AddForm, self).__init__(*args, **kwargs)
      self.user = kwargs.pop('user', None)
      self.fields['strategy'].queryset = self.fields['strategy'].queryset.order_by('name')

Try this also you can take a look at this SO answer which might be helpful to understand. 试试这个你也可以看一下这个可能有助于理解的答案。

You can order on your model Meta class 您可以在模型Meta类上订购

But as your error is saying, you are indenting your code with TABs and SPACEs in the same block. 但正如您的错误所说,您在同一个块中使用TAB和SPACE缩进代码。

Enable the tabs and spaces visualization on your ide and fix that. 在ide上启用选项卡和空格可视化并修复它。 Basically you have to choose between a tab or a block of spaces. 基本上,您必须在制表符或空格块之间进行选择。

Python (and other languages) that are indented usually complain if you do that. 如果你这样做,缩进的Python(和其他语言)通常会抱怨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM