1

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()

The problem is when i add templates in the models it is not shown in the forms.py. I need to restart the webserver for the updates to be shown

2 Answers 2

3

Get rid of that staticmethod. Do this in the form instead:

class Test2(forms.ModelForm):
    templates = forms.ModelChoiceField(queryset=Test.objects.filter(template=True))
Sign up to request clarification or add additional context in comments.

Comments

1

@Daniel's answer is correct, but if you will be filtering the objects often, a custom manager might be more appropriate:

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.