[Django]-Django Form in VueJS component template

2👍

I find a very clean solution to this problem to use djagno widget tweaks

With that you can have something like:

views.py

def myview(request):
    form = MyForm()
    return render(request, 'mytemplate.html', {'form': form})

mytemplate.html

{% load widget_tweaks %}
<form v-on:submit-prevent="myaction()">
    {% render_field form.field v-model="myattr" %}
</form>

And it will work flawlessly

0👍

This is fragment of code from this article, I recommend you to read it.

  • you have to attach view instance to some element like starting (in example)
  • set delimiters, because we do not need conflicts with django template {{ }} syntax
  • inside div with id=starting you can place your vue custom forms
<script type="text/javascript">
new Vue({
   el: "#starting",
   delimiters: ['${', '}'],
   data: {
      articles: [],
      loading: false,
      newArticle: {...}
      ...
   }
 },
mounted: function() {
},
methods: {
 addArticle: function() {
  this.loading = true;
  this.$http.post("/api/article/",this.newArticle)
   .then((response) => {
     console.log(response);
  })
  .catch((err) => {
    this.loading = false;
    console.log(err);
  }) 
 },
 ...
}
 });
</script>
  <div id="starting">
    <form v-on:submit.prevent="addArticle()">
            <div class="modal-body">
                <div class="form-group">
                <label for="article_heading">Article Heading</label>
                <input
                     type="text"
                     class="form-control"
                     id="article_heading"
                     placeholder="Enter Article Heading"
                     v-model="newArticle.article_heading"
                     required="required" >
            </div>
             <div class="form-group">
                      <label for="article_body">Article Body</label>
                      <textarea
                        class="form-control"
                        id="article_body"
                        placeholder="Enter Article Body"
                        v-model="newArticle.article_body"
                        required="required"
                        rows="3"></textarea>
                  </div>
             </div>
          <div class="modal-footer">
             <button type="submit" class="btn btn-primary">Save changes</button>
          </div>
       </form>
  </div>

Leave a comment