I'm able to insert (lame) static text onto the change form admin page, but I'd really like it to use the context of the current object being edited!
For instance, I want to format on the MyObject change form a URL to include the ID from a ForeignKey connected object (obj
) as a link.
My admin objects:
class MyObjectChangeForm(forms.ModelForm):
class Meta:
model = MyObject
fields = ('field1', 'obj',)
class MyObjectAdmin(admin.ModelAdmin):
form = MyObjectChangeForm
list_display = ('field1', 'obj')
def render_change_form(self, request, context, *args, **kwargs):
self.change_form_template = 'admin/my_change_form.html'
extra = {'lame_static_text': "something static",}
context.update(extra)
return super(MyObjectAdmin, self).render_change_form(request,
context, *args, **kwargs)
My template templates/admin/my_change_form.html
:
{% extends "admin/change_form.html" %}
{% block form_top %}
{{ lame_static_text }}
<a href="http://example.com/abc/{{ adminform.data.obj.id }}?"/>View Website</a>
{% endblock %}
The {{adminform.data.obj.id}}
call obviously doesn't work, but I'd like something along those lines.
How do I insert dynamic context from the current object into the admin change form?
To customize any default page we need to create our own template directory, create the file using the same name and position in the parent directory and inform Django to use it. To go deeper, we will customize the 404 error page and configure Django to use it.
Show activity on this post. The most straightforward answer is "no". As the Django Book says, the admin is for "Trusted users editing structured content," in this case the structured content being models arranged in hierarchies and configured through settings.py.
Add your extra context in change_view
class MyObjectAdmin(admin.ModelAdmin):
# A template for a very customized change view:
change_form_template = 'admin/my_change_form.html'
def get_dynamic_info(self):
# ...
pass
def change_view(self, request, object_id, form_url='', extra_context=None):
extra_context = extra_context or {}
extra_context['osm_data'] = self.get_dynamic_info()
return super(MyObjectAdmin, self).change_view(
request, object_id, form_url, extra_context=extra_context,
)
I believe the magic variable you seek is 'original', this contains the python object the change form is editing:
<a href="http://example.com/abc/{{ original.id }}?"/>View Website</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With