开发者

Handcoding forms vs django forms

开发者 https://www.devze.com 2023-03-03 14:32 出处:网络
Are there a开发者_如何转开发ny performance differences between handcoding forms in django (as well as all the validations in the views.py) and using django\'s form library? If they are roughly the sam

Are there a开发者_如何转开发ny performance differences between handcoding forms in django (as well as all the validations in the views.py) and using django's form library? If they are roughly the same, in which scenarios would one handcode a form over using the built-in ones?

Also, What about handcoding the HTML templates and using the django block tags, etc. to re-use certain areas?


Do you have insane, zero-tolerance performance requirements? As in: will people actually die or come to harm or you be fired if a page takes an extra few milliseconds to render?

I doubt it, so just let the framework do the lifting up to the point where you need more control over the HTML output -- that's actually far more likely a scenario than you needing to avoid executing some Python to save (at an utter guess) 15ms.

When you do need more control, that's when it's best to splice in some handmade HTML, or - even better - create an include/partial for form fields that you can reuse everywhere, to save you the time of manually writing more than you need to, but still giving you a lot more flexibility than myform.as_p etc

Here's a rough snippet I use and adapt a lot, to give me lots of control over form fields and also let me leverage the Django templating framework to save me time:

In my template:

{% for form_field in myform %}
   {% include "path/to/partials/form_field_as_p.html" %}
{% endfor %}

And in that form_field_as_p.html, something like:

{% if not form_field.is_hidden %}
    <p>

    {% if form_field.errors %}
      {% for error in form_field.errors %}
      <span class="errorlist">{{error}}</span>
      {% endfor %}
    {% endif %}         

    {{ form_field.label_tag }}

    {% if form_field.field.required %}
        <span class="required">*</span>
    {% endif %}

    {{ form_field }}

    {% if form_field.help_text %}
        <span class="form-help-text">{{ form_field.help_text }}</span>
    {% endif %}

    </p>    
{% else %}
    <div>{{ form_field }}</div> {# hidden field #}
{% endif %}
0

精彩评论

暂无评论...
验证码 换一张
取 消