User Specific Page in TODO List

I am making a simple todolist application but while I am trying to create user specific pages, I am unable to add a new task probably beacause database is not getting all required datas(i.e. owner of the task).

models.py

 from django.db import models
 from django.contrib.auth.models import User

 # Create your models here.

 class value(models.Model):
     task=models.CharField(max_length=200)
     complete=models.BooleanField(default=False)
     created=models.DateTimeField(auto_now_add=True)
     owner=models.ForeignKey(User,on_delete=models.PROTECT)

     def __str__(self):
         return self.task        

views.py

 from http.client import HTTPResponse
 from urllib import response
 from django.shortcuts import render,redirect
 from todo.models import value
 from django.http import HttpResponseRedirect
 from django.contrib.auth.decorators import login_required
 from django.contrib.auth.models import User
 # Create your views here.
 from .forms import TitleForm
 from django.urls import reverse
 from django.contrib.auth.models import User






def home(request):
    values=value.objects.all()    
    form=TitleForm()
    if request.method=='POST':
         form=TitleForm(request.POST)
         if form.is_valid():
             new_data=form.save(commit=False)
             new_data.owner=request.user()
             new_data.save()
         return HttpResponseRedirect('/')
    context={'form':form,'values':values}
    return render(request,'home.html',context)

#update

def update(request,id):

    ggwp=value.objects.get(id=id)
    form=TitleForm(instance=ggwp)
    if request.method == 'POST':
          form=TitleForm(request.POST,instance=ggwp)
          if form.is_valid:
             form.save()
             return redirect('home')
    context={'form':form,}
    return render(request,'update.html',context)




#delete

def delete_data(request, id ):
    if request.method=="POST":
        ggwp=value.objects.get(id=id)
        ggwp.delete()
        return HttpResponseRedirect(reverse('deldata', kwargs={'id':id}))
    return redirect("/")

forms.py

from django import forms
from django.forms import ModelForm
from .models import value
from django import forms

class TitleForm(forms.ModelForm):
    class Meta:
       model= value
       fields='__all__'

urls.py(app)

from django.conf.urls import url
from django.urls import path
from . import views


urlpatterns=[
    path('',views.home,name='home'),
    path('delete/<str:id>', views.delete_data,name='deldata'),
    path('update/<str:id>',views.update,name='update')
]

home.html(main page)

<form method="POST">
  {% if user.is_authenticated %}
  Hello,{{user.username}}<br>
  <a href="accounts/logout">Logout</a>
  {% else%}
  <a href="accounts/register">Register</a>
  <a href="accounts/login1">login</a>
  {% endif %}
</form>

<div class="p-3 mb-2 bg-warning text-dark" style="text-align: center;">

<form action="/" method="post" >
    {% csrf_token %} 
    {{form.task}}
     <input class='btn btm-sm btn-info' type='submit' name='add' value="add" > 
</form>


{% for val in values %}
    
    {% if val.complete == True %}
    <s>{{val}}</s>
    {% else %}
    <span>{{val}}</span>
    {% endif %}
    
    <form action="{% url 'deldata' val.id %}" method="POST" class="in-line">
        {% csrf_token %}
        <input class='btn btm-sm btn-danger' type="submit" name="delete" value="delete">
        <a  class='btn btm-sm btn-info' href="{% url 'update' val.id %}" >Update</a>
    </form>
    
 {% endfor %}
</div>

Home.html looks like this: todo

When i want to add a task and click on add, nothing really happens. It only redirects back to same page but not data is inserted in database. If there are problems in questions, I am really sorry!

1 answer

  • answered 2022-01-18 04:38 SANGEETH SUBRAMONIAM

    Home.html :

    <div class = "divname">
    
      {% if user.is_authenticated %}
          Hello,{{user.username}}<br>
          <a href="accounts/logout">Logout</a>
      {% else%}
          <a href="accounts/register">Register</a>
          <a href="accounts/login1">login</a>
      {% endif %}
    
    </div>
    
    <div class="p-3 mb-2 bg-warning text-dark" style="text-align: center;">
    
    <form method="POST" >
        {% csrf_token %} 
        {{form}}
         <input class='btn btm-sm btn-info' type='submit' name='add' value="add" > 
    </form>
    
    
    {% for val in values %}
        
        {% if val.complete == True %}
        <s>{{val}}</s>
        {% else %}
        <span>{{val}}</span>
        {% endif %}
        
        <form action="{% url 'deldata' val.id %}" method="POST" class="in-line">
            {% csrf_token %}
            <input class='btn btm-sm btn-danger' type="submit" name="delete" value="delete">
            <a  class='btn btm-sm btn-info' href="{% url 'update' val.id %}" >Update</a>
        </form>
        
     {% endfor %}
    </div>
    
    • UPDATE1 : EXCLUDING USER IN FORM AND ADDING THE CURRENT USER IN VIEWS

    #Do not add Owner into the model form fields

    forms.py:

    from django import forms
    from django.forms import ModelForm
    from .models import value
    from django import forms
    
    class TitleForm(forms.ModelForm):
        class Meta:
           model= value
           fields=['task', 'complete', 'created']
    

    Views.py:

    def home(request):
        values=value.objects.all()    
        form=TitleForm()
        if request.method=='POST':
             form=TitleForm(request.POST)
             if form.is_valid():
                 new_data=form.save(commit=False)
                 new_data.owner=request.user
                 new_data.save()
             return HttpResponseRedirect('/')
        context={'form':form,'values':values}
        return render(request,'home.html',context)
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum