I have a form including several fields. Let's say one of them is "subjects", a multiple choice selection field, and the other one is "main_subject", a single choice selection field. How should I code the views.py file in order to automatically select a subject in the "subjects" one, if the corresponding "main_subject" is selected? (I do not want to save a main subject for a student if it isn't included as one of his subjects).
models.py
class Subject(models.Model):
subject=models.CharField(primary_key=True, max_length=100)
class Student(models.Model):
name=models.CharField(primary_key=True, max_length=100)
main_subject=models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True)
class StudentSubject(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.ForeignKey(Student, on_delete=models.CASCADE)
subject = models.ForeignKey(Discipline, on_delete=models.CASCADE)
class Meta:
constraints = [models.UniqueConstraint(fields=['name ', 'subject '], name='uniqueStudentSubject')]
forms.py
class NewStudentForm(forms.ModelForm):
class Meta:
model=Student
fields=['name', 'main_subject']
widgets={'name': forms.TextInput(), 'main_subject': forms.Select()}
subjects = forms.ModelMultipleChoiceField(
widget=forms.CheckboxSelectMultiple(),
queryset=Subject.objects.all(),
required=False
)
views.py
def new_student(request):
if request.method == 'POST':
form = NewStudentForm(request.POST)
if form.is_valid():
form.save(commit=True)
for stu in form.cleaned_data['subjects']:
StudentSubject.objects.create(
name=Project.objects.get(pk=request.POST['name']),
subject=Subject.objects.get(pk=stu)
)
# SOMETHING ELSE......... #