我如何在Django中具有用户模型外键的模型中保存ModelFrom数据?

问题描述 投票:0回答:1

我有一个Detail模型,它的ForeignKeyUser模型。我也有一个基于UpdateStudentDetailForm模型的Detail 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']

我有一个具有用户模型的ForeignKey的详细模型。我也有一个基于Detail模型的UpdateStudentDetailForm ModelForm,但还有一个额外的字段,它是用户的下拉列表(...

python django django-forms modelform
1个回答
0
投票

您应该尝试:

© www.soinside.com 2019 - 2024. All rights reserved.