Django | Codecademy | Forms
4487 ワード
Django Forms vs. HTML Forms
Django Forms look much like HTML forms, but Django uses a model based system to handle the data.
Form Security <form>
{% csrf_token %}
...
</form>
Form Validation
Form validation is also necessary to help defend out applications from possible attacks that use incorrect data types to cause problems (e.g. SQL attacks). This validation can include ensuring only specific data types are being submitted to protect our database.views.py에서:
if form.is_valid():
form = form.save()
Submitting a Form
In Django, we’ll be using the "POST" method
when the form is submitted, which means all of the data from the forms will be sent to the POST method in views.py
.
to differentiate how the view function should treat a POST request vs rendering the usual form, we use an if statement
<form>
{% csrf_token %}
...
</form>
Form Validation
Form validation is also necessary to help defend out applications from possible attacks that use incorrect data types to cause problems (e.g. SQL attacks). This validation can include ensuring only specific data types are being submitted to protect our database.
views.py에서:
if form.is_valid():
form = form.save()
Submitting a Form
In Django, we’ll be using the "POST" method
when the form is submitted, which means all of the data from the forms will be sent to the POST method in views.py
.
to differentiate how the view function should treat a POST request vs rendering the usual form, we use an if statement
if
statement checks that the request method is "POST"
from .models import Model_Name
def renderTemplate(request):
if request.method == "POST":
test_model = Model_Name()
test_model.field = request.POST["field_name"]
test_model.save()
return render(request, "template_with_form.html")
Steps:1. check if the
request.method
is equal to "POST"
. "POST"
, it means that the form was submitted which means that we can grab all the data and use it to create a new model instance. Model_Name()
. test_model.field
a value of request.POST["field_name"]
. This is because in our form, we had an input field with a name set to "field_name"
. request.POST["field_name"]
syntax shows that request is treated like a dictionary with a "field_name"
property. Once all of the data from request.POST
is added to the model, we can save the model and render the form again. Reference
この問題について(Django | Codecademy | Forms), 我々は、より多くの情報をここで見つけました https://velog.io/@celeste/Django-Codecademy-Formsテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol