Home > Blockchain >  How to use Django sessions
How to use Django sessions

Time:09-11

I'm new to Django and i'm trying to build a Todo app with user authentication but i want to add sessions to it whereby everyone can have different tasks attached to their accounts but i don't know how to go about it. I've checked the Django documentation on it but i still don't get it.

Here's my models.py

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


# Create your models here.

class Task(models.Model):
    name = models.CharField(max_length=15)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.name


class User(AbstractUser):
    name = models.CharField(max_length=200, null=True)
    email = models.EmailField(unique=True, null=True)
    bio = models.TextField(null=True, blank=True)

    USERNAME_FIELDS = "email"
    REQUIRED_FIELDS = []

Then here's my view.py

from django.shortcuts import render, redirect
from .models import Task, User
from .forms import AddTaskForm 

@login_required(login_url="loginPage")
def home(request):
    tasks = Task.objects.all()

    context = {"tasks": tasks, }
    return render(request, "task/home.html", context)


# Add task view
@ login_required(login_url="loginPage")
def addTask(request):
    addTaskForm = AddTaskForm()
    if request.method == "POST":
        addTaskForm = AddTaskForm(request.POST)
        if addTaskForm.is_valid():
            addTaskForm.save()
            return redirect('home')

    context = {"addTaskForm": addTaskForm}
    return render(request, "task/addtask.html", context)


# Update task view
@login_required(login_url="loginPage")
def update(request, pk):
    updateTask = Task.objects.get(id=pk)
    updateTaskForm = AddTaskForm(instance=updateTask)

    if request.method == "POST":
        updateTaskForm = AddTaskForm(request.POST, instance=updateTask)
        if updateTaskForm.is_valid():
            updateTaskForm.save()
            return redirect('home')

    context = {"updateTaskForm": updateTaskForm}
    return render(request, "task/update-task.html", context)



# Delete task view
@ login_required(login_url="loginPage")
def delete(request, pk):
    deleteTask = Task.objects.get(id=pk)
    if request.method == 'POST':
        deleteTask.delete()
        return redirect("home")

    context = {"deleteTask": deleteTask}
    return render(request, "task/delete-task.html", context)

CodePudding user response:

Don't need to go with sessions. You need to improve model using Django ORM.

Like:

#models.py
class User(AbstractUser):
    name = models.CharField(max_length=200, null=True)
    email = models.EmailField(unique=True, null=True)
    bio = models.TextField(null=True, blank=True)

    USERNAME_FIELDS = "email"
    REQUIRED_FIELDS = []

class Task(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASADE)
    name = models.CharField(max_length=15)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.name

While saving tasks in Task model, provide the id of the user in the user field.

CodePudding user response:

check this simple use of sessions in django :

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django import forms
from django.urls import reverse

class NewTaskForm(forms.Form) :
    task = forms.CharField(label="Add Task ")

# Create your views here.
Tasks = []

def index(request) :
    if "Tasks" not in request.session :
        request.session["Tasks"] = []
    return render(request , "tasks/index.html",{
        "tasks" : request.session["Tasks"]
    })

def add(request) : 
    if request.method == "POST" :
        form = NewTaskForm(request.POST)
        if form.is_valid() : 
            task = form.cleaned_data["task"]
            request.session["Tasks"]  = [task]
            return HttpResponseRedirect(reverse("index"))
        else : 
            return render(request , "tasks/add.html" , {
                "form" : form 
            })
    
    return render(request , "tasks/add.html" ,{
        "form" : NewTaskForm()
    })

with this method each user views their own task lists, i have a project same as what you looking for, here

  • Related