Hey Mentors and Teachers, we appreciate having you, please help a young one here in this industry.
I recently had a similar issue with form submission and sure since I am a beginner this is one of my common challenges since I am still trying new ways, here I am using a model to save a form and also model form without having to use the form in the template
here is the model
class Order(models.Model):
STATUS = (
('New', 'New'),
('Accepted', 'Accepted'),
('Completed', 'Completed'),
('Cancelled', 'Cancelled'),
)
user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True)
payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True)
order_number = models.CharField(max_length=20)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=15)
email = models.EmailField(max_length=50)
address_line_1 = models.CharField(max_length=50)
address_line_2 = models.CharField(max_length=50, blank=True)
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
city = models.CharField(max_length=50)
order_note = models.CharField(max_length=100, blank=True)
order_total = models.FloatField()
tax = models.FloatField()
status = models.CharField(max_length=10, choices=STATUS, default='New')
ip = models.CharField(blank=True, max_length=20)
is_ordered = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def full_name(self):
return f'{self.first_name}'
and here is a view that is am using:
def place_order(request, total=0, quantity=0,):
current_user = request.user
# If the cart count is less than or equal to 0, then redirect back to shop
cart_items = CartItem.objects.filter(user=current_user)
cart_count = cart_items.count()
if cart_count <= 0:
return redirect('store')
grand_total = 0
tax = 0
for cart_item in cart_items:
total += (cart_item.product.price * cart_item.quantity)
quantity += cart_item.quantity
tax = (2 * total)/100
grand_total = total + tax
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
# Store all the billing information inside Order table
data = Order()
data.user = current_user
data.first_name = form.cleaned_data['first_name']
data.last_name = form.cleaned_data['last_name']
data.phone = form.cleaned_data['phone']
data.email = form.cleaned_data['email']
data.address_line_1 = form.cleaned_data['address_line_1']
data.address_line_2 = form.cleaned_data['address_line_2']
data.country = form.cleaned_data['country']
data.state = form.cleaned_data['state']
data.city = form.cleaned_data['city']
data.more_address_details = form.cleaned_data['more_address_details']
data.order_note = form.cleaned_data['order_note']
data.order_note = form.cleaned_data['order_note']
data.order_total = grand_total
data.tax = tax
data.ip = request.META.get('REMOTE_ADDR')
data.save()
# Generate order number
yr = int(datetime.date.today().strftime('%Y'))
dt = int(datetime.date.today().strftime('%d'))
mt = int(datetime.date.today().strftime('%m'))
d = datetime.date(yr,mt,dt)
current_date = d.strftime("%Y%m%d") #20210305
order_number = current_date + str(data.id)
data.order_number = order_number
data.save()
order = Order.objects.get(user = current_user, is_ordered = False, order_number = order_number)
context = {
'order': order,
'cart_items': cart_items,
'total': total,
'tax': tax,
'grand_total': grand_total,
}
return render(request, 'orders/payments.html', {'context': context})
else:
return redirect('checkout')
else:
return redirect('store')
and here is what is in the template:
<div class="card">
<div class="card-body">
<h4 class="card-title mb-4">Billing address </h4>
<form action="{% url 'place_order' %}" method="POST">
{% csrf_token %}
<div class="form-row">
<div class="col form-group">
<label for="">First Name</label>
<input type="text" name="first_name" class="form-control" required>
</div>
<div class="col form-group">
<label for="">Last Name</label>
<input type="text" name="first_name" class="form-control" required>
</div>
</div>
<div class="form-row">
<div class="col form-group">
<label for="">Email</label>
<input type="email" name="email" class="form-control" required>
</div>
<div class="col form-group">
<label for="">Phone Number</label>
<input type="text" name="phone" class="form-control" required>
</div>
</div>
<div class="form-row">
<div class="col form-group">
<label for="">Address line 1</label>
<input type="text" name="address_line_1" class="form-control" required>
</div>
<div class="col form-group">
<label for="">Address line 1</label>
<input type="text" name="address_line_1" class="form-control">
</div>
</div>
<div class="form-row">
<div class="col form-group">
<label for="">City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div class="col form-group">
<label for="">State</label>
<input type="text" name="state" class="form-control">
</div>
<div class="col form-group">
<label for="">Country</label>
<input type="text" name="country" class="form-control" required>
</div>
</div>
<div class="form-row">
<label for="">More details about your location</label>
<textarea name="order_note" class="form-control" rows="2"></textarea>
</div>
{% if form.errors %}
<div class="alert alert-danger">
Please correct the error{{ form.errors|pluralize }} below.
</div>
{% endif %}
<div class="form-row">
<label for="">Oder Note</label>
<textarea name="order_note" class="form-control" rows="2"></textarea>
</div>
</div>
</div> <!-- card.// -->
<button type="submit" name="submit" class="btn btn-primary btn-block">Place Order</button>
</form>