Django, save ModelForm

前端 未结 2 1953
慢半拍i
慢半拍i 2020-12-13 02:51

I have created a model Student which extends from the Django User and is a foreign key to another model while it has an integer field calle

2条回答
  •  情歌与酒
    2020-12-13 03:05

    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
    

    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',)
    

提交回复
热议问题