Ordering Choices in ModelForm ManytoManyField DJANGO -


i have in models.py

class business(models.model):    industry = models.models.manytomanyfield(industry) 

in forms.py

class businessform(forms.modelform):     class meta:         model = business 

when render form, industry names appear in multiple select box. do make industry names in alphabetical order?

there several ways:

you can override queryset ordering on per-form basis, set ordering meta class option, or override model manager queryset ordering method.

override global model manager queryset

class industrymanager(models.manager):     def get_query_set(self):         return (             super(industrymanager, self)             .get_query_set()             .order_by('name')         )  class industry(models.model):     name = models.charfield(max_length=128)     objects = industrymanager() 

specify global meta option ordering

class industry(models.model):     name = models.charfield(max_length=128)      class meta:         ordering = ['name'] 

per form ordering

class myform(forms.modelform):     class meta:         model = business      def __init__(self, *args, **kwargs):         super(myform, self).__init__(*args, **kwargs)            self.fields['industry'].queryset = industry.objects.order_by('name') 

there's shortcut called formfield_for_manytomany if dealing django admin.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -