Generate a dynamic form using flask-wtf and sqlalchemy

走远了吗. 提交于 2019-12-03 03:04:29
Melih

I think I managed to create dynamic forms with the idea from here https://groups.google.com/forum/#!topic/wtforms/cJl3aqzZieA

you have to create a dynamic form at view function, fetch the form field you want to get, and iterate every field to construct this form object. I used for fieldtypes simple text instead of integer values. Since it seems easy to read at code level.

class FormView(MethodView):
    def get(self):
        class DynamicForm(wtforms.Form): pass

        dform = main.models.Form.objects.get(name="name2")
        name = dform.name
        for f in dform.fields:
            print f.label
            setattr(DynamicForm , f.label, self.getField(f))

        d = DynamicForm() # Dont forget to instantiate your new form before rendering
        for field in d:
            print field # you can see html output of fields

        return render_template("customform.html", form=d)

    def getField(self, field): 
        if field.fieldtype == "text": 
            return TextField(field.label)
        if field.fieldtype == "password":
            return PasswordField(field.label)
        # can extend if clauses at every new fieldtype

for a simple form render jinja template 'forms.html'

{% macro render(form) -%}
<fieldset>
{% for field in form %}
{% if field.type in ['CSRFTokenField', 'HiddenField'] %}
  {{ field() }}
{% else %}
  <div class="form-group {% if field.errors %}error{% endif %}">
    {{ field.label }}
    <div class="input">
      {% if field.name == "body" %}
        {{ field(rows=10, cols=40) }}
      {% else %}
        {{ field() }}
      {% endif %}
      {% if field.errors or field.help_text %}
        <span class="help-inline">
        {% if field.errors %}
          {{ field.errors|join(' ') }}
        {% else %}
          {{ field.help_text }}
        {% endif %}
        </span>
      {% endif %}
    </div>
  </div>
{% endif %}
{% endfor %}
</fieldset>
{% endmacro %}

and customform.html is like this

{% extends "base.html" %}
{% import "forms.html" as forms %}

{% block content %}
{{ forms.render(form) }}
{% endblock %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!