Skip to content

Instantly share code, notes, and snippets.

@ehzawad
Created March 13, 2023 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehzawad/e8d2fe78649a92a36525cbd031e5d943 to your computer and use it in GitHub Desktop.
Save ehzawad/e8d2fe78649a92a36525cbd031e5d943 to your computer and use it in GitHub Desktop.
Python Session Django
# Python DJango Session
def index(request):
# check if there already exists a "tasks" key in our session
if "tasks" not in request.session:
request.session["tasks"] = []
return render(request, "tasks/index.html", {
"tasks": request.session["tasks"]
})
# Add a new task
def add(request):
if request.method == "POST":
# take in the data the user submitted and save it as form
form = NewTaskForm(request.POST)
# check if form data is valid (server-side validation)
if form.is_valid():
# Isolate the task from the 'cleaned' version of form data
task = form.cleaned_data["task"]
# Add the new task to our list of tasks
request.session["tasks"] += [task]
# Redirect user to list of tasks
return HttpResponseRedirect(reverse("tasks:index"))
else:
return render(request, "tasks/add.html", {
"form": form
})
return render(request, "tasks/add.html", {
"form": NewTaskForm()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment