Created
March 13, 2023 09:13
-
-
Save ehzawad/e8d2fe78649a92a36525cbd031e5d943 to your computer and use it in GitHub Desktop.
Python Session Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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