ModelForm, ModelFormSet template questions

I am using Django 4 and htmx and I am not sure I understand how best to use the template-based form rendering.

class TechForm(forms.ModelForm):
        class Meta:
            model = Technique
            fields = ['name', 'notes',]
           template_name = 'architech/forms/TechForm.html'
    
        class Media:
            css = {'all': ('sakura.css',)}

To turn this into a ModelFormset, I called modelformset_factory:

TechFormSet = forms.modelformset_factory(model=Technique, form=TechForm)

I hoped the formset instances would be rendered with the Form template (which has some htmx), but instead it seems to be a default form. I guess a formset is importantly different to a bunch of forms (adds management-form etc), so perhaps I need to spell it out in the template, but I don’t want to repeat myself.

Have you verified that your form template works outside of using it in a formset?

The most common mistake I’ve seen posted on here are people putting their form template in their base template directory instead of in the apps’ template directory.

So from what you’re specifying, your TechForm.html template would need to be in a directory something like:
project_dir/app_dir/templates/architech/forms.

1 Like

Thanks Ken, yes, that’s where it is. I think my mistake is that the template_name isn’t a meta property, its just a property of the class. I really don’t have much grip on why some things are in Meta and others aren’t.

class TechForm(forms.ModelForm):
     class Meta:
            model = Technique
            fields = ['name', 'notes',]
        
     template_name = 'architech/forms/TechForm.html'
    
     class Media:
            css = {'all': ('sakura.css',)}

Something that might help in most cases (at least every case I can think of right off-hand) when thinking about this -

A model form is a form that has some parts of the form “automatically generated” by the meta class. Everything in that category belongs in Meta. Everything that is part of the form itself - generally anything that would be in a non-model form - is part of the form, not part of Meta. (Note that there’s no Meta class in a standard form)

1 Like