Django,保存ModelForm
Django,保存ModelForm
我创建了一个名为Student的模型,它继承自Django User并作为另一个模型的外键,同时它还有一个名为year的整数字段。我尝试保存一个表单,它有两个字段。一个是课程ID,另一个是整数字段year。当我点击提交时,出现错误:无法分配"u'2'":"Student.course"必须是"Course"的实例。
models.py
class Student(models.Model): user = models.OneToOneField(User) course = models.ForeignKey(Course) year = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(7)])
view.py
def step3(request): user = request.user if request.method == 'POST': form = SelectCourseYear(request.POST) if form.is_valid(): form.save() return render_to_response("registration/complete.html", RequestContext(request)) else: form = SelectCourseYear() return render(request, 'registration/step3.html')
forms.py
class SelectCourseYear(forms.ModelForm): course = forms.CharField() year = forms.IntegerField(required=True) class Meta: model = Student fields = ['user', 'course', 'year']