【发布时间】:2023-03-29 23:40:01
【问题描述】:
我有一个 Detail 模型,它具有 ForeignKey 或 User 模型。我还有一个基于Detail 模型的UpdateStudentDetailForm ModelForm,但还有一个额外的字段是用户(学生)的下拉列表,我使用这个ModelForm 用于从当前用户(老师)那里获取输入。用户(教师)从下拉列表中选择用户(学生),填写其他字段并提交表格。现在,我希望将提交的数据保存在用户(老师)选择的用户(学生)的Detail 模型中。我应该在我的views.py 中做什么才能完成此操作?
models.py 中我的Detail 模型如下:
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}'
forms.py 中我的UpdateStudentDetailsForm 如下:
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']
【问题讨论】:
标签: python django django-forms modelform