问题
I am working my django projects based on html form submission method . But recently, I came to know that there exist django forms. Please let me know what is the difference between them.
回答1:
Writing a form in Django will ultimately produce a HTML form. The Django form can be bound to a model which will then apply validation to the form based on the model structure, this saves on having to manually code the validation and also helps keep everything aligned when changes are made to the model.
回答2:
From Django's forms documentation:
As well as its elements, a form must specify two things:
where: the URL to which the data corresponding to the user’s input should be returned
how: the HTTP method the data should be returned by
Django's Forms is a Python class which helps with these things. It's still using the HTML form input elements, but provides things to:
- help use the data inputted
- format the data received so it'll go smoothly in your database
- validate that the data makes sense for the use
- provide security
- pre-populate fields
You define the form in your project as a .py file, instead of in the HTML.
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
As you can see, the HTML input element is still there - but the content has been written re-useably in a python form. Django will take care of rendering it all into a page view.
来源:https://stackoverflow.com/questions/47184096/what-is-the-difference-between-django-form-and-html-form