user2499817
user2499817

Reputation: 77

django adding fields to model form

Following is the model which I have

class OrgStaff(BaseModel):
    user = models.OneToOneField(User)
    member_type = models.BooleanField(help_text="1. Read/Write 0. Read Only")
    task = models.ForeignKey(ToDos, null=True, blank=True)
    org = models.ForeignKey(Org)
    # TODO Add possible activities

    def __unicode__(self):
        return self.user.username

Following is the forms file

class AddStaffForm(ModelForm):

    class Meta:
        model = OrgStaff
        exclude = (
            'task',
            'org'
            )

and this is how I process the view

if request.POST and form.is_valid():
    form.save()
    ret_url = reverse("some_view", kwargs={
            'var':var,})
    return redirect(ret_url)
return render(request, "form.html", {"form":form})

This form would render a dropdown, which will show all the users in the database, and a radio box.

But actually, I want to create the form, so that I can add a new user(first name, last name, username, email and password) and then the rest of the fields from the abvoe AddStaffForm.

So question basically boils down to adding fields of userform to the addstaffform. And then handling them into the views.

Is it doable, or will I have to do it manually?

Can the above model form be extended so that I can first fill in a user detail, and then assign a type to him??

Please let me know, thanks.

Upvotes: 1

Views: 2379

Answers (1)

Shrikant Joshi
Shrikant Joshi

Reputation: 76

Use two separate forms - UserForm, created out of models.User & AddStaffForm but exclude the 'user' field in the AddStaffForm. Use only ONE submit button for both.

So your template will look like:

<form method="post" action="/path/to/wherever">
    {{ user_form }}
    {{ add_staff_form }}
    <button>Submit</button>
</form>

Then, when the user submits the form, process each form independently in the following order:

  1. Process the user form first and save the user instance created by the form to the db. if user_form.is_valid() is True, you can do this by simply doing user = user_form.save()

  2. Next, process the AddStaffForm but pass commit=False (i.e. staff = add_staff_form.save(commit=False) since it does not contain the value for the user field just yet. Provide the user values using staff.user = user and then staff.save()

Provided all other fields in the staff form are provided for (i.e. add_staff_form.is_valid() is otherwise True, this should result in the creation of a new staff instance written to db.

Hope this helps. :)

Upvotes: 4

Related Questions