ModelForm和相关对象的问题

时间:2016-03-21 22:44:45

标签: python django

使用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.

或类似的东西......对不起,我没有尝试上面的代码,所以错误可能会有所不同,但概念完全相同。

如果之前有人问我,我也很抱歉。我进行了谷歌搜索,无法找到这个问题的答案。

1 个答案:

答案 0 :(得分:0)

您可以使用get_or_create从数据库中获取员工,如果不存在则创建员工。

department, created = Employee.objects.get_or_create(user=request_or_user, department='')
if request.method == 'POST':
    form = DepartmentForm(request.POST, instance=department)
    ...

另一种选择是使用信号,以便在创建用户时创建相关模型。然后,您可以假设员工已经存在,您可以使用request.user.employee代替get_or_create