I have the following models: Department, Projects, Departmentprojects, Employees, and Membership. A Department has many Projects and Projects have many Employees that are assigned roles through Membership. I am trying to create a InlineFormset so that an EU can assign an Employee's role to multiple projects.
My template renders the right labels and fields, but the Departmentprojects labels and fields don't show the name of the projects. It only shows "Departmentprojects object". How can I get the form to render the name of the project instead of "Departmentprojects object"?
--
Current Template in Browser:
Departmentproject label: (drop down menu with two options listed as "Departmentprojects object") Role: Project Manager
Desired Template in Browser:
Departmentproject name 1: Project Manager
Departmentproject name 2: Some other role
--
MODELS:
class Projects(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Department(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Employees(models.Model):
name = models.CharField(max_length=15)
def __unicode__(self):
return self.name
class Departmentprojects(models.Model):
department = models.ForeignKey(Department)
projects = models.ForeignKey(Projects)
members = models.ManyToManyField(Employees, through='Membership')
class Membership(models.Model):
departmentprojects = models.ForeignKey(Departmentprojects)
employees = models.ForeignKey(Employees)
role = models.CharField(max_length=20)
--
VIEW
def addtoprojects(request, employees_id):
e = get_object_or_404(Employees, pk=employees_id)
ProjectsInlineFormSet = inlineformset_factory(Employees, Membership, max_num=1)
if request.method == "POST":
formset = ContactInlineFormSet(request.POST, instance=e)
if formset.is_valid():
formset.save()
else:
formset = ProjectsInlineFormSet(instance=e)
return render_to_response('gcstest/contact.html', {'e': e, 'formset': formset}, context_instance=RequestContext(request))
--
TEMPLATE
<form method="post" action="/assign_to_project/{{ employees.id }}/">
{% csrf_token %}
<table>
{{ formset }}
</table>
<input type="submit" value="Submit"/>
</form>
Add a __unicode__
method to your Departmentprojects
model e.g.
class Departmentprojects(models.Model):
department = models.ForeignKey(Department)
projects = models.ForeignKey(Projects)
members = models.ManyToManyField(Employees, through='Membership')
def __unicode__(self):
return "%s > %s" % (self.department, self.projects)