Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥

Django Forms

Django Forms

Introduction to Django Forms for Django Girls × Taipei.py workshop.

Tzu-ping Chung

February 23, 2016
Tweet

More Decks by Tzu-ping Chung

Other Decks in Programming

Transcript

  1. <form action="/path/to/send" method="post" enctype="multipart/form-data"> • How to send • Either

    get or post • Get: postcard • Post: Enveloped • Default: get
  2. 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
  3. 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, )
  4. from .forms import MessageForm def message_board(request): form = MessageForm() return

    render( request, 'message_board.html', {'form': form}, )
  5. CSRF Token • Cross Site Request Forgery protection • “Recognise”

    whether a form is legit • Protect the server from malicious changes
  6. 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, )
  7. 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, )
  8. 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
  9. 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
  10. 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}, )
  11. Exercises • Implement message form • Implement message model, save

    POST-ed form to it • Get messages from database • Display messages in template
  12. 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')