使用ModelForm時,我陷入了僵局。ModelForm和相關對象問題
我是用Django自帶的extending the User model,我也使用ModelForm,因此用戶可以編輯它。
按照文檔中的相同示例,我將擁有此代碼。
models.py
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# In this case, department is optional, so I have set 'blank' and 'null' to True.
department = models.CharField(max_length=100, blank=True, null=True)
forms.py
class DepartmentForm(ModelForm):
class Meta:
model = Employee
fields = ['department',]
這個問題是在視圖。我發現我需要將模型的一個實例傳遞給窗體,所以save()函數不需要定製它,但是當然,user.employee還沒有創建,因此會引發錯誤。
views.py
def DepartmentView(request):
# Here is the issue.
department = request.user.employee
if request.method == 'POST':
# I need to pass the instance here.
form = DepartmentForm(request.POST, instance=department)
if form.is_valid():
form.save()
else:
# And also here so it autocompletes the form.
form = DepartmentForm(instance=department)
return render(request, 'employee.html', {'form': form})
它的工作原理,如果我手動添加值通過shell來user.employee.department,然後重新載入頁面,否則錯誤是如下。
RelatedObjectDoesNotExist at [something]
User has no employee.
或者類似的東西...我很抱歉,我沒有嘗試上面的代碼,這樣的錯誤可能是有點不同,但概念是完全一樣的。
我也很抱歉,如果這之前已經問過。我做了一次Google搜索,找不到這個問題的答案。
請注意,對於CharField,通常不需要具有'null = True'。如果你只有'blank = True',那麼該字段是可選的,並且當沒有給出該值時將保存空字符串''''。 – Alasdair