I have a Detail
Model that has ForeignKey
of User
Model. I also have a UpdateStudentDetailForm
ModelForm that is based on Detail
model but also has an extra field that is a dropdown list of users (students), I use this ModelForm use to take input from a current user (teacher). User (teacher) select a user (student) from the dropdown list, fill other fields and submit the form. Now, I want that submitted data to be saved in Detail
Model of the user (student) that was selected by user (teacher). What should I do in my views.py
in order to accomplish this?
My Detail
Model in models.py is below:
class Detail(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=50)
skype_session_attendance = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(20)], verbose_name="Skype Session Attendances (of this subject, in numbers)", help_text="Enter the numbers of skype sessions of this subject, the student attended out of 20.")
internal_course_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(40)], verbose_name="Internal Course Marks (of this subject, in numbers)", help_text="Enter the total internal course marks of this subject, the student obtained out of 40.")
programming_lab_activity = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(25)], verbose_name="Programming Lab Activities (of this subject, in numbers)", help_text="Enter the total numbers of programming lab activities of this subject, the student participated in, out of 25.")
mid_term_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(45)], verbose_name="Mid_Term Marks (of this subject, in numbers)", help_text="Enter the total mid-term marks of this subject, the student obtained out of 45.")
final_term_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(90)], verbose_name="Final_Term Marks (of this subject, in numbers)", help_text="Enter the total final-term marks of this subject, the student obtained out of 90.")
def __str__(self):
return f'{self.user.username}-{self.subject}'
My UpdateStudentDetailsForm
in forms.py is below:
STUDENTS_LIST = []
for usr in User.objects.all():
if not usr.is_staff and not usr.is_superuser:
STUDENTS_LIST.append(str(usr.first_name + ' ' + usr.last_name + ' - ' + usr.username))
class UpdateStudentDetailsForm(forms.ModelForm):
stds = forms.CharField(widget=forms.Select(choices=STUDENTS_LIST), label='Select a Student')
class Meta:
model = Detail
fields = ['stds', 'subject', 'skype_session_attendance', 'internal_course_marks', 'programming_lab_activity', 'mid_term_marks', 'final_term_marks']
You should try:
user = models.OneToOneField(User, on_delete=models.CASCADE)
in your Detail model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.