24.1 Adding address

To enable the functionality of adding an address to a specific client, we need to first update the add_address.html file.

add_address.html
{% extends 'base.html' %}
{% load static %}

{% block body %}

<h3>
    Add Address
</h3>
<a href="{% url 'checkout' %}">Return to checkout</a>

<h3>Add a new address</h3>
<form method="POST" action="{% url 'add_address' %}">
    {% csrf_token %}
    <!--Adding the inputs based on the attributes of the Address class-->
    <input type="text" name="street" placeholder="Street">
    <input type="number" name="number" placeholder="Number">
    <input type="text" name="apartment" placeholder="Apartment">
    <input type="number" name="zip_code" placeholder="Zip Code">
    <input type="text" name="city" placeholder="City">
    <input type="text" name="state" placeholder="State">
    <button type="submit">Add address</button>
</form>


{% endblock %}

In the updated add_address.html file, we incorporated the following elements:

  • An <a> tag to allow the client to return to the checkout page.

  • Input fields for the client to enter values corresponding to the attributes defined in the Address class.

Subsequently, we need to update the add_address function in our views.py file to enable the creation of an Address instance associated with the client using the provided input values.

The process implemented in the code above is analogous to the steps undertaken in previous sections:

  • Verify if the user is authenticated.

  • If the user is not authenticated, retrieve the id_session generated by cookies.

  • Extract the input data from the HTML form in dictionary format.

  • Utilize the extracted data to create and save a new Address instance.

  • Redirect the user back to the checkout page, allowing for the addition of more addresses if needed.

The add_address function supports both authenticated and unauthenticated clients.

Last updated