'Subclassed form doesn't render customized input field in Django
I have a subclassed form which I want to render a custom max attribute on the input field. However, it doesn't return any form instance in the view and thus doesn't render any input field either:
# views.py
..
custom_max_attribute = qs_aggregates['total_equity']
print(custom_max_attribute) # prints 4000
withdraw_form = WithdrawForm(custom_max_attribute)
print(withdraw_form) # prints nothing
..
# template
..
<div class="field-wrapper">
<div class="field-title">Set your Amount</div>
<div class="withdraw-input-field">{{ withdraw_form.withdraw_amount }}</div> <!-- isnt rendered -->
</div>
..
# forms.py
class WithdrawForm(forms.Form):
"""
A form to withdraw available funds from Farena to the users bank account
"""
def __init__(self, custom_max_attribute, *args, **kwargs):
super().__init__(self, custom_max_attribute, *args, **kwargs)
withdraw_amount = forms.FloatField(widget=forms.NumberInput(attrs={'min': 1, 'max': custom_max_attribute, 'step': 0.01}))
Solution 1:[1]
This is a workaround, works for me but I see that you are working with withdrawals so you may need to implement some additional validation on form submission.
Basically. You can set custom attributes in JS, add class to the input in forms.py like this
widgets ={
'name' :forms.TextInput(attrs={'class':'shippForm'}),
'withdraw':forms.NumberInput(attrs={'class':'shippForm'}),
}
and then you can just
var form_fields = document.getElementsByClassName('shippForm')
form_fields[0].placeholder='{% trans "Name" %}';
form_fields[1].max='2115';
the max (2115) can be taken from context/database etc so you can check if user did some frontend shenanigans
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stud1234 |
