Reputation: 97
I have a model of Teacher that creates classes. I have another model of students who take the classes but do not create them. I also have the classes model. What I a trying to do is have the student search for classes and click on a result and add it to classes they are a part in. I have the search working, but I cant get the second part working.
I have my student model as a ManyToManyField because I figured a Classe should have more than one student, and the student can take part in more than one Classe. For some reason in admin, as soon as a student is added, it has them automatically taking part in all the classes created. I am trying to get the student to take part in only classes they choose, after searching for such classes.
My student model:
class Student(User):
classe = models.ManyToManyField(Classe)
school_name = models.CharField(max_length=250)
My view:
def add_course(request, classe_id):
#c = Classe.objects.get(pk=classe_id)
request.user.classe = classe_id
request.user.save()
return
Should I have the Classe as the one defining the ManyToMany relationship with the student? Also, since I have the ManyToMany relationship with the student, I can filter course objects based on students, but when I do, nothing shows up.
Thanks.
Upvotes: 0
Views: 40
Reputation: 599926
I think you're just misunderstanding the UI of a multi-select field in the admin. It always shows all options; but those that are actually selected for that user will be shown as highlighted. By default of course, no options will be selected, but you can click on them to add them.
You may find it better to use the filter_horizontal
option for that field, which makes the UI much clearer.
class StudentAdmin(admin.ModelAdmin):
model = Student
filter_horizontal = ('classe',)
Secondly, to add a course for a user in your view, you need to use .add()
:
request.user.classe.add(classe_id)
You don't need to call save()
after doing that.
Upvotes: 1