models.py
class Test(models.Model):
name = models.CharField(max_length=256)
slug_name = models.CharField(max_length=256)
template = models.BooleanField("Is Template",default=False)
@staticmethod
def template_as_tuple():
return Test.objects.filter(template=True).values_list('id','name')
forms.py
class Test2(forms.ModelForm):
templates = forms.ChoiceField(choices=Catalogue.predefined_settings_as_tuple(), required=False)
path = orms.FileField()
问题是当我在模型中添加模板时,它不会显示在forms.py中。我需要重新启动网络服务器才能显示更新
答案 0 :(得分:3)
摆脱那种静态方法。在表单中执行此操作:
class Test2(forms.ModelForm):
templates = forms.ModelChoiceField(queryset=Test.objects.filter(template=True))
答案 1 :(得分:1)
@ Daniel的答案是正确的,但是如果您经常过滤对象,custom manager可能更合适:
class TemplateFilter(models.Manager):
def get_query_set(self):
return super(TemplateFilter, self).get_query_set().filter(template=True)
class Test(models.Model):
name = models.CharField(max_length=256)
slug_name = models.CharField(max_length=256)
template = models.BooleanField("Is Template",default=False)
objects = models.Manager()
templates = TemplateFilter()
class Test2(forms.ModelForm):
templates = forms.ModelChoiceField(queryset=Test.templates.all())