Reputation: 7612
I have a ton of fields that I need to layout (reorder) in a specific way the form (with some other extra html stuff). I created change_form.html file for my model, which itself works.
The problem is all examples are looping over the fields, I just want to refer to each field by name.
# this works
{% for fieldset in adminform %}
{% for line in fieldset %}
{% for field in line %}
<p>{{ field.field }}</p>
{% endfor %}
{% endfor %}
{% endfor %}
I know you can customise the admin.ModelAdmin with fieldsets, etc.. But that's not what I want.
I was trying different ways like below, but it doesn't work:
# assuming the admin model has the fields: first_name & last_name
{% block content %}
<!-- doesn't work !!! ->
{{ adminform.fieldsets.0.1.fields.first_name.field }}
{{ adminform.fieldsets.0.1.fields.last_name.field }}
<!-- neither does this -->
{{ adminform.fields.first_name.field }}
{{ adminform.fields.last_name.field }}
{% endblock %}
Now this doesn't work, is there any efficient way to directly access the fields I need?
Upvotes: 1
Views: 1120
Reputation: 3102
You can call object with {{ original }}
.
So if you have field: last_name you can call it in template like this {{ original.last_name }}
Upvotes: 2
Reputation: 7612
I was looking in the complete wrong direction. Its actually super simple, you can use it as follows.
When you have model with a field last_name
you can access the field:
# change_form.html (custom)
{% extends "admin/change_form.html" %}
{% block field_sets %}
# get the label
<label for="{{ adminform.form.last_name.label }}">
{{ adminform.form.last_name.id_for_label }}
</label>
# get the html widget
{{ adminform.form.last_name }}
# get the field value
{{ adminform.form.last_name.value }}
# create your own input (without the label)
<input name="{{ adminform.form.last_name.html_name }}">
# some other fields you can reference
{{ adminform.form.last_name.max_length }}
{{ adminform.form.last_name.required }}
{{ adminform.form.last_name.help_text }}
{{ adminform.form.last_name.label_suffix }}
{% endblock %}
Upvotes: 1
Reputation: 1149
U can create a ModelForm to be used in your ModelAdmin, check de docs -> https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
another way could be setting fields tuple, docs here -> https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields
Hope this drives U in the right path.
Upvotes: 0