Reputation: 11686
i've been reading about this in the docs but couldn't find anything.
Do you recommend to extend custom forms in Django?
Here's my problem. I'm using Biblion to write a blog application. The thing is that i don't want to use the default behavior (create blog posts from the admin site). There's this form: https://github.com/eldarion/biblion/blob/master/biblion/forms.py#L13 that has custom logic to save the Post (and make some parsing).
I'd love to extend this form for some custom actions. For example, i'd like to make some users create blog Posts, but don't allow them to make published. Instead I should check and moderate them. So, for that sake i'm trying with something like:
class PostForm(AdminPostForm):
publish = forms.BooleanField(
required = False,
widget = forms.HiddenInput # don't show it
)
It's working now, but i wanted to ask you guys if there's some other option (i could prevent it to be shown in my template, iterating over the form fileds, but don't like this option very much).
Other option is to just copy/paste the code from AdminPostForm
, but, doesn't seem like a good option neither. But if there's no simple way to customize the form for several cases, i'll just do that.
Ideas?
Thanks!!
Upvotes: 1
Views: 931
Reputation: 391852
I'd love to extend this form for some custom actions
Stop right there.
Forms don't have "actions". Forms are for little more than validating input. ModelForms include an extension to save valid input. The focus is validating input.
If you want "actions", you should be writing view functions.
You might also need to create a custom admin action https://docs.djangoproject.com/en/1.3/ref/contrib/admin/actions/ (not a Form)
If you want to remove an item from a from, do this.
Use a ModelForm. https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/
List the field in the "exclude" value. https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form
Upvotes: -4
Reputation: 55197
If you want to implement a per-user logic in your forms you might want to extend your ModelAdmin
instead of the form.
Here, you'd want to override the ModelAdmin
's save_form
method.
save_form
takes 3 arguments in addtion to self
: request, form, change
. You would be doing the following:
def save_form(self, request, form, change):
instance = super(MyModelAdmin, self).save_form(request, form, change)
if instance.published and not user.has_perm('mark_published'):
instance.published = False #You could be displaying a message here.
return instance
Usually, Django classes have a lot of hooks so you can plug your custom logic just there.
Here, you're just hiding the input, but anyone with a decent browser would be able to modify this value and post True
in your published
input.
Upvotes: 5