0

The question title might be a little misleading, but I couldn't think of a better title. If you've got better title, please edit the title.

I have following set of models.py and forms.py`

# models.py
class BHA_Component(models.Model):
    field_1 = models.CharField(max_length=100)
    field_2 = models.CharField(max_length=100)
    field_3 = models.CharField(max_length=100)

# forms.py
class BHA_Component_Form(forms.ModelForm):
    class Meta():
        fields = '__all__'

I want to create custom attributes for each field, so that I can identify what kind of field it is on the Front-End, and assign a class for each field type.

Something like this:

enter image description here

Some fields are just plain blank, some are grey, some are purple, and some have check boxes. These are done by manually giving each field a particular HTML class on the Front-End. However, I want to give each field some attributes on the Back-End, and have those attributes identified on the Front-End. So, something like this:

{% for field in bha_component_form %}

  {% if field.custom_attribute == 'option_1' %}
    {{ field|add_class:"has_checkbox"}}
  {% else if field.custom_attribute == 'option_2' %}
    {{ field|add_class:"blue_background"}}
  {% else %}
    {{ field|add_class:"plain"}}
  {% endif %}

{% endfor %}

How can I do this?

1 Answer 1

1

To pass in attributes on the backend you can try something likes this:

email = forms.EmailField(widget=forms.EmailInput(attrs={'class': "form_control form-control-lg", 'placeholder': "Email"}), required=True, )

So, for your specific case:

models.py:

class BHA_Component(models.Model):
    field_1 = models.CharField(max_length=100, widget=forms.TextInput(attrs={'custom_attribute': "option_1") })
    field_2 = models.CharField(max_length=100, widget=forms.TextInput(attrs={'custom_attribute': "option_2") })
    field_3 = models.CharField(max_length=100, widget=forms.TextInput() })

It should be a case of using something like this in your template:

{% for field in bha_component_form %}
  {% if field.widget.attrs.custom_attribute == 'option_1' %}
    {{ field|add_class:"has_checkbox"}}
  {% else if field.widget.attrs.custom_attribute == 'option_2' %}
    {{ field|add_class:"blue_background"}}
  {% else %}
    {{ field|add_class:"plain"}}
  {% endif %}
{% endfor %}

It should just be a case of modifying what I have outlined above for your specific use case.

Hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.