jrief / django-angular

Let AngularJS play well with Django
http://django-angular.awesto.com/
MIT License
1.23k stars 294 forks source link

conditionally set ng-required #268

Closed luigielric closed 7 years ago

luigielric commented 7 years ago

Good Evening,

I don't know if i'm doing things properly but i can't manage to set dynamically ng-required to something. In my form, i've got field A, field B and field C. If field A=1 field B is required and C isn't if field A=2 field C is required and C isn't.

My field are created from a model in django.

forms.py

class PetForm(NgModelFormMixin,NgFormValidationMixin,Bootstrap3ModelForm):
    scope_prefix = 'pet_data'
    form_name = 'pet_form'

    class Meta:
        model = petdata
        fields = ('A','B','C'
        widgets = { 
            'A': forms.Select(attrs={'class':'select2', 'style':'width:100%'}),
            'B': forms.Select(attrs={'ng-required':"pet_data.A=='1'" , 'class':'select2', 'style':'width:100%'}),
            'C': forms.Select(attrs={'ng-required':"pet_data.A=='2'",'class':'select2', 'style':'width:100%'}),

A,B,C are rendered normally like this :

                        {{ form.A.label_tag }}
                        {{ form.A }}
                        {{ form.A }}

Same for B and C

But it doesn't work. The HTML still looks like this : (the "ng-required" from the widget is not taken into account). Exemple with B :

<select class="form-control ng-pristine ng-untouched ng-valid ng-valid-parse ng-valid-required" id="id_B" name="B" ng-model="pet_data['B']" ng-required="true" style="width:100%" required="required" tabindex="-1" aria-hidden="true">
<option value="0" selected="selected">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>

Is that normal because django-angular is forbidden what I'm trying to do or it's because I'm doing things not properly ?

Thank you for your time !

adrienbrunet commented 7 years ago

If you have a look at the code:

in forms/field_mixins.py

...
if self.required:
    self.widget.attrs['ng-required'] = 'true'
...

I guess this is why you don't have your own ng-required. I think we cannot currently set the ng-required. Maybe you want to add this feature? It shouldn't be that complicated. I don't have much time right now but tell me if you need more help.

Cheers

luigielric commented 7 years ago

I'm quite new in that area of knowledge but if I can help why not. What do you suggest ? If you have detailed instruction, I would do my best to help ;)

adrienbrunet commented 7 years ago

from Django doc:

Field.required¶ By default, each Field class assumes the value is required

You may try to use required=False first in your forms to see if your ng-required is still overwritten.

luigielric commented 7 years ago

It works perfectly. Thank you.