Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a hidden field in the admin site

How can I create a fully hidden field (input and label) in the admin site? I know about the exclude property, but it fully excludes the field from the template, while I need it in the web page, but hidden:

class OutForm(ModelForm):
    reply_to = forms.ModelChoiceField(queryset=InMessages.objects.all(), widget=forms.HiddenInput)

In the admin template I actually can hide a field, but not its label.

like image 722
gigimon Avatar asked Feb 15 '11 01:02

gigimon


1 Answers

The Django admin does not support hidden fields yet. There is an open ticket for that: https://code.djangoproject.com/ticket/11277

However, there are workarounds that don't require jQuery. The admin forms are rendered using admin/includes/fieldset.html. If you override this template, you can inject a CSS class to denote the row for hiding:

<div class="form-row
    {% if line.fields|length_is:'1' and line.errors %} errors{% endif %}
    {% for field in line %} {{ field.field.name }}
      {% if field.field.is_hidden %} has-hidden-field{% endif %}  # add this part
    {% endfor %}">

this is actually a single line in the file, I've expanded it to make it more readable.

( Neat detail: for an StackedInline/TabularInline objects, you can specify the template as variable in Python code. )

Next, you can hide that row in your CSS:

.form-row.has-hidden-field {
    display: none;
}

Which you can load via your admin page:

{% block extrastyle %}{{ block.super }}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}mysite/admin.css" />{% endblock %}

or by using the media definition in the modeladmin:

class Media:
    css = {'all': ('mysite/admin.css',)
like image 168
vdboor Avatar answered Oct 02 '22 16:10

vdboor