djangodjango-formsdjango-widget

Is it possible to modify widget attributes for each instance of model form in django?


I have a model and a form based on that model. The form will be reused in several templates. Is there a way to tweak the widget attributes of the form field in views before sending it to the template.

Shortest example:

class Price(models.Model):
    ProductID = models.ForeignKey(Product, on_delete = models.CASCADE)
    amount = models.DecimalField(max_digits=12, decimal_places=2)


class NewPriceForm(forms.ModelForm):
    class Meta:
        model = Price
        fields = ('ProductID','amount',)
        widgets = {'amount': forms.NumberInput(attrs={'autocomplete':'off', 'min':'0.01' }),
        }

def set_price(request, ProductID):
    price_form = NewPriceForm(prefix = 'price')

I want to set price_form minimum value to something other than in the widget attributes, based on variables that I have available in the view before sending it off to the template.

Something like this:

price_form.fields["amount"].widget.min = calculated_min_price


Solution

  • You could pass that data to the form in the view when you create it.

    class NewPriceForm(forms.ModelForm):
    
    
         def __init__(self, *args, **kwargs):
            min_value = kwargs.pop("min_value", None)
            super().__init__(*args, **kwargs)
            if min_value:
                self.fields["amount"].widget = forms.NumberInput(attrs={'autocomplete':'off', 'min':min_value })
    
    
        class Meta:
            model = Price
            fields = ('ProductID','amount',)
    
    
    def set_price(request, ProductID):
    
        price_form = NewPriceForm(min_value='10.00')