如何构建依赖于另一个模型的formset?

时间:2018-03-01 17:22:30

标签: python django

所以我基本上有三个模型:FileUpload,Lecture和Course。我想知道如何构建一个formset,对于课程中的任何讲座,我可以允许学生上传文档。我尝试了一些东西,但我只设法显示FileUpload字段。此外,教师有其特定的课程。这是我试过的:

#models.py

class Lecture(models.Model):
    LECTURE_CHOICES = (
        ('Courses', 'Courses'),
        ('Seminars', 'Seminars'),
    )
    course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures', )
    lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses', )
    lecture_title = models.CharField(max_length=100, blank=True, null=True)
    content = models.TextField(blank=False, default=None)

    def __str__(self):
        return str(self.lecture_title)


class FileUpload(models.Model):
    files = models.FileField(upload_to='documents', null=True, blank=True)
    lecture = models.ForeignKey('Lecture', related_name='files', on_delete=None, default=None)

    def __str__(self):
        return str(self.files)

#forms.py

class LectureForm(forms.ModelForm):
    lecture_title = forms.CharField(max_length=100, required=True)
    course = forms.ChoiceField()

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super().__init__(*args, **kwargs)
        self.fields['course'].choices = self.get_courses(user)

    @staticmethod
    def get_courses(teacher):
        teacher_data = TeacherData.objects.get(teacher_ID=teacher.teacher_ID)
        return [(x.id, x.name) for x in Course.objects.filter(Q(teacher1=teacher_data)
                                                              | Q(teacher2=teacher_data))]

    def clean_course(self):
        course_id = self.cleaned_data.get('course')
        course_obj = Course.objects.get(pk=course_id)
        return course_obj

    class Meta:
        model = Lecture
        fields = ('course', 'lecture_category', 'lecture_title', 'content')

class FileForm(forms.ModelForm):
    class Meta:
        model = FileUpload
        fields = ('files',)

#views.py

FileFormset2 = inlineformset_factory(Lecture, FileUpload, fields=('lecture',))

 formset = FileFormset2(request.POST, request.FILES, prefix='files')
        if formset.is_valid():
            formset.save()
        return redirect('classroom')

#classroom.html

<form method="post" action="" enctype=multipart/form-data>
                {% csrf_token %}
                {{ formset.management_form }}
                {% for form in formset %}
                    {{ form }} <br>
                {% endfor %}
                <br>
                <button type="submit">Add Upload</button>
            </form>

1 个答案:

答案 0 :(得分:1)

您只显示表单集。您还需要包含LectureForm