在帖子后修改django模型形式

时间:2011-09-27 16:30:23

标签: django post

我想修改用户提交的表单以自动插入project_id,但我一直得到的错误是Employee模型中的project_id不能为null;

我的模特:

class Project(models.Model):
    name = models.CharField(max_length=100)
    date_started = models.DateTimeField()

class Employee(models.Model):
    name = models.CharField(max_length=200)
    project = models.ForeignKey(Project)

class AddEmployeeForm(ModelForm):
   class Meta:
     model = Employee
     exclude = ('project',)

我的观点:

def emp_add(request, project_id):
 if request.method == 'POST':
    post = request.POST.copy() # make the POST QueryDict mutable
    post('project', project_id)
    form = AddEmployeeForm(post)
    if form.is_valid():
        saved = form.save()

3 个答案:

答案 0 :(得分:4)

喜欢这个吗?

if form.is_valid():
    employee = form.save(commit=False)
    employee.project = Project.objects.get(pk=project_id)
    employee.save()

答案 1 :(得分:3)

@ maciag.artur的答案,与commit=False一起保存将起作用。另一种方法是使用所需的project_id实例化Employee,并使用它来构造表单。

如果模型表单的自定义清理方法依赖于Employee.project字段,这将非常有用。

def emp_add(request, project_id)
    if request.method == 'POST':
        # create a new employee with the given project id
        employee = Employee(project_id) = project_id
        form = AddEmployeeForm(request.POST, instance=employee)
        if form.is_valid():
            saved = form.save()
        <snip>

供参考,请参阅Django文档中Using a subset of fields on the form下面的注释框。

答案 2 :(得分:1)

将项目ID作为隐藏输入添加到表单。当请求作为POST返回时,它将存在于POST对象中,来自表单。

def emp_add(request, project_id):
 if request.method == 'POST':
    post = request.POST.copy() # make the POST QueryDict mutable
    post('project', project_id)
    form = AddEmployeeForm(post)
    if form.is_valid():
        saved = form.save()
 else:
    form = AddEmployeeForm(initial={'project_id':'my_id_value'})