Editing Django _form.as_p

前端 未结 5 1359
名媛妹妹
名媛妹妹 2021-02-02 11:38

By default _form.as._p spits out:

相关标签:
5条回答
  • 2021-02-02 12:08

    If you just need a break, then there's no need to change the Django code. Just use CSS to style label as display: block.

    0 讨论(0)
  • 2021-02-02 12:11

    Pretty much what Brian describes above. I would write a new method for your form like as_myp. I made this for myself. I took as_table method and made as_plain to remove the tr/th markups. Ex.

    class MyForm(forms.Form):
        my_field1 = forms.CharField(...)
        my_field2 = forms.WhateverField(...)
    
        def as_myp(self):
            "Returns this form rendered as HTML <p>s."
            return self._html_output(
                normal_row = '<p%(html_class_attr)s>%(label)s</p> <p>%(field)s%(help_text)s</p>',
                error_row = '%s',
                row_ender = '</p>',
                help_text_html = ' <span class="helptext">%s</span>',
                errors_on_separate_row = True)
    
        def as_plain(self):
            "Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
            return self._html_output(
                normal_row = '%(label)s%(errors)s%(field)s%(help_text)s',
                error_row = '%s',
                row_ender = ' ',
                help_text_html = '<br /><span class="helptext">%s</span>',
                errors_on_separate_row = False)
    

    It just seemed easier to do that than write a template file and handle form field rendering with errors, tags, visible/hidden, etc.

    0 讨论(0)
  • 2021-02-02 12:16

    You simply just can't use form.as_p anymore. If the defaults don't work for you, then you must render the fields manually:

    <form action="/contact/" method="post">
        {% for field in form %}
            <div class="fieldWrapper">
                {{ field.errors }}
                {{ field.label_tag }}: {{ field }}
            </div>
        {% endfor %}
        <p><input type="submit" value="Send message" /></p>
    </form>
    

    See the docs: https://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields

    0 讨论(0)
  • 2021-02-02 12:17

    Template:

    <div id="my_form">
        {{ form.as_p }}
    </div>
    

    CSS:

    #my_form p label,
    #my_form p input{
        float: left;
        clear: left;
    }
    

    So if you add fields you can still use form.as_p

    0 讨论(0)
  • 2021-02-02 12:26

    Override as_p on your form class.

    class MyForm(forms.Form):
        def as_p(self):
            "Returns this form rendered as HTML <p>s."
            return self._html_output(
                normal_row = u'<p%(html_class_attr)s>%(label)s</p> %(field)s%(help_text)s',
                error_row = u'%s',
                row_ender = '</p>',
                help_text_html = u' <span class="helptext">%s</span>',
                errors_on_separate_row = True)
    
    0 讨论(0)
提交回复
热议问题