web programming session 17: forms -...

Post on 21-Sep-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CE419 Web Programming Session 17 Forms

Forms

bull ltformgt is the way that allows users to send data to server for processing

2

Forms

3

Processing Forms

bull Itrsquos possible to process forms just using Djangorsquos HttpRequest class

bull requestGET requestPOST requestFILES

bull Aint Nobody Got Time For That

4

Processing Forms ndash The Stone Age Way

def register(request) if requestmethod == POST username = requestPOSTget(username None) if not username username_error = uنامم کارربریی رراا وواارردد کنيید elif not rematch([dw_]3 username) username_error = uنامم کارربریی بايید حدااقل سهھ کاررااکتر وو شامل ااعداادد وو حرووفف باشد elif Userobjectsfilter(username=username)count() gt 0 username_error = uاايین نامم کارربریی قبال گرفتهھ شدهه ااست email = requestPOSTget(email None) if not email email_error = uآآددررسس اايیميیل رراا وواارردد کنيید elif not email_research(email) email_error = uاايیميیل معتبریی رراا وواارردد کنيید elif Userobjectsfilter(email=email)count() gt 0 email_error = uاايین آآددررسس اايیميیل قبال ااستفاددهه شدهه ااست

5

Default value in the case that lsquousernamersquo doesnrsquot exist

Processing Forms ndash The Stone Age Way

bull Pretty cool huh

bull Donrsquot Repeat Yourself dude

6

Django Forms API

bull Helps you with some common tasks

bull Auto-generate an HTML form for you

bull Check submitted data against set of validation rules

bull Redisplay form in case of errors

bull Convert submitted data to relevant Python types

7

Form Object

bull A Form object encapsulates a sequence of form fields and a collection of validation rules

from django import forms

class ContactForm(formsForm) subject = formsCharField(max_length=100) message = formsCharField() sender = formsEmailField() cc_myself = formsBooleanField(required=False)

CharField DateField FileField

EmailField BooleanField RegexField

hellip

formspy

9

Field Object

bull Important field arguments bull Fieldrequired bull Fieldlabel bull Fieldinitial bull Fieldwidget bull Fieldhelp_text bull Fielderror_messages

bull Fieldvalidators

father_name = formsCharField(required=False)

url = formsURLField(label=Your Web site)

url = formsURLField(initial=http)

comment = formsCharField(widget=formsTextarea)

Not for fallback

sender = formsEmailField(help_text=Real address)

name = formsCharField(error_messages=required lsquoEnter your name dudersquo)

even_field = formsIntegerField(validators=[validate_even])

10

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Forms

bull ltformgt is the way that allows users to send data to server for processing

2

Forms

3

Processing Forms

bull Itrsquos possible to process forms just using Djangorsquos HttpRequest class

bull requestGET requestPOST requestFILES

bull Aint Nobody Got Time For That

4

Processing Forms ndash The Stone Age Way

def register(request) if requestmethod == POST username = requestPOSTget(username None) if not username username_error = uنامم کارربریی رراا وواارردد کنيید elif not rematch([dw_]3 username) username_error = uنامم کارربریی بايید حدااقل سهھ کاررااکتر وو شامل ااعداادد وو حرووفف باشد elif Userobjectsfilter(username=username)count() gt 0 username_error = uاايین نامم کارربریی قبال گرفتهھ شدهه ااست email = requestPOSTget(email None) if not email email_error = uآآددررسس اايیميیل رراا وواارردد کنيید elif not email_research(email) email_error = uاايیميیل معتبریی رراا وواارردد کنيید elif Userobjectsfilter(email=email)count() gt 0 email_error = uاايین آآددررسس اايیميیل قبال ااستفاددهه شدهه ااست

5

Default value in the case that lsquousernamersquo doesnrsquot exist

Processing Forms ndash The Stone Age Way

bull Pretty cool huh

bull Donrsquot Repeat Yourself dude

6

Django Forms API

bull Helps you with some common tasks

bull Auto-generate an HTML form for you

bull Check submitted data against set of validation rules

bull Redisplay form in case of errors

bull Convert submitted data to relevant Python types

7

Form Object

bull A Form object encapsulates a sequence of form fields and a collection of validation rules

from django import forms

class ContactForm(formsForm) subject = formsCharField(max_length=100) message = formsCharField() sender = formsEmailField() cc_myself = formsBooleanField(required=False)

CharField DateField FileField

EmailField BooleanField RegexField

hellip

formspy

9

Field Object

bull Important field arguments bull Fieldrequired bull Fieldlabel bull Fieldinitial bull Fieldwidget bull Fieldhelp_text bull Fielderror_messages

bull Fieldvalidators

father_name = formsCharField(required=False)

url = formsURLField(label=Your Web site)

url = formsURLField(initial=http)

comment = formsCharField(widget=formsTextarea)

Not for fallback

sender = formsEmailField(help_text=Real address)

name = formsCharField(error_messages=required lsquoEnter your name dudersquo)

even_field = formsIntegerField(validators=[validate_even])

10

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Forms

3

Processing Forms

bull Itrsquos possible to process forms just using Djangorsquos HttpRequest class

bull requestGET requestPOST requestFILES

bull Aint Nobody Got Time For That

4

Processing Forms ndash The Stone Age Way

def register(request) if requestmethod == POST username = requestPOSTget(username None) if not username username_error = uنامم کارربریی رراا وواارردد کنيید elif not rematch([dw_]3 username) username_error = uنامم کارربریی بايید حدااقل سهھ کاررااکتر وو شامل ااعداادد وو حرووفف باشد elif Userobjectsfilter(username=username)count() gt 0 username_error = uاايین نامم کارربریی قبال گرفتهھ شدهه ااست email = requestPOSTget(email None) if not email email_error = uآآددررسس اايیميیل رراا وواارردد کنيید elif not email_research(email) email_error = uاايیميیل معتبریی رراا وواارردد کنيید elif Userobjectsfilter(email=email)count() gt 0 email_error = uاايین آآددررسس اايیميیل قبال ااستفاددهه شدهه ااست

5

Default value in the case that lsquousernamersquo doesnrsquot exist

Processing Forms ndash The Stone Age Way

bull Pretty cool huh

bull Donrsquot Repeat Yourself dude

6

Django Forms API

bull Helps you with some common tasks

bull Auto-generate an HTML form for you

bull Check submitted data against set of validation rules

bull Redisplay form in case of errors

bull Convert submitted data to relevant Python types

7

Form Object

bull A Form object encapsulates a sequence of form fields and a collection of validation rules

from django import forms

class ContactForm(formsForm) subject = formsCharField(max_length=100) message = formsCharField() sender = formsEmailField() cc_myself = formsBooleanField(required=False)

CharField DateField FileField

EmailField BooleanField RegexField

hellip

formspy

9

Field Object

bull Important field arguments bull Fieldrequired bull Fieldlabel bull Fieldinitial bull Fieldwidget bull Fieldhelp_text bull Fielderror_messages

bull Fieldvalidators

father_name = formsCharField(required=False)

url = formsURLField(label=Your Web site)

url = formsURLField(initial=http)

comment = formsCharField(widget=formsTextarea)

Not for fallback

sender = formsEmailField(help_text=Real address)

name = formsCharField(error_messages=required lsquoEnter your name dudersquo)

even_field = formsIntegerField(validators=[validate_even])

10

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Processing Forms

bull Itrsquos possible to process forms just using Djangorsquos HttpRequest class

bull requestGET requestPOST requestFILES

bull Aint Nobody Got Time For That

4

Processing Forms ndash The Stone Age Way

def register(request) if requestmethod == POST username = requestPOSTget(username None) if not username username_error = uنامم کارربریی رراا وواارردد کنيید elif not rematch([dw_]3 username) username_error = uنامم کارربریی بايید حدااقل سهھ کاررااکتر وو شامل ااعداادد وو حرووفف باشد elif Userobjectsfilter(username=username)count() gt 0 username_error = uاايین نامم کارربریی قبال گرفتهھ شدهه ااست email = requestPOSTget(email None) if not email email_error = uآآددررسس اايیميیل رراا وواارردد کنيید elif not email_research(email) email_error = uاايیميیل معتبریی رراا وواارردد کنيید elif Userobjectsfilter(email=email)count() gt 0 email_error = uاايین آآددررسس اايیميیل قبال ااستفاددهه شدهه ااست

5

Default value in the case that lsquousernamersquo doesnrsquot exist

Processing Forms ndash The Stone Age Way

bull Pretty cool huh

bull Donrsquot Repeat Yourself dude

6

Django Forms API

bull Helps you with some common tasks

bull Auto-generate an HTML form for you

bull Check submitted data against set of validation rules

bull Redisplay form in case of errors

bull Convert submitted data to relevant Python types

7

Form Object

bull A Form object encapsulates a sequence of form fields and a collection of validation rules

from django import forms

class ContactForm(formsForm) subject = formsCharField(max_length=100) message = formsCharField() sender = formsEmailField() cc_myself = formsBooleanField(required=False)

CharField DateField FileField

EmailField BooleanField RegexField

hellip

formspy

9

Field Object

bull Important field arguments bull Fieldrequired bull Fieldlabel bull Fieldinitial bull Fieldwidget bull Fieldhelp_text bull Fielderror_messages

bull Fieldvalidators

father_name = formsCharField(required=False)

url = formsURLField(label=Your Web site)

url = formsURLField(initial=http)

comment = formsCharField(widget=formsTextarea)

Not for fallback

sender = formsEmailField(help_text=Real address)

name = formsCharField(error_messages=required lsquoEnter your name dudersquo)

even_field = formsIntegerField(validators=[validate_even])

10

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Processing Forms ndash The Stone Age Way

def register(request) if requestmethod == POST username = requestPOSTget(username None) if not username username_error = uنامم کارربریی رراا وواارردد کنيید elif not rematch([dw_]3 username) username_error = uنامم کارربریی بايید حدااقل سهھ کاررااکتر وو شامل ااعداادد وو حرووفف باشد elif Userobjectsfilter(username=username)count() gt 0 username_error = uاايین نامم کارربریی قبال گرفتهھ شدهه ااست email = requestPOSTget(email None) if not email email_error = uآآددررسس اايیميیل رراا وواارردد کنيید elif not email_research(email) email_error = uاايیميیل معتبریی رراا وواارردد کنيید elif Userobjectsfilter(email=email)count() gt 0 email_error = uاايین آآددررسس اايیميیل قبال ااستفاددهه شدهه ااست

5

Default value in the case that lsquousernamersquo doesnrsquot exist

Processing Forms ndash The Stone Age Way

bull Pretty cool huh

bull Donrsquot Repeat Yourself dude

6

Django Forms API

bull Helps you with some common tasks

bull Auto-generate an HTML form for you

bull Check submitted data against set of validation rules

bull Redisplay form in case of errors

bull Convert submitted data to relevant Python types

7

Form Object

bull A Form object encapsulates a sequence of form fields and a collection of validation rules

from django import forms

class ContactForm(formsForm) subject = formsCharField(max_length=100) message = formsCharField() sender = formsEmailField() cc_myself = formsBooleanField(required=False)

CharField DateField FileField

EmailField BooleanField RegexField

hellip

formspy

9

Field Object

bull Important field arguments bull Fieldrequired bull Fieldlabel bull Fieldinitial bull Fieldwidget bull Fieldhelp_text bull Fielderror_messages

bull Fieldvalidators

father_name = formsCharField(required=False)

url = formsURLField(label=Your Web site)

url = formsURLField(initial=http)

comment = formsCharField(widget=formsTextarea)

Not for fallback

sender = formsEmailField(help_text=Real address)

name = formsCharField(error_messages=required lsquoEnter your name dudersquo)

even_field = formsIntegerField(validators=[validate_even])

10

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Processing Forms ndash The Stone Age Way

bull Pretty cool huh

bull Donrsquot Repeat Yourself dude

6

Django Forms API

bull Helps you with some common tasks

bull Auto-generate an HTML form for you

bull Check submitted data against set of validation rules

bull Redisplay form in case of errors

bull Convert submitted data to relevant Python types

7

Form Object

bull A Form object encapsulates a sequence of form fields and a collection of validation rules

from django import forms

class ContactForm(formsForm) subject = formsCharField(max_length=100) message = formsCharField() sender = formsEmailField() cc_myself = formsBooleanField(required=False)

CharField DateField FileField

EmailField BooleanField RegexField

hellip

formspy

9

Field Object

bull Important field arguments bull Fieldrequired bull Fieldlabel bull Fieldinitial bull Fieldwidget bull Fieldhelp_text bull Fielderror_messages

bull Fieldvalidators

father_name = formsCharField(required=False)

url = formsURLField(label=Your Web site)

url = formsURLField(initial=http)

comment = formsCharField(widget=formsTextarea)

Not for fallback

sender = formsEmailField(help_text=Real address)

name = formsCharField(error_messages=required lsquoEnter your name dudersquo)

even_field = formsIntegerField(validators=[validate_even])

10

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Django Forms API

bull Helps you with some common tasks

bull Auto-generate an HTML form for you

bull Check submitted data against set of validation rules

bull Redisplay form in case of errors

bull Convert submitted data to relevant Python types

7

Form Object

bull A Form object encapsulates a sequence of form fields and a collection of validation rules

from django import forms

class ContactForm(formsForm) subject = formsCharField(max_length=100) message = formsCharField() sender = formsEmailField() cc_myself = formsBooleanField(required=False)

CharField DateField FileField

EmailField BooleanField RegexField

hellip

formspy

9

Field Object

bull Important field arguments bull Fieldrequired bull Fieldlabel bull Fieldinitial bull Fieldwidget bull Fieldhelp_text bull Fielderror_messages

bull Fieldvalidators

father_name = formsCharField(required=False)

url = formsURLField(label=Your Web site)

url = formsURLField(initial=http)

comment = formsCharField(widget=formsTextarea)

Not for fallback

sender = formsEmailField(help_text=Real address)

name = formsCharField(error_messages=required lsquoEnter your name dudersquo)

even_field = formsIntegerField(validators=[validate_even])

10

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Form Object

bull A Form object encapsulates a sequence of form fields and a collection of validation rules

from django import forms

class ContactForm(formsForm) subject = formsCharField(max_length=100) message = formsCharField() sender = formsEmailField() cc_myself = formsBooleanField(required=False)

CharField DateField FileField

EmailField BooleanField RegexField

hellip

formspy

9

Field Object

bull Important field arguments bull Fieldrequired bull Fieldlabel bull Fieldinitial bull Fieldwidget bull Fieldhelp_text bull Fielderror_messages

bull Fieldvalidators

father_name = formsCharField(required=False)

url = formsURLField(label=Your Web site)

url = formsURLField(initial=http)

comment = formsCharField(widget=formsTextarea)

Not for fallback

sender = formsEmailField(help_text=Real address)

name = formsCharField(error_messages=required lsquoEnter your name dudersquo)

even_field = formsIntegerField(validators=[validate_even])

10

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Field Object

bull Important field arguments bull Fieldrequired bull Fieldlabel bull Fieldinitial bull Fieldwidget bull Fieldhelp_text bull Fielderror_messages

bull Fieldvalidators

father_name = formsCharField(required=False)

url = formsURLField(label=Your Web site)

url = formsURLField(initial=http)

comment = formsCharField(widget=formsTextarea)

Not for fallback

sender = formsEmailField(help_text=Real address)

name = formsCharField(error_messages=required lsquoEnter your name dudersquo)

even_field = formsIntegerField(validators=[validate_even])

10

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Using a Form in a View

from djangoshortcuts import renderfrom djangohttp import HttpResponseRedirectfrom mysiteforms import ContactForm

def contact(request) if requestmethod == POST form = ContactForm(requestPOST) if formis_valid() processing the form and doing something return HttpResponseRedirect(thanks) else form = ContactForm()

return render(request contacthtml form form)

There are three different code paths here

Bound vs Unbound

The successfully validated form data will be in the formcleaned_data

dictionary

11

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Processing the Form

if formis_valid() subject = formcleaned_data[subject] message = formcleaned_data[message] sender = formcleaned_data[sender] cc_myself = formcleaned_data[cc_myself]

recipients = [infoexamplecom] if cc_myself recipientsappend(sender)

from djangocoremail import send_mail send_mail(subject message sender recipients) return HttpResponseRedirect(thanks)

You can still access the unvalidated data

directly from requestPOST

12

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Displaying the Form

ltform action=contact method=postgt csrf_token formas_p ltinput type=submit value=Submit gtltformgt

Donrsquot panic Wersquoll talk about this in a later session

Only outputs form fields donrsquot forget ltformgtltformgt

Render result ltform action=contact method=postgtltpgtltlabel for=id_subjectgtSubjectltlabelgt ltinput id=id_subject type=text name=subject maxlength=100 gtltpgtltpgtltlabel for=id_messagegtMessageltlabelgt ltinput type=text name=message id=id_message gtltpgtltpgtltlabel for=id_sendergtSenderltlabelgt ltinput type=email name=sender id=id_sender gtltpgtltpgtltlabel for=id_cc_myselfgtCc myselfltlabelgt ltinput type=checkbox name=cc_myself id=id_cc_myself gtltpgtltinput type=submit value=Submit gtltformgt

13

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Donrsquot Like It Okay whatever

ltform action=contact method=postgt formnon_field_errors ltdiv class=fieldWrappergt formsubjecterrors ltlabel for=id_subjectgtEmail subjectltlabelgt formsubject ltdivgt ltdiv class=fieldWrappergt formmessageerrors ltlabel for=id_messagegtYour messageltlabelgt formmessage ltdivgt ltdiv class=fieldWrappergt formsendererrors ltlabel for=id_sendergtYour email addressltlabelgt formsender ltdivgt ltdiv class=fieldWrappergt formcc_myselferrors ltlabel for=id_cc_myselfgtCC yourselfltlabelgt formcc_myself ltdivgt ltpgtltinput type=submit value=Send message gtltpgtltformgt

Displays a list of form errors rendered as an unordered list

Produces the HTML needed to display the form widget

14

Wersquoll talk about it in a minute Be patience

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

More Convenient Way

ltform action=contact method=postgt for field in form ltdiv class=fieldWrappergt fielderrors fieldlabel_tag field ltdivgt endfor ltpgtltinput type=submit value=Send message gtltpgtltformgt

fieldlabel fieldvalue fieldhelp_text fieldis_hidden fieldfield fieldhtml_name

15

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Using Forms Directly with a Model

bull Donrsquot Repeat Yourself

class Author(modelsModel) name = modelsCharField(max_length=100) title = modelsCharField(max_length=3 choices=TITLE_CHOICES) birth_date = modelsDateField(blank=True null=True)

def __str__(self) return selfname

class Book(modelsModel) name = modelsCharField(max_length=100) authors = modelsManyToManyField(Author)

class AuthorForm(formsModelForm) class Meta model = Author fields = [name title birth_date]

class BookForm(formsModelForm) class Meta model = Book fields = [name authors]

ModelForm objects have an extra save() method

16

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

Any Questions

26

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

References

bull httpsdocsdjangoprojectcomen16topicsforms

bull httpsdocsdjangoprojectcomen16refformsfields

bull httpsdocsdjangoprojectcomen16refformswidgets

bull httpsdocsdjangoprojectcomen16refformsvalidation

bull httpwwwpythonorg

27

top related