Integration AngularJS and Django forms to write data [closed]

2

How are you handling the integration frameworks in JavaScript with forms

asked by anonymous 01.10.2015 / 19:53

1 answer

2

As you said, this is a bad idea. As your question is too broad, I will restrict myself to answering only the form question.

Django has formsets which is a feature that allows you to submit multiple forms of the same type at once.

Formsets work quite similarly to traditional forms, and in views, you can pass request.POST to an instance of it which will know how to process it.

I made a small example using formsets for models, which works analogously to ModelForm :

models.py

class Pessoa(models.model):
    nome = models.CharField(max_length=255)

forms.py

from django.forms.models import modelformset_factory
from .models import Pessoa

PessoaFormSet = modelformset_factory(Pessoa, fields(('nome',))

There are several ways to create formsets, the one I've presented is just a short way. However, it is possible to create a regular form and pass it as a parameter to the function that generates the formset. Take a look at the documentation for this (links at the end of the answer).

views.py

from django.shortcuts import render, redirect
from .forms import PessoaFormSet
from .models import Pessoa

def adicionar_nomes(request):
    formset = PessoaFormSet(queryset=Pessoa.objects.none())
    if request.method == 'POST':
        formset = PessoaFormSet(request.POST)
        if formset.is_valid():
            formset.save()
            return redirect('/')
    return render(request, 'adicionar_nomes.html', {'formset': formset})

The only remark here is the queryset parameter passed to the formset. By default, django passes all objects of the given class to modelsformset_factory , which is not interesting if you are creating a form to add new objects.

add_names.html

<form method="post">
    {% csrf_token %}
    {% verbatim %}
    <!-- Seu código em Angular -->
    {% endverbatim %}
    <button type="submit">Salvar</button>
</form>

Finally, add your magic to the template. As AngularJS uses tags with the same syntax as Django templates, to use them without Django processing them before the response is sent, place them inside the verbatim block.

Anyway, it's worth reading the Django documentation on formsets. What I presented here was only a small part, but enough to avoid the creation of franksteins and direct processing of request.POST .

Useful Django Documentation for your question

Forms

Formsets for models

template tag verbatim

    
01.10.2015 / 22:35