Home > Software design >  Django: order elements of a form field
Django: order elements of a form field

Time:07-31

I have two models named Quiz and Course

class Quiz(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='quizzes',)

and

class Course(models.Model):
    name = models.CharField(max_length=30)

I'm using quiz model in a createview.

class newQuiz(CreateView):
    model = Quiz
    template_name = 'teacher/new_quiz.html'
    fields = ['name', 'course', ]

course field is shown as an choice field in the form how can i order the course choices in ascending order while showing in the form

CodePudding user response:

The simplest way is to provide a default odering for the Course model with the ordering meta option [Django-doc]:

class Course(models.Model):
    name = models.CharField(max_length=30)

    class Meta:
        ordering = ('name',)

or you can patch the form in the CreateView itself by overriding .get_form(…) [Django-doc]:

class CreateQuizView(CreateView):
    model = Quiz
    template_name = 'teacher/new_quiz.html'
    fields = [
        'name',
        'course',
    ]

    def get_form(self, *args, **kwargs):
        form = super().get_form(*args, **kwargs)
        form.fields['course'].queryset = Course.objects.order_by('name')
        return form
  • Related