0

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
    })

1 Answer 1

1

Can you post your forms.py ? It should be done just like you want this with Django ModelForm.

You can even filter with some properties with it, like in example below:

class WarehouseForm(forms.ModelForm):
    forms.ModelChoiceField(required=False, widget=forms.Select, queryset=Item.objects.filter(name__in=['Test1', 'Test2']))

    class Meta:
        model = Warehouse
        fields = ['item', 'location']

Because I see that the problem is not in the forms, but actually using them.

You should have form passed into your template by the view, like this:

def some_view(request, pk):
    order = Order.objects.get(id = pk)
    form = OrderForm(instance = order)
    return render(request, 'yourtemplate.html', {'form':form})

Then in the html you can even write:

<form methodd="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type='submit' value="Submit">
</form>

If you want to render field by field, you can go with: {{ form.customer }}

If you truly want to just have a loop go with

{% for customer in form.fields.customer.choices.queryset %}
    <a class="dropdown-item" > {{ customer }}</a>
{% endfor %}

and it should more or less - work, but it will probably cause form.is_valid to not act as expected.

Sign up to request clarification or add additional context in comments.

4 Comments

It is passed by the view. I also added it to the question.
Everything works great and shows but i just can't get it to display in a for instead of writting .1 .2 .3 etc.
I know, but then the form looks very basic and there is no way in styling it.
Yes but it is supposed to be displayed in a dropdown list from bootstrap, so i have to acces every option from form.customer. I can do that by typing form.customer.1 then .2 and so on, but it only works for a small number of customers. So i would want it in a loop like this for i in form.customer and then pass the i as an id form.customer.i instead of form.customer.1 but it doesn't want to work when i do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.