2

This is on Django 1.5.

I have what appears to be a simple problem, but which turned out to be really complicated in practice. So I'm working on a job application site, and I have 2 models:

  • Applicant
  • Skill

The 2 models are related through a through model, ApplicantSkillScore. So it looks something like:

class Applicant(models.Model):
    name = models.CharField(max_length=255)
    skills = models.ManyToManyField(Skills, through='ApplicantSkillScore')

class Skill(models.Model):
    name = models.CharField(max_length=255)

class ApplicantSkillScore(models.Model):
    applicant = models.ForeignKey(Applicant)
    skill = models.ForeignKey(Skill)
    score = models.FloatField(_("Score"))

Now what I want to do is to render a table-based form to enter an applicant's skill score, like this:

 -----------------------------------------------
|           |            |        |             |
| Applicant | Javascript | Python | Objective-C |
|-----------+------------+--------+-------------|
| John      |  5.0       | <Form> |    <Form>   |
| Jane      |  <Form>    | 6.7    |    <Form>   |
 -----------------------------------------------

The idea is that:

  1. The applicants and skills are derived dynamically, from the respective models. (If the skills were hard-coded fields, this would be 10000x easier.)
  2. If the applicant's skill score is present, display a prepopulated form. Otherwise, display an empty form.

Is there an elegant way in Django to render a form like this?

1 Answer 1

0

I think the way to go is to use inline formsets.

You could then render all the Applicant and their associated skill score as a formset.

  1. The applicants and skills are derived dynamically, from the respective models. (If the skills were hard-coded fields, this would be 10000x easier.)

Basically you just want to create a parent model object and its associated children (ApplicantSkillScore). That's where inline formsets are the solution because they allow you to have a view to create/modify your Applicant model and the other models linked to it with a foreign key.

  1. If the applicant's skill score is present, display a prepopulated form. Otherwise, display an empty form.

That's just a matter of rendering your forms in your templates. With the inline formsets, it will act just like a normal form and display the data if any or just an empty form. Up to you how you want to present it.

I've used this example to get started : inline formset with class based view example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.