Define a Custom Form for use in Django's ModelAdmin Add View
I'm trying to expose a Django model in admin using the ModelAdmin class. ModelAdmin seems to assume you use the same form for add and change. I'd like the add_view to use a simplified form that only lists a handful of required fields. After submission, it'll redirect to the change_view and use ModelForm's default form to render nearly all fields.
What's the easiest way to do this? I've inspected the code, but I don't see a clear way. ModelAdmin tends to refer to a single self.form reference in both the add_view and change_view. I'm thinking of overriding add_view(), but I don't want to reimplement all the code. It might be more efficient to overr开发者_StackOverflowide get_form(), but I don't see how to detect whether get_form() is being called during add_view or change_view.
get_form()
is passed an obj
parameter when called during change_view
. Simply detect that return the new form/tweak parameters as needed.
For example:
class MyModelAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
# hide every other field apart from url
# if we are adding
if obj is None:
kwargs['fields'] = ['url']
return super(MyModelAdmin, self).get_form(request, obj, **kwargs)
Will force the form to only display the "url" field when adding and everything else otherwise.
精彩评论