Python Django: Getting output as "task object(1)" instead of actual value in model table

Viewed 453

I am pretty new to django. I am trying to create a simple task management app and I created a class Taskdb in model.py. The problem I am facing that I am getting output like task object(1) instaed of actual value that I put in task field. Please look into my files below (model.py and view.py) and let me know where I am going wrong.

Models.py

from django.db import models
from django.utils import timezone


class Taskdb(models.Model):
    task = models.CharField(max_length = 30)
    priority = models.CharField(max_length = 30)
    completed = models.BooleanField(default=False)
    time_date = models.DateTimeField(default=timezone.now)


def __str__(self):
    return "%s %s"%(self.task, self.completed)

Views.py

from django.shortcuts import render, redirect
from .forms import UserRegisterForm
from .models import Taskdb


def home(request):
    return render(request, 'index.html')

def task(request):
    all_items = Taskdb.objects.all()
    return render(request, 'task.html', {'all_items': all_items})

task.html

{% extends 'base.html' %} {% block body %}
<h2>My Task</h2>
<h4>Welcome {{ user.username }}!</h4>
<h3>Your task list.</h3>
{% for task in all_items %}
<p>{{ task }}</p>
{% endfor %} {% endblock %}

Output:

Screen shot of Task.html web page

admin site: Screen shot of admin site of the app

1 Answers

In your django model's class, you have this, which is correct:

 def __str__(self):
    return "%s %s"%(self.task, self.completed)

That will return whatever you want in the Django admin (in the case above, it will return whatever is in the Task and Completed columns for that row).

In your code above, however, the __str__ is not indented enough so it is not part of the class for that model. Make sure you properly indent it. So, it should look like this:

class Taskdb(models.Model):
    task = models.CharField(max_length = 30)
    priority = models.CharField(max_length = 30)
    completed = models.BooleanField(default=False)
    time_date = models.DateTimeField(default=timezone.now)


    def __str__(self):
        return "%s %s"%(self.task, self.completed)

There are also other attributes you can put in the model's Meta class to change they way things display in the Djang admin.

For more information: https://www.geeksforgeeks.org/customize-django-admin-interface/

Related