如何将pk从ModelForm传递给DetailView?

时间:2017-08-15 21:06:05

标签: django django-views

我正在使用ClassroomCreateView来选择课堂。然后我想显示使用ClassroomDetailView选择的教室。这将显示该课堂中的学生列表。我想我应该能够使用pk并从ModelForm遍历到DetailView。

课堂模型

class Classroom(models.Model):
    BLOCK_NUMBER = (
        ('11', 'Block 1-1'),
        ('12', 'Block 1-2'),
        ('13', 'Block 1-3'),
        ('14', 'Block 1-4'),
        ('21', 'Block 2-1'),
        ('22', 'Block 2-2'),
        ('23', 'Block 2-3'),
        ('24', 'Block 2-4'),
    )
    class_list = models.TextField()
    course_block = models.CharField(max_length=10, choices=BLOCK_NUMBER)

    def __str__(self):
        return self.get_course_block_display()

    def save(self, *args, **kwargs):
        super(Classroom, self).save(*args, **kwargs)
        # overrides the default save function to parse the class list
        studentList = []
        studentList = self.class_list.split('\n')
        print (studentList)
        for line in studentList:
            line = line.strip('\r')
            s = Student.objects.create(nickname = line, classroom = self)

学生模特

class Student(models.Model):
    classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE)
    nickname = models.CharField(default='JohnS', max_length=31)

Forms.py

class AttendForm(ModelForm):
    class Meta:
        model = Classroom
        fields = ['course_block']

    def __init__(self, *args, **kwargs):
        super(AttendForm, self).__init__(*args, **kwargs)

Views.py

class AttendCreateView(CreateView):
    model = Classroom
    form_class = AttendForm
    template_name = 'classroom/attend_form.html'

    def get_success_url(self):
        return reverse('classroom:random', self.kwargs['pk'])

create_attendance_view = AttendCreateView.as_view()

我认为这是我失踪的部分。 course_block有一个pk,但我没有将它从表单传递到视图。

class ClassroomDetailView(DetailView):
    model = Classroom
    template_name = 'classroom/random_list.html'

    def get_context_data(self, **kwargs):
        class_pk = self.kwargs['pk']
        context = super(ClassroomDetailView, self).get_context_data(**kwargs)
        students = Student.objects.filter(pk = 'class_pk')
        context['students'] = students
        return context

detail_classroom_view = ClassroomDetailView.as_view()

urls.py

url(r'^classup/$', create_classroom_view, name='classroom'),
url(r'^attend/$', create_attendance_view, name='students'),
url(r'^(?P<pk>[0-9]+)/$', detail_classroom_view, name='random'),

如何从表单选择转到详细视图(可能使用选择的pk)?

0 个答案:

没有答案