且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django,保存ModelForm

更新时间:2023-11-30 15:00:04

如果您已经在字段中提到过,您不需要重新定义 ModelForm 中的字段属性。所以你的表单应该这样 -

You dont need to redefine fields in the ModelForm if you've already mentioned them in the fields attribute. So your form should look like this -

class SelectCourseYear(forms.ModelForm):
    class Meta:
        model = Student
        fields = ['course', 'year'] # removing user. we'll handle that in view

我们可以在视图中轻松处理表单 - p>

And we can handle the form with ease in the view -

def step3(request):
    user = request.user
    if request.method == 'POST':
        form = SelectCourseYear(request.POST)
        if form.is_valid():
            student = form.save(commit=False)
            # commit=False tells Django that "Don't send this to database yet.
            # I have more things I want to do with it."

            student.user = request.user # Set the user object here
            student.save() # Now you can send it to DB

            return render_to_response("registration/complete.html", RequestContext(request))
    else:
        form = SelectCourseYear()
    return render(request, 'registration/step3.html',)