Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to display a custom field only in change view (admin)
    primarykey
    data
    text
    <p>I'm totally new in Python and Django :) and i need some help.</p> <p><strong>What i want to do:</strong></p> <p>I have a model <em>Page</em> and i need to add a custom field "message" when someone try to update one object.</p> <p>Why? Because i'm building a revision system. This field, it's just an explanation about the change. So this field is not linked to the Page (but to another model PageRevision)</p> <p>After some research i managed to add this field to my form in the admin.py file, like this:</p> <pre><code>class PageAdminForm(forms.ModelForm): # custom field not backed by database message = forms.CharField(required=False) class Meta: model = Page </code></pre> <p>it's working, my field is now displayed...But i don't want this field everywhere. Just when someone try to update a Page object. i have found this answer <a href="https://stackoverflow.com/questions/6321916/different-fields-for-add-and-change-pages-in-admin">different-fields-for-add-and-change-pages-in-admin</a> but it's not working for me because it's a custom field (i think).</p> <p>The rest of my code in admin.py:</p> <pre><code>class PageAdmin(admin.ModelAdmin): form = PageAdminForm fields = ["title", "weight", "description", "message"] list_display = ["title", "weight", "description"] list_filter = ["updated_at"] def get_form(self, request, obj=None, **kwargs): if obj is None: # not working ? kwargs['exclude'] = ['message'] # else: # kwargs['exclude'] = ['message'] return super(PageAdmin, self).get_form(request, obj, **kwargs) def save_model(self, request, obj, form, change): if not obj.id: obj.author = request.user obj.modified_by = request.user wiki_page = obj.save() # save page in revision table revision = PageRevision(change=change, obj=wiki_page, request=request) # retrieve value in the custom field revision.message = form.cleaned_data['message'] revision.save() </code></pre> <p><strong>def get_form</strong> doesn't exclude my custom message field because i think it doesn't know is existence. If i put another field like title, it's works. So how to exclude the custom field from add view ?</p> <p>Thanks :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload