Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register a Custom Form with Django Admin

In admin_forms.py I've written the following code:

class AdminForm(forms.Form):
    category = forms.ModelChoiceField(queryset=Category.objects.all())
    question = forms.CharField(widget=forms.Textarea)
    q_active = forms.BooleanField(initial=True)
    option = forms.CharField()
    option_active = forms.BooleanField(initial=True)

I want it get registered with Django Admin, so in my admin.py, I've written

from api.admin_forms import AdminForm
class EntryAdmin(admin.ModelAdmin):
    add_form = AdminForm
    fieldsets = (
        ('Category', {
            'fields': 'category'}),
        ('Question', {'fields': ('question', 'q_active')}),
        ('Answer Option', {'fields': ('option', 'option_active')}),
        ('Selected Answer', {'fields': ('user_role', 'answer')}),
    )
admin.site.register(EntryAdmin)

Definitely, this is not how we can make it work. help please!

like image 891
abdullah Avatar asked Nov 13 '15 11:11

abdullah


People also ask

How do I automatically register all models in Django admin?

To automate this process, we can programmatically fetch all the models in the project and register them with the admin interface. Open admin.py file and add this code to it. This will fetch all the models in all apps and registers them with the admin interface.

What is admin site register in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.


1 Answers

You should set form instead of add_form.

class EntryAdmin(admin.ModelAdmin):
    form = AdminForm
    ...

When you register your model admin, you must provide the model as the first argument:

admin.site.register(Entry, EntryAdmin)

ModelAdmin does not have an attribute add_form, so setting it has no effect. The UserAdmin has an add_form attribute, which is used when adding new users.

like image 100
Alasdair Avatar answered Nov 15 '22 10:11

Alasdair