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.
{% 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.
def add_address(request) :
if request.method == "POST" : #? handling the submission of the form
if request.user.is_authenticated:
client = request.user.client
else :
if request.COOKIES.get('id_session') :
id_session = request.COOKIES.get("id_session")
client, created = Client.objects.get_or_create(id_session=id_session)
else : #? if the client enters directly on the cart, whithout generating cookies
return redirect('store') #? return directly to the store as the cart should be empty
data = request.POST.dict() #? converts the request data to a dictionary
address = Adres.objects.create(client=client, street=data.get('street'), city=data.get('city'), state=data.get('state'), zip_code=data.get('zip_code'), number=int(data.get('number')), apartment=data.get('apartment'))
address.save()
return redirect('checkout') #? redirects the user to the checkout page to add more addresses if needed
else :
context = {}
return render(request, 'add_address.html', context)
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.

add_address
function supports both authenticated and unauthenticated clients.Last updated