0
我試圖創建類型爲CreateView
的視圖。此視圖將採用我創建的form_class = CourseForm
,並排除其中的一些字段。 instructor
字段是foriegnKey,我不希望用戶能夠在窗體中控制它。這是一個取決於登錄用戶的字段。Django:在創建視圖中爲ForiegnKey設置初始值
# forms.py
class CourseForm(forms.ModelForm):
class Meta:
model = Course
exclude = ['instructor', 'members', 'slug']
# ...
我的觀點如下。我認爲,當我提交
# views.py
@method_decorator(login_required, name='dispatch')
class CourseCreateView(CreateView):
model = Course
template_name = 'course_form.html'
success_url = reverse_lazy('course-create-complete')
form_class = CourseForm
def get_initial(self):
initial = super(CourseCreateView, self).get_initial()
initial = initial.copy()
profile = get_object_or_404(Profile, user__username=self.request.user)
initial['instructor'] = profile
return initial
# models.py
class Course(models.Model):
instructor = models.ForeignKey(Profile, related_name="Instructor")
# ... other fields
但萬阿英,蔣達清是通過在initial
教官值會通過配置文件實例,每當我提出我得到以下錯誤的形式:
NOT NULL constraint failed: myapp_course.instructor_id
在這種情況下,我認爲排除是更好的解決方案;否則你需要驗證用戶輸入。您的第二個解決方案因此更受歡迎。 –
...但是,我認爲你可以重寫它來設置講師_before_保存(然後返回'超(...)')。 –