[Answered ]-Getting certain values to appear in django form

1👍

def get_form(self, form_class):
        form = super(CreateQuestion, self).get_form(form_class)
        form.fields['classe']= Classe.objects.filter(professor=self.request.user.id)
        return form

you could try something like this

1👍

There’re many ways to solve this problem depending on how you structure your Django application. For example, one way could be:

class QuestionForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        professor = kwargs.pop('professor')
        super(QuestionForm, self).__init__(*args, **kwargs)
        self.fields['classe'].queryset = Classe.objects.filter(professor=professor)

    class Meta:
         model = Question
         fields = ('title', 'question', 'classe')

class CreateQuestionView(LoginRequiredMixin, CreateView):
    form = QuestionForm
    template_name = "attendance_test/add_test.html"

    def get_form_kwargs(self):
        kwargs = super(CreateQuestionView, self).get_form_kwargs()
        kwargs['professor'] = self.request.user
        return kwargs

    def form_valid(self, form):
        form.instance.instructor = self.request.user
        return super(CreateQuestionView, self).form_valid(form)

This filters classes based on the currently logged in user.

Although I think it is incorrect to inherit Teacher model from User. More performant and traditional solution would be to use aggregation in this case:

class Teacher(models.Model):
    user = models.ForeignKey(User)
    # or
    #user = models.OneToOneField(User)

Also, you have problem with your code: initial is an initial selected value for the form field, it’s not a range of allowed values. By setting initial you set an initial selected value for the form field.

context is a dict of variables that are passed into your template. So I believe you don’t need to define get_context in your view (or at least it doesn’t need to pass list of Classes).

Leave a comment