How can I set up filtering in the form model of one field based on another when selecting?

I have 2 model tables. In the first table I have a form in the set in which there is one interesting field. This field can have the same values.

If we consider the second table model - then in the second table model I placed 2 fields from the first table.

And in these two fields - there is a field in which there can be duplicate values. I would like, if possible, to enter data into the second table - taking into account: selection of data from the city field and most importantly -

  • so that after selecting in the city field - some filtering of the second field occurs. For example, filtering of two fields occurs according to the selected first field and is substituted into the second field.

How can this be done. I select the city field - and so that the second field is filtered.

How can I set up filtering in the form model of one field based on another when selecting?

Help me please, I will be glad to any hint on how to do this?

from django.db import models

# Create your models here.


TYPE_OBJECT = [
    ("1", "Котельная"),
    ("2", "Сети"),
    ("3", "БМК"),
    ("4", "ЦТП"),
    ("5", "ТГУ"),
]

TYPE_WORK = [
    ("1", "Реконструкция"),
    ("2", "Капитальный ремонт"),
    ("3", "Строительство"),
]

TYPE_CITY = [
    ("1", "Бронницы"),
    ("2", "Луховицы"),
    ("3", "Павловский Посад"),
    ("4", "Раменское"),
    ("5", "Шатура"),
]

class ArkiOneObject (models.Model):
    city = models.CharField(
        choices=TYPE_CITY,
    verbose_name="Выберите ОМСУ")
    typeobject = models.CharField(
        choices=TYPE_OBJECT,
    verbose_name="Выберите тип объекта")
    typework = models.CharField(
        choices=TYPE_WORK,
    verbose_name="Выберите тип работ")
    nameobject = models.TextField(verbose_name="Наименование объекта")
    def __str__(self):
        return self.nameobject, self.city 

 
    
class ArkiTwoObject (models.Model):
    city = models.OneToOneField(ArkiOneObject, verbose_name="Выберите ОМСУ", on_delete=models.CASCADE)
    nameobject = models.OneToOneField(ArkiOneObject, verbose_name="Наименование объекта", on_delete=models.CASCADE)
    power_lenth = models.FloatField(verbose_name="Мощность или длина")
    potr_msd = models.IntegerField(verbose_name="Кол-во Потребители МСД")
    potr_cityzen = models.IntegerField(verbose_name="Кол-во Жители")
    potr_social = models.IntegerField(verbose_name="Кол-во Социальные")
    value_budget = models.FloatField(verbose_name="Объём финансирования")
    podryadchik = models.CharField(verbose_name="Подрядчик")
    date_contract = models.DateField(verbose_name="Дата заключения контракта")
    zena_contr = models.FloatField(verbose_name="Цена контракта")  
    

from django import forms
from .models import *


class FormOne (forms.ModelForm):
    class Meta:
        model = ArkiOneObject
        fields = "__all__"



class FormTwo (forms.ModelForm):
    class Meta:
        model = ArkiTwoObject
        fields = "__all__"
                

                        from django.shortcuts import render, redirect
from django.template import context
from django.http import HttpResponse
import pandas as pd
from .models import *
from .forms import *

def index(request):
    context={}

    return render(request, 'index.html', context)



def formone(request):
    context = {}
    formone = FormOne(request.POST or None)
    if formone.is_valid():
        formone.save()

        return redirect("formone")
    context['formone'] = formone
    return render(request, "formone.html", context)


def formtwo(request):
    context = {}
    formtwo = FormTwo(request.POST or None)
    if formtwo.is_valid():
        formtwo.save()

        return redirect("formtwo")
    context['formtwo'] = formtwo
    return render(request, "formtwo.html", context)    


def table(request):
    context = {}
    table = ArkiTwoObject.objects.all()
    table = pd.DataFrame.from_records(table.values())

    context['table'] = table

    table_2 = ArkiOneObject.objects.all()
    table_2 = pd.DataFrame.from_records(table_2.values())
    print(table_2)

    context['table_2'] = table_2
    return render(request, "table.html", context)


# Create your views here.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>title</title>
</head>
<body>
    <div>
        <form method="POST" class="post-form">
            {% csrf_token %} {{formone.as_p}}
            <button type="submit" class="button">Отправить</button>
        </form>
    </div>
    
</body>
</html>

Can me use this ?

Is it possible to somehow adapt something similar to my problem?

I would like a list to appear in the form based on data from another list
Select from the second field - filtering data - (content) depending on the received values ​​of the first field.
For example.
London Cafe
London Restaurant
London Fast Food
Manchester Pizzeria
Manchester Burgers

I select a city in the form field and the second field is filtered by establishments.

class ExcludedDateForm(ModelForm):
    class Meta:
        model = models.ExcludedDate
        exclude = ('user', 'recurring',)
    def __init__(self, user=None, **kwargs):
        super(ExcludedDateForm, self).__init__(**kwargs)
        if user:
            self.fields['category'].queryset = models.Category.objects.filter(user=user)
class FilterByUserMixin(LoginRequiredMixin):
    """
    Filters the queryset with `self.request.user` in a specified `user_field` field. `user_field` defaults to "user".
    """
    user_field = "user"
    
    def get_queryset(self, *args, **kwargs):
        return (
            super()
            .get_queryset(*args, **kwargs)
            .filter(**{self.user_field: self.request.user})
        )
class Book(models.Model):
    author = models.ForeignKey(MyUser, on_delete=models.RESTRICT)
    number_pages = models.PositiveIntegerField()
    title = models.CharField(max_length=1000)
class BookUpdateView(FilterByUserMixin, UpdateView):
    model = Book
    template_name = "book/my_book_update_template.html"
    fields = ["number_pages", "title"]
    success_url = reverse_lazy("book-update-success")
    user_field = "author"

This UpdateView will ensure that the current user can only edit books he is an author of. We can’t modify the queryset property directly because we don’t have access to request.user yet.

Our custom queryset will be used in the get_object method, which gets called in the post method. If the object doesn’t match Django will throw a 404 page.

You can add more filtering specific to the view by overwriting the get_queryset method and then calling super.

Share

Edit

Follow

How to select from the second field in the form - filtering data depending on the values of the first field?

It seems like you want to change the selection options on the rendered page.

I think there are two approaches:

  • Request the sub-options based on the selected option via JavaScript and render the response.
  • Pre-load all sub-options and show/hide them dynamically depending on the selected option.

Either way, I believe JavaScript is necessary.