1👍
NOTE This answer is just a general idea of an approach.
What you want here is a ManyToManyField between your Student/User model and the course model, since supposedly many students can have a Course, and a Course can have Many Students. You could do this with your user model, but it’ll be easier for me to answer with a separate Student model connected to the user model, such as:
from django.conf import settings
class Student(models.Model):
student = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
This is one way to separate different types of users, for example, teachers from students, by extending the user model with a OneToOneField. You could also just add another field to your user model, such as user_type, if you have a custom user model already in place.
Now to your actual question. Set up the ManyToManyField (Note how I capitalize class names (Course, not course):
class Course(models.Model):
course_name = models.CharField(max_length=200)
course_id = models.CharField(max_length=10)
course_sec = models.IntegerField()
classroom_id = models.CharField(max_length=50,unique=True)
created_by = models.ForeignKey(User,on_delete=models.CASCADE)
students = models.ManyToManyField(Student, blank=True)
Now the simple part. When you want to add a student to the course, all you have to do is first get the course by querying for the classroom_id, then adding the student to it:
student = Student.objects.get(student=request.user)
course = Course.objects.get(classroom_id=request.POST.get('classroom_id'))
course.add(student)
Note that the add() function automatically saves. The ManyToManyField will create an intermediate table between Students and Courses. Read up on the docs to see how you can query to get all students in a course, or to get all courses a student has.
Edit
If you are going to use your User model instead of creating a seperate Student and Teacher model, like I believe you did here, that is fine. You can just change the ManyToManyField like this:
# Instead of:
class Course(models.Model):
course_name = models.CharField(max_length=200)
course_id = models.CharField(max_length=10)
course_sec = models.IntegerField()
classroom_id = models.CharField(max_length=50,unique=True)
created_by = models.ForeignKey(User,on_delete=models.CASCADE)
students = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)
Then in your view,
Course.objects.get(classroom_id=request.POST.get('classroom_id'))
course.add(request.user)