我正在如下所示的模型中创建对象。我想要做的是使用UpdateView更新“ class_list”。该更新似乎回溯到我对象的模型窗体,该模型窗体中包含一个干净的例程,这会导致问题。
class ClassroomForm(ModelForm):
class Meta:
model = Classroom
fields = ['course_name', 'course_block','class_list']
def clean(self):
try:
Classroom.objects.get(course_block=self.cleaned_data['course_block'])
self.redirect = True
raise forms.ValidationError("Exists already")
except Classroom.DoesNotExist:
pass
return self.cleaned_data
我现在正在为同一模型实现UpdateView。视图很简单:
class BlockUpdateView(UpdateView):
model = Classroom
fields = ['class_list']
success_url = reverse_lazy('classroom:blocklist')
update_classroom_view = BlockUpdateView.as_view()
这是从下面的模板代码调用的:
{% for block in classroom_blocks %}
<li>{{ block.get_course_block_display }}<a href ="{% url 'classroom:blockUpdate' block.id %}" class="button">EDIT</a><a href ="{% url 'classroom:blockDelete' block.id %}" class="button">DELETE</a></li>
{% empty %}
<li>No classes set up yet.</li>
{% endfor %}
我成功进入了可以更新模型的视图。进行编辑后,按Submit
,然后出现以下错误:
Exception Type: KeyError
Exception Value: 'course_block'
Exception Location: C:\Users\dwsmith\mysite\classroom\models.py in clean, line 59
line 59: Classroom.objects.get(course_block=self.cleaned_data['course_block'])
我想知道在这种情况下是否以及如何使用UpdateView。但是,情况还有一个问题。 “ class_list”是我随后解析并迭代以在Student类中创建新对象的名称的列表。由于我正在编辑class_list并提交新列表,因此我认为可能必须先删除所有现有的Student对象,然后再通过分析已编辑的class_list创建新的Student对象。下面显示了“课堂”和“学生”模型以及我如何解析class_list。
class Classroom(models.Model):
COURSE_NAME = (
('MA8', 'Math 8'),
('SC10', 'Science 10'),
('PH11', 'Physics 11'),
('PH12', 'Physics 12'),
)
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_name = models.CharField(max_length=20, choices=COURSE_NAME)
course_block = models.CharField(max_length=10, choices=BLOCK_NUMBER)
group_size = models.IntegerField(default=3)
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')
for line in studentList:
line = line.strip('\r')
s = Student.objects.create(nickname = line, attend = True, classroom = self)
class Student(models.Model):
classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE)
student_first = models.CharField(default='John', max_length=30)
student_last = models.CharField(default='Smith', max_length=30)
nickname = models.CharField(default='JohnS', max_length=31)
attend = models.BooleanField(default=True)
I have a 35 second view that shows the use and intended use of UpdateView.