Реализация зависимого / связанного раскрывающегося списка с Django не работает - PullRequest
0 голосов
/ 09 июля 2020

Я пытаюсь создать зависимый раскрывающийся список с django, используя javscript. Я перешел по этой ссылке [Учебник] [1], но она не работает. Пожалуйста, найдите приведенные ниже коды и справку

Заранее спасибо.

Модель:

class Painter(models.Model):
painter_user_id = models.OneToOneField('account.CustomUser', on_delete=models.CASCADE)
painter_user = models.CharField(max_length=100)
painter_id = models.CharField(max_length=20, null=True, unique=True)
painter_ornot = models.CharField(choices=(('Painter', 'Painter'), ('Not painter', 'Not painter')), max_length=50,
                                 null=True)
tse_verified = models.CharField(max_length=10, null=True, choices=(('Yes', 'Yes'), ('No', 'No')))
registration_via = models.CharField(max_length=20, null=True)
painter_firstname = models.CharField(max_length=100)
painter_lastname = models.CharField(max_length=100)
painter_dob = models.DateField(null=True)
painter_address = models.CharField(max_length=200, null=True)
painter_pincode = models.CharField(max_length=6, null=True)
painter_regdate = models.DateField(auto_now_add=True, null=True)
painter_datecreated = models.DateTimeField(auto_now_add=True)
painter_city = models.ForeignKey(City, null=True, on_delete=models.SET_NULL)
painter_territory = models.ForeignKey(Territory, on_delete=models.SET_NULL, null=True)
painter_state = models.ForeignKey(State, null=True, on_delete=models.SET_NULL)
painter_dealer = models.ForeignKey(Dealer, null=True, on_delete=models.SET_NULL)
painter_tse = models.ForeignKey(TSE, null=True, on_delete=models.SET_NULL)
painter_asm = models.ForeignKey(ASM, null=True, on_delete=models.SET_NULL)
painter_rm = models.ForeignKey(RM, null=True, on_delete=models.SET_NULL)
painter_depot = models.ForeignKey(Depot, null=True, on_delete=models.SET_NULL)
painter_zone = models.ForeignKey(Zone, null=True, on_delete=models.SET_NULL)
painter_dgm = models.ForeignKey(DGM, null=True, on_delete=models.SET_NULL)
painter_balance = models.IntegerField(default=0)
bank_ac = models.IntegerField(null=True)
ifsc = models.CharField(max_length=11, null=True)
bank_name = models.CharField(max_length=100, null=True)
aadhar = models.CharField(max_length=16, null=True)
aadhar_pic_front = models.ImageField(upload_to='aadhar', default='user.png', null=True)
aadhar_pic_back = models.ImageField(upload_to='aadhar', default='user.png', null=True)

class Meta:
    permissions = (
        ('edit painter', 'can edit painter'),
        ('upload painter', 'can upload painter'),
        ('download painter', 'can download painter'),
    )

Формы:

class AddPainterForm(forms.ModelForm):
class Meta:
    model = Painter
    fields = ['painter_ornot', 'painter_user', 'painter_firstname', 'painter_lastname', 'tse_verified',
              'painter_dob', 'painter_tse',
              'painter_dealer', 'painter_address',
              'aadhar', 'aadhar_pic_front', 'aadhar_pic_back', 'painter_zone', 'painter_state', 'painter_city', 'painter_pincode']

    widgets = {
        'painter_ornot': forms.Select(
            attrs={'type': 'list', 'class': "form-control", 'placeholder': "Select"}),
        'first_name': forms.TextInput(
            attrs={'type': 'text', 'class': "form-control", 'placeholder': "First name"}),
        'last_name': forms.TextInput(
            attrs={'type': 'text', 'class': "form-control", 'placeholder': "Last name"}),
        'mobile': forms.TextInput(
            attrs={'type': 'text', 'class': "form-control", 'placeholder': "Mobile"}),
        'depot': forms.Select(
            attrs={'type': 'list', 'class': "form-control", 'placeholder': "Select depot"}),
        'tse_verified': forms.Select(
            attrs={'type': 'list', 'class': "form-control", 'placeholder': "Select"}),
        'tse': forms.Select(
            attrs={'type': 'list', 'class': "form-control", 'placeholder': "Select TSE"}),
        'dealer': forms.Select(
            attrs={'type': 'list', 'class': "form-control", 'placeholder': "Select Dealer"}),
        'aadhar': forms.NumberInput(
            attrs={'type': 'text', 'class': "form-control", 'placeholder': "Enter Aadhar Number"}),
        'aadhar_pic_front': forms.FileInput(
            attrs={'type': 'file', 'class': "form-control", 'placeholder': "Upload photo"}),
        'aadhar_pic_back': forms.FileInput(
            attrs={'type': 'file', 'class': "form-control", 'placeholder': "Upload photo"}),
        'dob': forms.DateInput(
            attrs={'type': 'date', 'class': "form-control", 'placeholder': "Date of birth"}),
        'address': forms.TextInput(
            attrs={'type': 'text', 'class': "form-control", 'placeholder': "Address"}),
        'city': forms.Select(
            attrs={'type': 'list', 'class': "form-control", 'placeholder': "Select city"}),
        'state': forms.Select(
            attrs={'type': 'list', 'class': "form-control", 'placeholder': "Select State"}),

        'pincode': forms.TextInput(
            attrs={'type': 'list', 'class': "form-control", 'placeholder': "Pin Code"}),
    }

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['painter_city'].queryset = City.objects.none()

вид:

def add_painter(request):
form = AddPainterForm
cities = City.objects.all()
last_painter = Painter.objects.last()
last_id = last_painter.id
if request.method == 'POST':
    p_uname = request.POST['painter_user']
    p_pwd = request.POST['painter_user']
    p_f_name = request.POST['painter_firstname']
    p_l_name = request.POST['painter_lastname']
    p_tse_verified = request.POST['tse_verified']
    p_tse = request.POST['painter_tse']
    p_dealer = request.POST['painter_dealer']
    p_aadhar = request.POST['aadhar']
    p_aadhar_pic_front = request.FILES['aadhar_pic_front']
    p_aadhar_pic_back = request.FILES['aadhar_pic_back']
    p_dob = request.POST['painter_dob']
    p_address = request.POST['painter_address']
    p_state = request.POST['painter_state']
    p_city = request.POST['painter_city']
    p_pincode = request.POST['painter_pincode']
    tse = TSE.objects.get(pk=p_tse)
    p_asm = tse.tse_asm.id
    p_rm = tse.tse_rm.id
    p_dgm = tse.tse_dgm.id
    p_depot = tse.tse_depot.id
    p_zone = tse.tse_zone.id
    p_territory = tse.tse_territory.id

    if CustomUser.objects.filter(mobile=p_uname).exists():
        messages.error(request, 'Mobile number already registered')
    elif Painter.objects.filter(aadhar=p_aadhar).exists():
        messages.error(request, "Aadhar already registered")
    else:
        user = get_user_model().objects.create(mobile=p_uname, password=p_pwd, first_name=p_f_name,
                                               last_name=p_l_name, role='Painter')
        user.set_password(p_pwd)
        user.save()
        group = Group.objects.get(name='Painter')
        user.groups.add(group)
        p_id = 'PR0' + str(last_id)
        newPainter = Painter(painter_firstname=p_f_name, painter_lastname=p_l_name, painter_zone_id=p_zone,
                             painter_dob=p_dob, painter_dealer_id=p_dealer, aadhar=p_aadhar,
                             aadhar_pic_back=p_aadhar_pic_back, aadhar_pic_front=p_aadhar_pic_front,
                             painter_istseverified=p_tse_verified, painter_pincode=p_pincode,
                             painter_address=p_address, painter_state_id=p_state, painter_city_id=p_city,
                             painter_tse_id=p_tse,
                             painter_asm_id=p_asm, painter_rm_id=p_rm, painter_dgm_id=p_dgm,
                             painter_depot_id=p_depot, painter_territory_id=p_territory,
                             painter_user=p_uname, registration_via='Admin', painter_id=p_id, painter_user_id=user)

        newPainter.save()
        messages.success(request, 'Painter added')

context = {'form': form, 'cities': cities}
return render(request, 'add_painter.html', context)


def load_cities(request):
   state_id = request.GET.get('painter_state')
   print(state_id)
   cities = City.objects.filter(city_state_id=state_id).order_by('city_name')
   return render(request, 'city_dropdown_list_options.html', {'cities': cities})

url:

urlpatterns = [
path('painters', views.painter, name='painter'),
path('ajax/load-cities/', views.load_cities, name='ajax_load_cities'),
path('add_painter', views.add_painter, name='add_painter'),]

шаблон:

{% extends 'base.html' %}

{% block content %}
<hr>
{% for message in messages %}
    {% if message == 'Painter added' %}
        <p style="text-align: center; font-size: medium; font-weight: bold; color: green ">. 
 {{ message }}</p>
    {% else %}
        <p style="text-align: center; font-size: medium; font-weight: bold; color: red ">{{ 
    message }}</p>
    {% endif %}
 {% endfor %}
 <form method="post" id="form" data-cities-url="{% url 'ajax_load_cities' %}" action="{% url 
'add_painter' %} ">
{% csrf_token %}
<table>
  {{ form.as_table }}
</table>

<button type="submit">Save</button>
    <script>
    $("#painter_state").change(function () {
        var url = $("#form").attr("data-cities-url");  // get the url of the `load_cities` view
        var stateID = $(this).val();  // get the selected country ID from the HTML input

        $.ajax({                       // initialize an AJAX request
            url: '{% url 'ajax_load_cities' %}',  // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
            data: {
                'painter_state': stateID       // add the country id to the GET parameters
            },
            success: function (data) {   // `data` is the return of the `load_cities` view function
                $("#painter_city").html(data);  // replace the contents of the city input with the data that came from the server
            }
        });

    });
</script>
{%endblock%}

Я пытаюсь создать зависимый раскрывающийся список с помощью django, используя javscript. Я перешел по этой ссылке [Учебник] [1], но она не работает. Пожалуйста, найдите приведенные ниже коды и справку

Заранее благодарим.

...