1
votes

I want to use a Django (1.4) modelformset in which, when the formset is loaded the forms will be arranged by a exam_date field I have in my model. To do this I've created the following simple BaseModelFormSet

class BaseExamDateFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseExamDateFormSet, self).__init__(*args, **kwargs)
        self.queryset = models.ExamDate.objects.all().order_by('exam_date')

As you can see I've changed the queryset as proposed in the django docs (later I'll also change its clean method but it doesn't matter right now). After that I am using it in my view to create the formset:

ExamDateFormSet = modelformset_factory(
    models.ExamDate, 
    exclude =('authority', ), 
    can_delete=True, 
    extra=1,
    formset = forms.BaseExamDateFormSet
)
...
formset = ExamDateFormSet()

My problem is that when the formset is rendered the data in the forms is always in the same ordering (probaby by id) regardless of the value of the order_by attribute :(

Should I try setting a default order by in my ExamDate model ? I really don't like that solution though :(

TIA !

2

2 Answers

3
votes

After some more searching I found a solution !

I ignored the queryset attribute and added the following method to the BaseExamDateFormSet:

def get_queryset(self):
    return models.ExamDate.objects.all().order_by('exam_date')

However I don't know yet why the queryset attribute isn't working.

1
votes

Easier still, in your above code you could erase your formset= argument in modelformset_factory call and instantiate your formset as:

formset = ExamDateFormSet(queryset=models.ExamDate.objects.order_by('exam_date'))