Umar Milanzi Snr
Umar Milanzi Snr

Reputation: 97

Displaying tasks under specific project in django

HI I am currently trying to develop a project management system. I am stuck at showing tasks related to a particular project when I view project details

model.py looks like this

class Project(models.Model):
    name        = models.CharField(max_length=50)
    start_date  = models.DateField(default=date.today)
    due_date    = models.DateField(default=date.today)
    progress    = models.CharField(max_length=20, choices=progress)
    status      = models.CharField(max_length=20, choices=status)
    priority    = models.CharField(max_length=20, choices=priority)

    def __str__(self):
        return self.name

    def total_projects(self):
        return Project.objects.all().count()

    def get_absolute_url(self):
        return reverse('projects:project_list')


class Task(models.Model):
    title       = models.CharField(max_length=50)
    project     = models.ForeignKey(Project, related_name="tasks", on_delete=models.CASCADE)
    priority    = models.CharField(max_length=20, choices=priority)
    status      = models.CharField(max_length=20, choices=status)
    assigned    = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return '%s - %s' % (self.project.name, self.title)

    def get_absolute_url(self):
        return reverse('projects:add_task')

views.py looks like this

class ProjectListView(ListView):
    model = Project
    template_name = 'projects/project_list.html'


class ProjectDetailView(DeleteView):
    model = Project
    template_name = 'projects/project_detail.html'

    def get_context_data(self, *args, **kwargs):
        projects = Project.objects.order_by('id')
        context = super(ProjectDetailView, self).get_context_data(*args, **kwargs)

        context["projects"] = projects
        return context

I have tried searching the net, nothing is clear

Upvotes: 0

Views: 204

Answers (1)

Tom Hamilton Stubber
Tom Hamilton Stubber

Reputation: 767

Okay so a couple of things here.

You've created a ForeignKey relation between the Product and Tasks objects, so you can just do product.tasks.all().

You've slightly messed up the view though. You should be inheriting from DetailView, not DeleteView, and then you'll have access to the object in the context.

For example:

views.py

class ProjectDetailView(DetailView):
    model = Project
    template_name = 'projects/project_detail.html'

projects/project_detail.html

...
{% for task in object.tasks.all() %}
   <li>{{ task }}</li>
{% endfor %}

Upvotes: 1

Related Questions