当我加载页面“ sportsman.html” 时,我看不到外键表单。但是,当调用“提交”按钮(向数据库发送请求)时,会出现 ForeignKey ,并且一切正常。可能是什么问题呢?我以为这是由于HTML模板引起的,但不是。
models.py:
class Sportsman(models.Model):
first_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Имя')
last_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Фамилия')
middle_name = models.CharField(max_length=64, blank=True, null=True, default=None,
verbose_name='Отчество')
email = models.EmailField(max_length=128, blank=True, null=True, default=None, verbose_name='Емейл')
phone = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Номер тел.')
dob = models.DateField(default=None, null=True, blank=True, verbose_name='Дата рожд-я')
gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True, default=True, verbose_name='Пол')
age = models.ForeignKey(Age_category, on_delete=models.CASCADE, null=True, blank=True, default=True, verbose_name='Возраст. кат-ия')
def __str__(self):
return "Спортсмен(ка): %s %s, почта: %s" % (self.first_name, self.last_name, self.email)
class Meta:
verbose_name = 'Спортсмен'
verbose_name_plural = 'Спортсмены'
def save(self, *args, **kwargs):
super(Sportsman, self).save(*args, **kwargs)
views.py:
def sportsman(request):
documents = Document.objects.filter(is_active=True)
gender = Gender.objects.filter(is_active=True)
if request.method == "POST":
form = SportsmenForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return render(request, 'sportsman/sportsman.html', locals())
forms.py:
class SportsmenForm(forms.ModelForm):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
middle_name = forms.CharField(required=True)
email = forms.EmailField(required=True)
phone = forms.CharField(required=True)
dob = forms.DateField(required=True)
country = forms.CharField(required=True)
region = forms.CharField(required=True)
town = forms.CharField(required=True)
age = forms.ModelChoiceField(queryset=Age_category.objects.filter(is_active=True), required=True)
gender = forms.ModelChoiceField(queryset=Gender.objects.filter(is_active=True), required=True)
trainer = forms.CharField()
class Meta:
model = Sportsman
exclude = ['created', 'updated']
HTML:
<div class="form-select">
<label for="gender">Пол:</label>
{{ form.gender }}
</div>
<div class="form-select">
<label for="age">Возрастная категория:</label>
{{ form.age }}
</div>