Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Django Forms
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Tzu-ping Chung
February 23, 2016
Programming
280
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Django Forms
Introduction to Django Forms for Django Girls × Taipei.py workshop.
Tzu-ping Chung
February 23, 2016
Transcript
32 slides
Django Forms
Django Forms • Forms? • Forms! • Model forms
Web Page
Web Page with Form submit
<form action="/path/to/send" method="POST" enctype="multipart/form-data"> <!-- form content --> <input type="submit">
</form>
None
<form action="/path/to/send" method="post" enctype="multipart/form-data"> • Where to send • URL
• Default: "" (current URL)
<form action="/path/to/send" method="post" enctype="multipart/form-data"> • How to send • Either
get or post • Get: postcard • Post: Enveloped • Default: get
<form action="/path/to/send" method="post" enctype="multipart/form-data"> • How to read • application/x-www-form-urlencoded
• Default • multipart/form-data • Form contains file
GET Submission Query string
POST Submission "GET /admin/ HTTP/1.1" 302 0 "GET /admin/login/?next=/admin/ HTTP/1.1"
200 1679 "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 "GET /admin/ HTTP/1.1" 200 3407
<form action="/path/to/send" method="POST" enctype="multipart/form-data"> <!-- form content --> <input type="submit">
</form>
<input type="submit"> <button type="submit"> Submit </button>
<input type="submit"> <button type="submit"> Submit </button>
<form action="/path/to/send" method="POST" enctype="multipart/form-data"> <!-- form content --> <input type="submit">
</form>
Django Forms!
Models Database Django forms HTML forms
from django import forms class MessageForm(forms.Form): name = forms.CharField( max_length=100,
) title = forms.CharField( max_length=100, required=False, ) content = forms.CharField( widget=forms.Textarea, )
from .forms import MessageForm def message_board(request): form = MessageForm() return
render( request, 'message_board.html', {'form': form}, )
<form method="post"> {% csrf_token %} {{ form.as_p }} <button>ૹग़</button> </form>
<form method="post"> {% csrf_token %} {{ form.as_p }} <button>ૹग़</button> </form>
?
CSRF Token • Cross Site Request Forgery protection • “Recognise”
whether a form is legit • Protect the server from malicious changes
None
None
class Message(models.Model): name = models.CharField( max_length=100, ) title = models.CharField(
max_length=100, blank=True, ) content = models.TextField() created_at = models.DateTimeField( auto_now_add=True, )
class Message(models.Model): name = models.CharField( max_length=100, ) title = models.CharField(
max_length=100, blank=True, ) content = models.TextField() created_at = models.DateTimeField( auto_now_add=True, )
class MessageForm(forms.Form): # ... def save(self): data = self.cleaned_data message
= Message( name=data['name'], title=data['title'], content=data['content'], ) message.save() return message
class MessageForm(forms.Form): # ... def save(self): data = self.cleaned_data message
= Message( name=data['name'], title=data['title'], content=data['content'], ) message.save() return message
def message_board(request): if request.method == 'POST': form = MessageForm(request.POST) if
form.is_valid(): form.save() else: form = MessageForm() return render( request, 'message_board.html', {'form': form}, )
Further Reading • Model forms • Form factories • Custom
“cleaning”
Exercises • Implement message form • Implement message model, save
POST-ed form to it • Get messages from database • Display messages in template
Hint {% for m in messages %} <div class="message"> <p>{{
m.name }}</p> <h5>{{ m.title }}</h5> <div>{{ m.content|linebreaks }}</div> </div> {% endfor %} Message.obejcts.order_by('-created_at')
More Decks by Tzu-ping Chung
See All by Tzu-ping Chung
Datasets: What it is, and how it was made
uranusjr
0
240
Let’s fix extras in Core Metadata 3.0
uranusjr
0
730
Python Packaging: Why Don’t You Just…?
uranusjr
1
300
這樣的開發環境沒問題嗎?
uranusjr
9
2.8k
Django After Web 2.0
uranusjr
3
2.3k
We Store Cheese in A Warehouse
uranusjr
1
510
The Python You Don’t Know
uranusjr
17
3.4k
Python and Asynchrony
uranusjr
0
450
Graphics on Raspberry Pi with Qt 5
uranusjr
0
96k
Other Decks in Programming
See All in Programming
AI時代のTerminal環境を UNIX哲学で設計・運用する
yasunori0418
1
360
Goコンパイラを作ってGoをもっと理解する / Build a Go compiler to better understand Go
ikura_hamu
0
130
作れるエンジニアから、価値を届けるエンジニアへ
ryunakayama
1
310
どうしても Eloquent でリポジトリパターンをやりたいんだ #phpcon_niigata / phpcon-niigata-2026
shogogg
0
610
LLM 101: Exploring LLMs, Starting with Tokens.
dalinaum
0
110
Enforcing Your Architecture with Unit Tests in the AI Era (Swift Connection X)
steliosf
PRO
1
190
React Native에 현대적인 빌드 도구 더하기: Rollipop 구현기
leegeunhyeok
0
180
느린 네트워크와 저사양 디바이스 사용자를 위한 웹뷰 로딩 시간 개선기
kmkim
1
240
Growing PicoRuby's Ecosystem on ESP32
yuuu
2
140
AIコーディング時代のKotest ユニットテストから APIレベルの仕様固定化テストへ
ooga04
0
270
Web3Dライブラリを作ってVue Custom Rendererの仕組みを理解しよう / lets learn vue custom renderer by making 3d library
drumath2237
1
140
社内AIエージェント「Askワンバン」における コストチューニングの取り組み
t0yohei
0
170
Featured
See All Featured
Why Mistakes Are the Best Teachers: Turning Failure into a Pathway for Growth
auna
0
360
The Language of Interfaces
destraynor
162
27k
The Director’s Chair: Orchestrating AI for Truly Effective Learning
tmiket
1
350
Visualizing Your Data: Incorporating Mongo into Loggly Infrastructure
mongodb
50
10k
Unsuck your backbone
ammeep
672
58k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
360
31k
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
12
1.4k
AI Search: Implications for SEO and How to Move Forward - #ShenzhenSEOConference
aleyda
1
1.4k
Rebuilding a faster, lazier Slack
samanthasiow
85
9.8k
Practical Orchestrator
shlominoach
192
12k
How Software Deployment tools have changed in the past 20 years
geshan
3
35k
Mobile First: as difficult as doing things right
swwweet
225
10k