I have Student, Class and StudentClass models. I would like a student to be able to join a new class by inputting the class_code into a form. To join a class the user's student_id and the class_code is saved to the StudentClass model. The student_id isn't a form field so should be obtained by querying the Student model with the logged-in user's username and returning the student_id.
models.py:
class StudentClass(models.Model):
class Meta:
unique_together = (('class_code', 'student_id'),)
class_code = models.ForeignKey(Class, on_delete=models.CASCADE)
student_id = models.ForeignKey(Student, on_delete=models.CASCADE)
forms.py:
class JoinClassForm(forms.ModelForm):
class Meta:
model = StudentClass
fields = ['class_code']
exclude = ('student_id',)
views.py
@login_required
def join_class(request):
if request.method == "POST":
joinclass_form = JoinClassForm(request.POST or None)
if joinclass_form.is_valid():
formclass_code = joinclass_form.data.get('class_code')
if Class.objects.filter(class_code=formclass_code).exists():
joinclass_form.save(commit=False)
joinclass_form.student_id =
Student.objects.filter(username=request.user.username).values_list('student_id', flat=True)
joinclass_form.save()
return redirect('assignments')
else:
messages.success(request, ("This class doesn't exist!"))
else:
joinclass_form = JoinClassForm
return render(request, 'join_class.html', {'joinclass_form': joinclass_form})
I've tried using a hidden_field for student_id, excluding student_id from the form fields and saving as commit=False, and I've gotten the same error: IntegrityError Not NULL constraint failed. Is there an error in my code that I have missed or am I using the wrong method? Thanks in advance
Edit: Forgive me but copy-paste went kinda awry on the last set of code and I have no idea how to fix it
CodePudding user response:
you dont need to put .username at request.user. You can just say request.user
CodePudding user response:
Thanks everyone for your help but I managed to fix it now
In case anyone needs this in the future, I realised that I made 2 mistakes:
- I wasn't saving my form correctly in my views.py, I was trying to save the value student_id to the form rather than an object.
https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#the-save-method
- I named my foreign key in my StudentClass table as student_id which meant that Django was renaming it as student_id_id. To fix this, I just removed _id from student_id in the StudentClass table.