How to add text information to forms in a form set in Django?

I want to show the title and description from the db request in each form, but I don’t want it in charfield, I want it to be HTML formatted text.

sample code template:

{% for form, data in zipped_data %}
   <div class="row">
      <div class="first_col">
         <span class="title">{{ data.0 }}</span>
         <div class="desc">
            {{ data.1|default:"None" }}
         </div>
      </div>
      {% for field in form %}
         <div class="fieldWrapper" style="float: left; ">
            {{ field.errors }}
            {{ field }}
         </div>
      {% endfor %}
{% endfor %}

Is this the most idiomatic way to do this? Or is there a way to add text that will not appear inside the text box or text input of my model:

class ReportForm(forms.Form):
   comment = forms.CharField()

?

+5
source share
4 answers

, , / - . - , , , .

class MyForm (forms.Form):
    def __init__ (self, title, desc, *args, **kwargs):
        self.title = title
        self.desc = desc
        super (MyForm, self).__init__ (*args, **kwargs) # call base class

:

form = MyForm ('Title A', 'Description A')

, . , - , :

   <h1>{{ form.title }}</h1>
   <p>{{ form.desc }}</p>

, , , , , , Django Python API , , .

+10

, :

class ReadOnlyText(forms.TextInput):
  input_type = 'text'

  def render(self, name, value, attrs=None):
     if value is None: 
         value = ''
     return value

:

class ReportForm(forms.Form):
  comment = forms.CharField(widget=ReadOnlyText, label='comment')
+4

, , . , , , , . , - , HiddenInput . :

class ReadOnlyText(forms.HiddenInput):
    input_type = 'hidden'

    def render(self, name, value, attrs=None):
        if value is None:
            value = '' 
        return mark_safe(value + super(ReadOnlyTextWidget, self).render(name, value, attrs))

class ReportForm(forms.Form):
  comment = forms.CharField(widget=ReadOnlyText, label='comment')
+2
source

I think you can get it using "{{field.value}}". Maybe it's easier.

{% for form in formset %}
    {% for field in form %}
        {% if forloop.counter = 1 %}
            <td><img src="{{ MEDIA_URL }}{{ field.value }}"/></td>
        {% endif %}
        {% if forloop.counter = 2 %}
            <td>{{ field.value }}</td>
        {% endif %}
        {% if forloop.counter > 2 %}
            <td>{{ field }}{{ field.errors }}</td>
        {% endif %} 
    {% endfor %}
{% endfor %}
0
source

All Articles