Django:如何将外键添加到依赖表单,添加到多表单?

时间:2018-01-04 11:06:15

标签: django python-3.x django-forms django-views

原谅下面示例表结构的逻辑。它只是我的情况的一个简单例子。

所以情况是我想创建一个员工表单页面,部门和直线经理可能已经存在或可能不存在。因此,我将下拉框替换为外键的表单字段,因此如果需要为用户一步完成,则可以创建它们。然而,由于这种依赖性,我没有做正确的事情以使其工作。

如果您需要更多细节,请询问。

如果你能使标题更精确,请做。

感谢您的时间。

模型

class Employee(models.Model):
    name = models.CharField()
    age = models.CharField()
    line_manager = models.ForeignKey(LineManager)
    department = models.ForeignKey(Department)

class LineManager(models.Model):
    manager_name = models.CharField()
    department = models.ForeignKey(Department)

class Department(models.Model):
    department_name = models.CharField()

表格

class EmployeeForm(ModelForm):
    class Meta:
        model = Employee
        fields = ['name',
                  'age'
                  #'line_manager' Not needed
                  #'department' Not needed]
        exclude = ('line_manager', 'department')

class LineManagerForm(ModelForm):
    class Meta:
        model = LineManager
        fields = ['manager_name']
        exclude = ('department') 

 # There is a basic form for Department, as well.

查看

class AddEmployeeView(View):
    forms = {'department': DepartmentForm(self.request.POST or None),
             'line_manager': LineManagerForm(self.request.POST or None),
             'employee': EmployeeForm(self.request.POST or None)]}

    def get(self, request, *args, **kwargs):
        form_list = [form for _,form in forms]
        return render (request, 'app/temp.html', {'forms': form_list}

    def post(self, request, *args, **kwargs):
        if all([form.is_valid() for _,form in forms]):
            department_data = forms['department'].cleaned_data
            department_obj, _ = Department.objects.get_or_create(department_data)

            line_manager_instance = forms['line_manager'].instance
            line_manager_instance.department = department_obj
            line_manager_data = forms['line_manager'].cleaned_data
            line_manager_obj, _ = LineManager.objects.get_or_create(line_manager_data)

            employee_instance = forms['employee'].save(commit=False)
            employee_instance.department = department_obj
            employee_instance.line_manager = line_manager_obj
            employee_instance.save()

HTML

<form method="POST">
    {% csrf_token %}
    {% form in forms %}
        {{ form.as_p }}
    {% endform %}
<input type='submit'/>
</form>

0 个答案:

没有答案