iscream
iscream

Reputation: 790

Updating instance of model in Django

I'm a beginner and trying to make a to-do list app. I want the app to display only the tasks that have not yet been marked completed (by the user).

models.py:

class Task(models.Model):
    user        = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title       = models.CharField(max_length=50)
    description = models.TextField(blank=True, null=True)
    start_date  = models.DateTimeField()
    end_date    = models.DateTimeField()
    priority    = models.BooleanField(default=True)
    completed   = models.BooleanField(default=False)


    def __str__(self):
        return self.title

View:

def task(request):
    task = Task.objects.filter(user=request.user, completed=False)
    queryset = task.order_by('-start_date')

    context = {
        'task': queryset,
    }

    return render(request, 'task-list.html', context)

template:

{% if request.user.is_authenticated %}
    <h2>Here is the list of tasks you gotta get done:</h2>
    {% if task %}
        <ul>
        {% for obj in task %}
            <li><strong>{{ obj.title }}</strong></li>
            <p>{{ obj.description }}</p>
            <p>
                Start at: {{ obj.start_date }}
            </p>
            <p>
                end at: {{ obj.end_date }}
            </p>
        {% endfor %}
        </ul>
    {% else %}
        <p>You dont have anything on this list yet!</p>
    {% endif %}
{% else %}
    <p>Hey! Please login to check your to-do list! click <a href="{% url 'account_login' %}">here!</a></p>
{% endif %}

I want to display an option (a link/button) for the user, which upon clicking would update the instance 'completed' to True (and so the task will no longer be displayed). I would like to use an achor tag as the button. something like

<a href="{% url 'complete' id=obj.id %}">completed</a>

I have created this view:

def task_completed(request, id):
    get_task = Task.objects.filter(id=id)
    get_task.instance.completed = True

    return redirect('task:task-page')

The urls.py:

urlpatterns = [
    path('', home, name='home-page'),
    path('task', task, name='task-page'),
    path('complete', task_completed, name='complete'),
]

upon loading the task-list page, it shows

Reverse for 'complete' not found. 'complete' is not a valid view function or pattern name.

any help would be appreciated!

Upvotes: 0

Views: 38

Answers (1)

Manan M.
Manan M.

Reputation: 1394

Please try to set your url as below...

<a href="{% url 'app_name:complete' id=obj.id %}">completed</a>

And your url should be...

path('complete/<int:id>', task_completed, name='complete'),

Upvotes: 1

Related Questions