Django | Codecademy | Forms
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>
{% csrf_token %}
...
</form>
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
- This
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"
.
- When the method is
"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. - Notice our test_model is a new
Model_Name()
. - We then assign the
test_model.field
a value ofrequest.POST["field_name"]
. This is because in our form, we had an input field with a name set to"field_name"
. - The
request.POST["field_name"]
syntax shows that request is treated like a dictionary with a"field_name"
property. Once all of the data fromrequest.POST
is added to the model, we can save the model and render the form again.
If our conditional isn’t met, it usually means that the form is being rendered for the first time, so we can skip the instance creation and just render the form as normal.
Author And Source
이 문제에 관하여(Django | Codecademy | Forms), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@celeste/Django-Codecademy-Forms저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)