简体   繁体   中英

adding form styling to django forms

I am currently in the process of adding a theme to the admin of django one issue I have found it adding styling to the forms is that it is very difficult and I can't find much useful documentation on it. The only real thing I need to do is add classes to the form elements so that they match the theme I am using is this possible and if so how would you go about doing it the code I am currently using is very basic and the basic code included in the standard theme does anybody know how to add classes to these standard bits of code bellow is what I have.

  {% if is_popup %}
        <input type="hidden" name="_popup" value="1" />
  {% endif %}
  {% if save_on_top %}
        {% block submit_buttons_top %}
            {% submit_row %}
        {% endblock %}
  {% endif %}
  {% if errors %}
        <p class="errornote">
                {% blocktrans count counter=errors|length %}
                     Please correct the error below.
                     {% plural %}
                     Please correct the errors below.
                {% endblocktrans %}
        </p>
        {{ adminform.form.non_field_errors }}
  {% endif %}

 {% block field_sets %}
        {% for fieldset in adminform %}
                {% include "admin/includes/fieldset.html" %}
        {% endfor %}
 {% endblock %}

 {% block after_field_sets %}{% endblock %}

 {% block inline_field_sets %}
        {% for inline_admin_formset in inline_admin_formsets %}
                {% include inline_admin_formset.opts.template %}
        {% endfor %}
 {% endblock %}

 {% block after_related_objects %}{% endblock %}

 {% block submit_buttons_bottom %}
        {% submit_row %}
 {% endblock %}

There are a lot of ways to do this, but certainly one way would be to overwrite all the widgets in your ModelAdmin rather than in the template. That could look something like this:

from django.db import models
from django.contrib import admin
from django.forms.extras.widgets import TextInput

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.TextField: {'widget': TextInput(attrs={'class':'my-widget-class'},)},
    }

You'd have to go through and do that for each widget, but then they'd have the appropriate classes -- at least for that modelAdmin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM