Answer the question
In order to leave comments, you need to log in
How to correctly insert custom html code between form fields (modelform)?
I have a form that inherits from ModelForm. It has a field with a specific name (for example, let it be name) how to insert my html code after it? For example, so that in the template it looks something like this:
field1
field2
name_field
link
...
field_N
Of the options, I only managed to check the field name when rendering the form in a loop, and if the name matches 'name', insert my code. But it seems to me that this is not correct. If I add my function inside the class (as I would do in admin.py to add custom code) and make it readonly, then it says to me that this field was not found. Are there options to add my pseudo field to the form, or what would be the right way to implement it?
I tried to do something like this:
class Data(ModelForm):
class Meta:
def my_tag(self):
return "<hr>"
model = PersonalInfo
fields = ('last_name', 'my_tag', 'first_name', )
widgets = {
'last_name': TextInput(attrs={'class': 'fio form-control',}),
'first_name': TextInput(attrs={'class': 'fio form-control',}),
}
Answer the question
In order to leave comments, you need to log in
As an option - write your own widget for name_field, which will display
the desired html something like
class TextInputWithOpts(forms.TextInput):
def __init__(self, attrs={}):
super(TextInputWithOpts, self).__init__(attrs)
def render(self, name, value, attrs=None):
output = []
output.append(super(TextInputWithOpts, self).render(name, value, attrs))
if value and hasattr(value, 'optional_html'):
output.append(value)
return mark_safe(u''.join(output))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question