D
D
Dzhemchik2020-02-02 05:45:14
Django
Dzhemchik, 2020-02-02 05:45:14

Why is the id of the foreignkey field not displayed in the template?

Hello! Unable to display model id in html template.
Need help/hint.

#models.py
class Order(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __str__(self):
        return 'Order {}'.format(self.id)
#...

class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='items', on_delete=models.SET_NULL,
                             null=True)
#...
    def __str__(self):
        return f'{self.id}'

views.py
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save()
            for item in cart:
                OrderItem.objects.create(order=order, # не отображается в шаблоне
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
            # очистка корзины
            cart.clear()
            return render(request, 'orders/order/created.html',
                          {'orders': order})
    else:
        form = OrderCreateForm
    return render(request, 'orders/order/create.html',
                  {'cart': cart, 'form': form})

And the html itself
{% extends "shop/base.html" %}

{% block title %}Thank you{% endblock %}

{% block content %}
    <h1>Thank you</h1>
    <p>Your order has been successfully completed. Your order number is
        <strong>{{ order.id }}</strong>.</p>
{% endblock %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-02-02
@dzhem911

{'orders': order}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question