Professional Documents
Culture Documents
0 COMMENTS
by Dayne (47)
IN THESE INTERESTS
django
Django forms are an excellent way to manage user input in a Django application. Once you learn how 20 SUBSCRIBERS SUBSCRIBE
to wield them, you'll never go back to manually coding a form tag and handling the response. This
python
guide will scratch the surface but get you far enough to begin using and learning the power of
103 SUBSCRIBERS SUBSCRIBE
Django's Form class.
Using a mature web framework's form class also enforces more secure code than you write
(probably). For example, Django forms will complain loudly if you do not use CSRF protection,
something that can easily go forgotten if you're manually coding a form.
class ArticleForm(
ArticleForm(forms.
forms.ModelForm)
ModelForm):
forms.
title = forms .CharField
CharField(
()
forms.
desc = forms.TextField
TextField(()
Meta:
class Meta:
model = Article
There are other minor steps which we will cover, but this is the basic framework for using Django
forms.
ContactForm(
class ContactForm (forms
forms.
.Form
Form)
):
name = forms.
forms.CharField(
CharField()
forms.
email = forms .EmailField
EmailField(()
forms.
message = forms .CharField
CharField((widget
widget=
=forms
forms.
.Textarea
Textarea))
Create a view
def contact(
contact(request
request)
):
ContactForm(
contact_form = ContactForm ()
render(
return render(request
request,
, "contact.html"
"contact.html",
, {"form"
"form":
: contact_form
contact_form}
})
url(
url(r'^contact/?$'
'^contact/?$',
, contact
contact,, name
name=
='contact'
'contact')
)
Create a template
h1>
<h1>Contact
Contact<</h1
h1>
>
<form role=
role="form" action=
action="" method
method=
="post"
"post">>
{% csrf_token %}
{{ form }}
type=
<button type ="submit"
"submit">
>Submit
Submit<
</button
button>
>
form>
</form>
if request.
request.method == 'POST':
'POST':
ContactForm(
contact_form = ContactForm(data
data=
=request
request.
.POST
POST)
)
if contact_form.
contact_form.is_valid
is_valid(():
request.
name = request.POST
POST..get
get(
('name'
'name',
, '')
'')
email = request.
request.POST.
POST.get(
get('email',
'email', '')
'')
request.
message = request .POST
POST.
.get
get(
('message'
'message',
, '')
'')
# do some processing with name and email
messages.
messages.success
success((request
request,, 'Your message has been sent!')
sent!')
redirect(
return redirect('contact'
'contact') )
else:
else:
ContactForm(
contact_form = ContactForm ()
django.
from django.db import models
Article(
class Article(models
models.
.Model
Model)
):
title = models.
models.CharField(
CharField(max_length=
max_length=1000)
1000)
models.
desc = models.CharField
CharField((max_length
max_length=
=1000
1000)
)
Create a form
ArticleForm(
class ArticleForm(forms
forms.
.ModelForm
ModelForm)):
Meta:
class Meta:
model = Article
'title',
fields = ['title', 'desc'
'desc',
,]
Create a view
url(
url(r'^articles/create?$'
'^articles/create?$',
, contact
contact,, name
name=
='article_create'
'article_create')
)
Create a template
h1>
<h1>Article Form<
Form</h1
h1>
>
<form role=
role="form" action
action=
="" method=
method="post"
"post">
>
{% csrf_token %}
form.
{{ form.as_p }}
<button type
type=
="submit"
"submit">
>Submit
Submit<
</button
button>
>
form>
</form>
class ArticleForm(
ArticleForm(forms.
forms.ModelForm)
ModelForm):
Meta:
class Meta:
model = Article
'title',
fields = ['title', 'desc'
'desc',
,]
widgets = {
'desc':
'desc': forms.
forms.Textarea(
Textarea(attrs=
attrs={'class':
'class': 'desc'}
'desc'}),
}
if request.
request.method == 'POST'
'POST':
:
ArticleForm(
article_form = ArticleForm(data
data=
=request
request.
.POST
POST)
)
if article_form.
article_form.is_valid
is_valid(():
article_form.
article = article_form .save
save(
()
redirect(
return redirect('article-detail'
'article-detail',
, pk
pk=
=article
article.
.pk
pk)
)
else:
else:
article_form = ArticleForm(
ArticleForm()
def article_edit(
article_edit(request
request,
, pk
pk)
):
try:
try:
Article.
article = Article .objects
objects.
.get
get(
(pk
pk=
=pk
pk)
)
Article.
except Article .DoesNotExist
DoesNotExist::
redirect(
return redirect('article-create'
'article-create') )
ArticleForm(
article_form = ArticleForm(instance
instance==article
article)
)
render(
return render(request
request,
, "article_form.html"
"article_form.html",
, {"form"
"form":
: article_form
article_form}
})
url(
url(r'^articles/(?P<pk>\d+)/edit?$'
'^articles/(?P<pk>\d+)/edit?$',
, contact
contact,, name
name=
='article-edit'
'article-edit')
)
if request.
request.method == 'POST'
'POST':
:
ArticleForm(
article_form = ArticleForm(instance
instance==article
article,
, data
data=
=request
request.
.POST
POST)
)
article_form.
if article_form.is_valid
is_valid(():
article_form.
article = article_form.save
save(
()
redirect(
return redirect('article-detail'
'article-detail',
, pk
pk=
=article
article.
.pk
pk)
)
else:
else:
ArticleForm(
article_form = ArticleForm(instance
instance==article
article)
)
def clean_title(
clean_title(self)
self):
self.
title = self .cleaned_data
cleaned_data.
.get
get(
('title'
'title',
, None
None)
)
return title
Default or .as_table()
article_form = ArticleForm(
ArticleForm()
print(
print(article_form
article_form)
) # or print(article_form.as_table())
# results
<tr>
tr>
th>
<th><label for
for=
="id_title"
"id_title">
>Title
Title:
:</label
label>
></th
th>
>
td>
<td><input id
id=
="id_title" maxlength
maxlength=
="1000" name
name=
="title" type
type=
="text" /></td
td>
>
tr>
</tr>
tr>
<tr>
<th>
th><label for=
for="id_desc">
"id_desc">Desc:
Desc:</label>
label></th>
th><td>
td>
class=
<textarea class ="desc" cols
cols=
="40" id
id=
="id_desc" maxlength
maxlength=
="1000" name
name=
="desc" rows
rows=
="10"
"10">
></textarea
textarea>
><
tr>
</tr>
.as_p()
ArticleForm(
article_form = ArticleForm ()
print(
print(article_form
article_form.
.as_p
as_p(
())
#results
<p>
<label for=
for="id_title"
"id_title">>Title
Title:
:</label
label>
>
id=
<input id="id_title" maxlength
maxlength=="1000" name
name=
="title" type
type=
="text" />
</p>
<p>
for=
<label for="id_desc"
"id_desc">
>Desc
Desc::</label
label>
>
class=
<textarea class ="desc" cols
cols=="40" id
id=
="id_desc" maxlength
maxlength=
="1000" name=
name="desc" rows
rows=
="10"
"10">
></textarea
textarea>
>
</p>
article_form.as_ul()
ArticleForm(
article_form = ArticleForm()
print(
print(article_form
article_form.
.as_ul
as_ul(
())
#results
li>
<li>
for=
<label for="id_title"
"id_title">
>Title
Title:
:</label
label>
>
id=
<input id="id_title" maxlength
maxlength=
="1000" name
name=
="title" type
type=
="text" />
li>
</li>
<li>
li>
<label for
for=
="id_desc"
"id_desc">
>Desc
Desc:
:</label
label>
>
class=
<textarea class="desc" cols
cols=
="40" id
id=
="id_desc" maxlength
maxlength=
="1000" name
name=
="desc" rows
rows=
="10"
"10">
></textarea
textarea>
>
li>
</li>
ArticleForm(
article_form = ArticleForm ()
article_form:
for field in article_form:
print(
print(field)
field)
# results
id=
<input id="id_title" maxlength
maxlength=
="1000" name
name=
="title" type
type=
="text" />
class=
<textarea class ="desc" cols
cols=
="40" id
id=
="id_desc" maxlength
maxlength=
="1000" name=
name="desc" rows
rows=
="10"
"10">
></textarea
textarea>
>
In Template
10 Conclusion
Pros of Django Forms
Weaknesses
0 COMMENTS
Dayne (47)
Dayne loves hacking things, in both a computer sense and a wielding an
axe sense.
Share this guide!
Email
0 0 0 2 0 0
Combine Two Querysets in Why and how we use Django How to validate yaml from the
Django (with different models) howchoo was originally built in PHP and
command line (using Python)
Today, I stumbled upon a use case where I needed Codeigniter, then we switched completely to This guide will show you how to validate yaml on
to have a querysets that had objects from different Django in February of 2015. the command line using Python.
models. Django has a neat "contenttypes
framework" which is a good way to achieve this. tyler View tyler View
Ashley View
How to use Siri to control anything -- from IFTT to custom programs and devices
by tyler in pi, python, apple
/django
©2018 howchoo, llc | Sitemap | Terms of use | Privacy policy | DMCA requests