How to create 2 Forms simultaneously in Django and configure the views

Asked

Viewed 203 times

-1

What I want to do is create 2 Forms simultaneously, on just one page 'index.html'. One would just be a normal form that will send a message to contact, and the other is a record that I need to save to the database. So far I have been able to create only using a form, this way.

class IndexView(FormView):
template_name = 'index.html'
form_class = ContatoForm
success_url = reverse_lazy('index')

def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    context['servicos'] = Servico.objects.order_by('?').all()
    context['funcionarios'] = Funcionario.objects.order_by('?').all()
    context['portfolios'] = Portfolio.objects.order_by('?').all()
    context['testimonials'] = Testimonial.objects.order_by('?').all()

    return context

def form_valid(self, form, *args, **kwargs):
    form.send_mail()
    messages.success(self.request, 'E-mail enviado com sucesso')
    return super(IndexView, self).form_valid(form, *args, **kwargs)

def form_invalid(self, form, *args, **kwargs):
    messages.error(self.request, 'Erro ao enviar e-mail')

    return super(IndexView, self).form_invalid(form, *args, **kwargs)

Now I needed to add another form, which is this

class RegistroModelForm(forms.ModelForm):
class Meta:
    model = Registro
    fields = ['nome', 'email', 'phone', 'area']

1 answer

0


Alive, you can create multiples Forms, there is even inlineformset_factory among others, depends on the use case. Even here in this "class based Generic views", you can use a different one that best suits your case that Django provides, such as: View, Listview, Templateview, Createview, Deleteview, Updateview that you can import from Jango.views.Generic. Or simply use a function of yours that involves doing more code and validations than these base classes already do for you.

py views.

from django.views.generic import CreateView

class IndexView(CreateView):
    template_name = 'index.html'
    form_class = ContatoForm
    form_class_adicional = RegistroModelForm

    def get(self, request, *args, **kwargs):
        context = { 
            'form': self.form_class,
            'form_new': self.form_class_adicional(),
            'servicos': Servico.objects.order_by('?').all(),
            'funcionarios': Funcionario.objects.order_by('?').all(),
            'portfolios': Portfolio.objects.order_by('?').all(),
            'testimonials': Testimonial.objects.order_by('?').all()
        }
        return render(request, self.template_name, context)

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            form = self.form_class(request.POST or None, request.FILES or None)
            form_new = self.form_class_adicional(request.POST or None, request.FILES or None)
            # aqui Django valida o teu form, neste caso só os dois válidos irá gravar, mas podes mudar esta lógica
            if form.is_valid() and form_new.is_valid(): 
                form.save()
                form_new.save()
                form.send_mail() # envias o email
                #messages.success(self.request, 'E-mail enviado com sucesso') # esta mensagem colocas na função send_mail
                #messages.error(self.request, 'Erro ao enviar e-mail')        # esta mensagem colocas na função send_mail
            return redirect('index')
        return redirect('index')

index.html

<form action="." enctype="multipart/form-data" method="POST">
    {% csrf_token %}
    {{ form }}
    {{ form_new }}
    <button type="submit" value="submit">Gravar</button>
</form>
  • I would need to do a filtering also to know which Forms are going pro form_valid to be able to do an action or not, because they are different and independent forms that are on the same page. While Registromodelform is to save in the database, Contactoform is to send a message to me, so how would you filter? I also have another problem, the template is already ready and mounting in html, in case I would only reuse the fields.

  • Hello to your other question, I usually do not use Formview class based, use Createview or Updateview. I edited my answer from your example with multiple Rfms. You’ll have to do something like this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.