0

Normally, when I use Django's Form API to display model form, I will pass the form object to the template via django.template.Context and render its fields using Django's templating language:

<form role="form" method="post">
    {% csrf_token %}           
    {{ form.non_field_errors }}
    <div class="form-group">
        <label for="id_content">Content</label>
        {{ form.content }}
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

The form.content will be rendered as

<textarea id="id_content" rows="10" cols="40" name="content" style="margin: 2px; width: 339px; height: 164px;"></textarea>

But now I want to use it with AngularJS, i.e. binding the input field to an ng-model

<textarea ng-model="content" id="id_content" rows="10" cols="40" name="content" style="margin: 2px; width: 339px; height: 164px;"></textarea>

Is there anyway to achieve this?

1 Answer 1

2

One way is to override form init method and update widget attributes:

class MyForm(forms.ModelForm):
    # fields..

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['content'].widget.attrs.update({'ng-model': 'content'})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. But I've settled for custom filter. I'll post my code later for your review. With filter there is no need to override form init every time.
@LimH. Sure, there're probably few more ways to do it, another one can be to use this mixin from django-angular.

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.