Setting Up the Form in HTML
We will be using an HTML form to make a POST request to add a new image to our database. A form is essentially of the following format:
<form method="POST" action="/url/to/handle/post>
<input name="X">
<input name="Y">
<button type="submit">Submit</button>
</form>
Let's look at each part.
The form element has two key attributes defined. The method indicates that this is a POST request. The action indicates what URL the POST request to be made to when it is submitted. This is the URL which we will have to handle in Django to make a view for with the post method defined.
Within the form there are a few input elements. These elements are where the user inputs the data, often as a text bo x. When the data is sent to the backend, it will be in a dictionary where the key is the name of the input and the value is whatever the user inputted. So for the first input, the key would be "X".
The button element is labeled with the type of "submit", meaning that the form knows that when the user presses the button, it should send the POST request with the data.
Now that we have the basic structure of a form down, let's look at a form HTML for our purposes that will be using some boot strap:
<div class="container">
<div class="row">
<form method="post" action="/createPost">
{% csrf_token %}
<div class="form-group">
<label>Image URL</label>
<input name="imgURL" type="text" class="form-control" placeholder="A URL from Google!">
</div>
<div class="form-group">
<label>Name</label>
<input name="name" type="text" class="form-control" placeholder="What is your name">
</div>
<div class="form-group">
<label>Caption</label>
<input name="caption" type="text" class="form-control" placeholder="What is the picture about?">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
A few things to note here:
First off, we have added a mysterious {% csrf_token %} item into the form. This is a requirement by Django that if we want the security of the form to be good, we need to include it. I won't go into detail why in this guide but you can read more about it here if you are interested.
Notice that we add a lot of <div> elements and class names. These are all standard copy from bootstrap. You can see there forms documentation here.
Now our website looks like this:
However, if you noticed, if you click submit it gives the following error:
This is because we haven't made the /createPost URL in our urls.py. we'll do that next!