Django - dynamicznie wyświetlanie pól w formularzu

0

Witam,
Mam pytanie. Jak można dynamicznie zmieniać wyświetlane pola w formularzu?
Mam kilka linijek kodu
models.py

from django.db import models

class Country(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class City(models.Model):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class Person(models.Model):
    name = models.CharField(max_length=100)
    birthdate = models.DateField(null=True, blank=True)
    country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True)
    city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.name

urls.py

from django.urls import path, include

from . import views

urlpatterns = [
    path('', views.PersonListView.as_view(), name='person_changelist'),
    path('add/', views.PersonCreateView.as_view(), name='person_add'),
    path('<int:pk>/', views.PersonUpdateView.as_view(), name='person_change'),
    path('ajax/load-cities/', views.load_cities, name='ajax_load_cities'),  # <-- this one here

]

no i views.py

from django.views.generic import ListView, CreateView, UpdateView
from django.urls import reverse_lazy
from .models import Person, City
from django.shortcuts import render

class PersonListView(ListView):
    model = Person
    context_object_name = 'people'

class PersonCreateView(CreateView):
    model = Person
    fields = ('name', 'birthdate', 'country', 'city')
    if Person.city =='Warszawa':
        fields = ('name', 'country', 'city')
    success_url = reverse_lazy('person_changelist')

class PersonUpdateView(UpdateView):
    model = Person
    fields = ('name', 'birthdate', 'country', 'city')


    success_url = reverse_lazy('person_changelist')

def load_cities(request):
    country_id = request.GET.get('country')
    cities = City.objects.filter(country_id=country_id).order_by('name')
    return render(request, 'hr/city_dropdown_list_options.html', {'cities': cities})

person_form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h2>Person Form</h2>
  <form method="post" novalidate>
    {% csrf_token %}
    <table>
      {{ form.as_table }}
    </table>
    <button type="submit">Save</button>
    <a href="{% url 'person_changelist' %}">Nevermind</a>
  </form>
</body>
</html>

city_dropdown_list_options.html

<option value="">---------</option>
{% for city in cities %}
<option value="{{ city.pk }}">{{ city.name }}</option>
{% endfor %}

dokładnie chodzi o tą część kodu

class PersonCreateView(CreateView):
    model = Person
    fields = ('name', 'birthdate', 'country', 'city')
    if Person.city =='Warszawa':
        fields = ('name', 'country', 'city')

Czy w ogóle to może działać? Jak to zrobić aby po wybraniu miasta Warszawa ilość pól w formularzu uległa zmianie.

1

Dynamicznie tego nie osiągniesz poprzez python, a tym bardziej django. Naucz się używać JS i po stronie przeglądarki takie operacje realizuj.

Ewentualnie możesz po wybraniu miasta przekierować na kolejną stronę, gdzie z pozomu django (statycznie) wyrenderujesz stronkę z docelowym formularzem.

1 użytkowników online, w tym zalogowanych: 0, gości: 1