我有2个模特'学生'和'Abc'。
class Abc(models.Model):
student = models.ForeignKey(Student)
name = models.CharField(max_length=10)
nickname = models.CharField(max_length=20)
ClassAbcForm(forms.ModelForm):
class Meta:
model = Student
fields = ('name', 'nickname') # Note that I didnt include student field.
我没有包含'student'字段,因为可以通过视图填充。用户应该只是 输入'name'和'nickname'字段。因此,我通过设置Meta类中的“fields”仅包含要在表单中显示的那些字段。
我在视图中尝试如下:
student = student_instance
student_id = id
但是,得到了错误。
如果我将'student'添加到表单中的字段,那么它工作正常。什么是解决方案?
答案 0 :(得分:0)
ClassAbcForm(forms.ModelForm):
class Meta:
model = Abc //should be Abc not Student
fields = ('name', 'nickname')
def view_name(request):
student = Student(student_id=student_id) //define first student here
if request.method == 'POST':
form = ClassAbcForm(request.POST, instance=student)
if form.is_valid():
form.save()
................