dubreakkk
dubreakkk

Reputation: 209

modifying django model forms after post

I would like to modify a user submitted form to automatically insert the project_id, but I keep getting the error that project_id in the Employee model cannot be null;

My model:

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',)

My view:

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()

Upvotes: 1

Views: 400

Answers (3)

Alasdair
Alasdair

Reputation: 308779

@maciag.artur's answer, to save with commit=False will work. Another way is to instantiate an Employee with the required project_id, and use it to construct the form.

This is useful if your model form's custom clean method relies on the Employee.project field.

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>

For reference, see the note box below Using a subset of fields on the form in the Django docs.

Upvotes: 3

Matt S
Matt S

Reputation: 1882

Add the project ID to the form as a hidden input. When the request comes back as a POST, it will exist in the POST object, from the form.

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'})

Upvotes: 1

ArturM
ArturM

Reputation: 703

Like this?

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

Upvotes: 4

Related Questions