I am trying to set null=True
and blank=True
for a field using label_from_instance
.
But it cannot be set by defining a field in the model class
.
If I try to set it like the code below, I get an error.
fk_id = NameChoiceField(queryset=PkModel.objects.all().order_by('pk_name').distinct(), null=True, blank=True)
TypeError: init() got an unexpected keyword argument 'null'
How could I set null
and blank
in this case?
Here are the codes:
forms.py
from django import forms
from django.forms import ModelChoiceField
from .models import *
class NameChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return f'{obj.pk_name}'
class IndexForm(forms.ModelForm):
fk_id = NameChoiceField(queryset=PkModel.objects.all().order_by('pk_name').distinct())
class Meta:
model = FkModel
fields = '__all__'
models.py
from django.db import models
class PkModel(models.Model):
pk_id = models.IntegerField(verbose_name='pk_id',primary_key=True)
pk_name = models.CharField(max_length=20, verbose_name='pk_name')
class Meta:
verbose_name_plural = 'PkModel'
class FkModel(models.Model):
fk_code = models.CharField(max_length=20, verbose_name='fk_code', primary_key=True)
fk_id = models.ForeignKey(PkModel, to_field='pk_id', db_column='fk_id', verbose_name='fk_id',
on_delete=models.CASCADE, null=True, blank=True)
class Meta:
verbose_name_plural = 'FkModel'
Python 3.8
Django 3.2
CodePudding user response:
Use required=False
.
null
and blank
are for model fields, and describe valid data at the database level. In a form, you instead declare whether the field must be set for the form to be valid.