У меня есть проблемы с отображением from типа ModelForm в Django
Я пробую учебник по Django формам и выпадающим спискам, но у меня не получается показать форму, возможно учебник по старой версии Django, но я перепробовал все, я не понимаю, что я упускаю.
Сначала мой Forms.py
from django import forms
from .models import Person, City
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'birthdate', 'country', 'city')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['city'].queryset = City.objects.none()
Модель:
from django.db import models
class Country(models.Model):
class Meta:
db_table = 'countries'
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class City(models.Model):
class Meta:
db_table = 'cities'
name = models.CharField(max_length=30)
state_id = models.BigIntegerField(null=True)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Person(models.Model):
class Meta:
db_table = 'people'
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
Шаблон:
{% block content %}
<h2>{% trans "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>
{% endblock %}
И, наконец, View.py
from django.shortcuts import render
from django.views.generic import ListView, CreateView, UpdateView
from django.views.generic.edit import FormView
from django.urls import reverse_lazy
from .models import Person
from .forms import PersonForm
class PersonListView(ListView):
model = Person
context_object_name = 'people'
class PersonCreateView(CreateView):
model = Person
form_class = PersonForm
# no longer necessary and already defined in Forms.py
fields = ('name', 'berthdate', 'country', 'city')
success_url = reverse_lazy('person_changelist')
class PersonUpdateView(UpdateView):
model = Person
form_class = PersonForm
fields = ('name', 'birthdate', 'country', 'city')
success_url = reverse_lazy('person_changelist')
Urls.py
from django.contrib import admin
from django.urls import path, include
from countries import views
from django.conf.urls.i18n import i18n_patterns
urlpatterns = i18n_patterns(
path('admin/', admin.site.urls),
# person_list.html
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'),
prefix_default_language=False
)
В urls.py проблем нет, и в шаблоне все загружается правильно, кроме формы внутри таблицы. Ваша помощь будет очень признательна.