我使用ClassroomCreateView
來選擇一個教室。然後我想顯示使用ClassroomDetailView
選擇的教室。這將顯示該教室中的學生名單。我想我應該可以使用pk並從ModelForm到DetailView進行遍歷。如何將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)?
顯示你的'urls.py',即'教室:隨機'是什麼。另外,發生了什麼?你會得到一個錯誤,模板中有錯誤的鏈接,還有其他的東西嗎? –
上面編輯顯示urls.py。當我使用self.object.id時,在AttendCreateView上提交AttendForm後,ClassroomDetailView中的id#會自動增加。即.../45 /然後/ 46 /等等。我在ClassroomDetailView中打印了一個print語句來打印self.kwargs ['pk'],它會打印出「none」。沒有任何錯誤。 –
好吧,只有現在我明白你想要做什麼。它實際上非常類似於[今日堆棧溢出的前一個問題](https://stackoverflow.com/questions/45699023/displaying-other-attribute-values-if-one-is-known-in-django-template/45699325 ),但是她正在使用基於函數的視圖('index'),您正試圖使用'CreateView'。我同意你對評論的回答,如果我使用基於類的視圖,那麼我將使用[FormView](https://docs.djangoproject.com/en/1.11/ref/class-based-意見/通用編輯/#FormView控件)。 –