Django fieldsets problem on save
I did the following. Not sure if it's right:
class FooAdmin(admin.ModelAdmin):
fieldsets = (
# ...
)
other_fieldsets = (
# ...
)
def get_fieldsets (self, request, obj = None):
if some_cond:
return self.other_fieldsets
return self.fieldsets
Update: def
missing. But of course, that wasn't the problem 开发者_开发知识库once I get a Django checkup error.
Now, on this admin model, when I save it gives the standard field verification error on top, but no field is marked as invalid. I tried setting all the fields to blank = True
, but I can only make it work removing get_fieldsets().
As pointed by Yuji Tomita, you can't use get_fieldsets() without overriding the form with get_form():
class MyModelAdmin(admin.ModelAdmin):
def get_fieldsets(self, request, obj=None):
if obj:
return [(None, {'fields': ('field_c', 'field_b')})]
return [(None, {'fields': ('field_a', 'field_b', 'field_c')})]
def get_form(self, request, obj=None, **kwargs):
if obj:
defaults = {'exclude': ('field_a',)}
else:
defaults = {}
defaults.update(kwargs)
return super(MyModelAdmin, self).get_form(request, obj, **defaults)
As I was just splitting the form into fieldsets and showing them according to users, I think that in this case Django still think it needs to validate the fields that aren't actually in the form due to get_fieldsets(). Once these fields are excluded in get_forms(), things started to work.
Many thanks, Yuji Tomita.
There is obviously a syntax error here. You need def
keyword, to define a function. Like this:
def get_fieldsets (self, request, obj = None):
if some_cond:
return self.other_fieldsets
return self.fieldsets
But this won't work either either (although syntactically correct), because it must be called by the admin.
The problem is, that you are trying to have different fieldsets depending on the request sent by the user. I don't think that's currently possible, because you set fieldsets statically in a class once and for all. Could you explain, what exactly you are trying to achieve, maybe we can find some solution.
精彩评论