Django: how to choose from a list based on the previous selection?

Assume that I am a furniture manufacturer. I have many customers and each of them buy from me many diffrent products. In Django I will write class for Customer, Product and the most important for me Order from customer.

How can I do something like filter for that?

class Customer(models.Model):
     name = models.CharField(max_length=10, blank=False)

class Product(models.Model):
    name = models.CharField(max_length=10, blank=False)
    customer_number_product = models.SmallIntegerField(max_length=6, blank=False)
    customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE())

class Order(models.Model):
    order_number = models.IntegerField(max_length=4, blank= False)
    customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE())
    orderdate = datetime...
    deliverydate = datetime...
    ordered_product = HERE IS A PROBLEM 

I need to choose from the Product database only one product belongs to specific customer. I do not want to choose from list with thousands products which I sell to all my customers.

These are just your definitions for your models. Your various views and forms are responsible for doing whatever filtering is required to build and render the desired page(s).

But how can I build an instance with these information and in this way, with drop down list with products for one customer? Could you give me any advices?

models.py
class Customer(models.Model):
    name = models.CharField(max_length=10, blank=False)

class Product(models.Model):
    name = models.CharField(max_length=10, blank=False)
    customer_number_product = models.SmallIntegerField(max_length=6, blank=False)
    customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE())

class Order(models.Model):
    order_number = models.IntegerField(max_length=4, blank= False)
    customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE())
    orderdate = datetime...
    deliverydate = datetime...
    ordered_product = models.OneToOneField(Product, on_delete=models.CASCADE())

views.py
def new_order(request):
    form = OrderForm(request.POST or None)
            what sould I write here ? how make a filter for one definition?    
    return render(request, 'new_Order', {'form':form})

In your view (new_order), how do you know what customer is requesting the view?

What does your OrderForm look like?

Note - an Order is not a OneToOne relationship with Product, unless the customer may only ever place one order for that product. If the customer is able to place multiple orders for a Product, then it should be a ForeignKey relationship.

Likewise, can a Product only ever be ordered by only one Customer? If so, then you’re ok. But if not - if multiple Customers can place orders for the same product, then you do not want a ForeignKey relationship between Product and Customer. (You probably don’t want a relationship there at all - only between the Order and Customer.)

Hello everyone,
I think that I have found the solution of my problem and now I can nam it - Dependent Cascading Dropdown List. Here is the link to video

BUT (there is also “but” :slight_smile: ) I have a problem that it does not work :((((
Please check what I do wrong:

index.html

<!doctype html>
<html lang="en">
<head>
    <!--<meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> -->
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
            $(document).ready(function()
            {
                var $select1=$('#select1'),
                    $select1=$('#select2'),
                    $options=$select2.find('option');
                    $select1.on('change',function()
                    {
                        $select2.html($options.filter('[value="'+this.value+'"]'));
                    }).trigger('change');
            });
    </script>

</head>
<body>
    <div style="text-align:center">
        <h2> how to Cerate DDL jQuery Select2</h2>
        <h4>Django Web tutorials</h4>
        <hr/>
        <select id="select1">
            <option selected disabled="true">--Wybierz--</option>
            {% for products in Product%}
            <option value="{{products.id}}">{{products.ksztalt}}</option>
            {% endfor%}
        </select>

        <select id="select2">
            <option selected disabled="true">==wybierz==</option>
            {% for items in Item%}
            <option value="{{items.material_id}}">{{items.wymiar}}</option>
            {% endfor%}
        </select>



    </div>


</body>
</html>

views.py

from django.shortcuts import render
from .models import Material, WymiarMat
# Create your views here.
def magazynddl(request):
	prodobj=Material.objects.all()
	itemobj=WymiarMat.objects.all()
	return render(request, 'Index.html',{"Product":prodobj, "Item":itemobj})

models.py

from django.db import models

# Create your models here.


class Material(models.Model):
    """Tworzę klase do wyboru materiału"""

    DRUT = 1
    TASMA = 2

    KSZTALT = (
        (DRUT, ('Drut')),
        (TASMA, ('Tasma')),
    )
    ksztalt = models.PositiveSmallIntegerField(
        choices=KSZTALT,
        default=DRUT,
        unique=True,
        blank=False,
        null=True,
        help_text='kształt materiału'
    )

    class Meta:
        db_table='materialtab'

    def __str__(self):
        """Ciąg znaków jaki ma reprezentować Obiekt """
        if self.ksztalt == 1:
            cos = 'Drut'
        elif self.ksztalt == 2:
            cos = 'Taśma'
        else:
            cos = 'cos nie trybi'

        return f'{cos}'

class WymiarMat(models.Model):
    """Tworzę wymiary średnicy drutu lub taśmy"""
    material = models.ForeignKey(Material, on_delete=models.CASCADE)
    wymiar = models.CharField('Wymiar',max_length=10, unique=True, blank=False)

    def __str__(self):
        """Ciąg znaków jaki ma reprezentować Obiekt """
        #materialpom=self.material
        #if materialpom =='Drut':
        #    cos = '\u2300'
        #else:
        #    cos = 'gg'
        return f'{self.wymiar}'

obraz

Please do not leave me alone with that :stuck_out_tongue:

Without looking at this in too much detail, shouldn’t the second line be $select2=$('#select2'),?

1 Like

Hehehe It is working :slight_smile: I was looking much time at this and movie, and have not seen it :(((
You are my hero.

Could you also give me any website or manual to solve that part of code:

<script>
            $(document).ready(function()
            {
                var $select1=$('#select1'),
                    $select1=$('#select2'),
                    $options=$select2.find('option');
                    $select1.on('change',function()
                    {
                        $select2.html($options.filter('[value="'+this.value+'"]'));
                    }).trigger('change');
            });
    </script>

I do not what happen here ;/

I’m not sure I understand what you’re asking here. Are you asking why your original version didn’t work?

If so, I’ll ask you - what’s the value of $select2 at the third line in that section?

I am sorry, the correct version is as you noted:

<script>
            $(document).ready(function()
            {
                var $select1=$('#select1'),
                    $select2=$('#select2'),    - correct line
                    $options=$select2.find('option');
                    $select1.on('change',function()
                    {
                        $select2.html($options.filter('[value="'+this.value+'"]'));
                    }).trigger('change');
            });
    </script>

My question is about this whole code. How it works step by step, line by line…

e.g. as below I understand that I define the variebles

 var $select1=$('#select1'),
     $select2=$('#select2'),

and what about next lines?

I would like thank you so much for your time and support!!!

I am a beginner and I am still looking for teaching aids. I would like to understand as much as can to change later some code lines e.g. to add one more select3

Well, this is all JavaScript code - and I’m going to guess that it’s using jQuery as well. So those would be your resources for further research.
(No, I don’t have any specific recommendations for either.)