Browse Source

feat: Dear Diary Project - 9. Processing The Form

master
Bobson Lin 2 years ago
parent
commit
8eb56111bc
3 changed files with 16 additions and 2 deletions
  1. +7
    -0
      dear_diary/README.md
  2. +1
    -0
      dear_diary/entries/templates/entries/add.html
  3. +8
    -2
      dear_diary/entries/views.py

+ 7
- 0
dear_diary/README.md View File

@ -129,3 +129,10 @@ Creating A Form
1. Create `EntryForm` in [entries/forms.py](./entries/forms.py).
2. Use `EntryForm` in `views.add` function.
3. Use form in `add.html` template.
Processing The Form
------
1. Use `EntryForm` to handle POST request.
2. Redirect after submit form.
3. Add CSRF token in form.

+ 1
- 0
dear_diary/entries/templates/entries/add.html View File

@ -23,6 +23,7 @@
<div class="container">
<form action="{% url 'add' %}" method="post">
{% csrf_token %}
<div class="field">
<div class="control">
{{ form.text }}


+ 8
- 2
dear_diary/entries/views.py View File

@ -1,4 +1,4 @@
from django.shortcuts import render
from django.shortcuts import render, redirect
from .models import Entry
from .forms import EntryForm
@ -12,7 +12,13 @@ def index(request):
def add(request):
form = EntryForm()
if request.method == 'POST':
form = EntryForm(request.POST)
if form.is_valid():
form.save()
return redirect(to='home')
else:
form = EntryForm()
context = {'form': form}
return render(request, 'entries/add.html', context)

Loading…
Cancel
Save