so I'm writting a program for creating orders for specific users and items. My problem is when I'm trying to display all customers, products and statuses from this model:
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=20, null=True, choices=STATUS)
def __str__(self):
return self.product.name
I have to do this manually:
{% extends 'accounts/base.html' %}
{% load static %}
{% block main %}
<form action="" method="post">
{% csrf_token %}
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
customer
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" > {{ form.customer.1 }}</a>
<a class="dropdown-item" > {{ form.customer.2}}</a>
<a class="dropdown-item" > {{ form.customer.3}}</a>
<a class="dropdown-item" > {{ form.customer.4}}</a>
<a class="dropdown-item" > {{ form.customer.5}}</a>
</div>
</div>
<input type="submit" name="submit" class="btn btn-success">
</form>
{% endblock %}
That's because when i tried making a loop which would just give them ids instead of numbers it just wouldn't show up.
Can anybody help me? :(
Forms.py
from django.forms import ModelForm
from .models import *
class OrderForm(ModelForm):
class Meta:
model = Order # model do którego tworzymy formę
fields = '__all__' # pola które dzięki niej chcemy uzupełnić
Views.py
def createOrder(request):
form = OrderForm # tworzymy obiekt który bedzie trzymał formę z plikuu forms.py
if request.method == 'POST': # jeżeli meotda request-u to POST
form = OrderForm(request.POST) # to zmieniami wartość obiektu na formę z requestem POST
if form.is_valid(): # jeżeli forma jest prawidłowa
form.save() # zapisz formę w bazie danych
return redirect('/') # przekieruj na stronę główną
return render(request, 'accounts/order_form.html', {
'form': form, # przekazujemy formę do html-a aby mogła zostać wyświetlona
})