Loading 2 form on the same page and saving them

Asked

Viewed 415 times

0

I have a system, and I need to change, I want to take the pets option, and put it in a separate table, because it will have more than one type of user that would use it. But I’m not getting it to appear along with the other form on the same page and then I need you to save both forms at the same time. remembering that each time I register the form, a user is created in the system by Usercreationform would need a help to be able to show and save both forms at once

py.models

class Pets(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    pets = models.CharField(max_length=255, choices=PET_CHOICES)

class Usuario(models.Model):

    nome = models.CharField(max_length=50, blank=False)
    sobrenome = models.CharField(max_length=50, blank=False)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    email = models.EmailField(blank=False)

Forms.py

   class PetsForm(forms.ModelForm):
   pets = forms.MultipleChoiceField(
          widget=forms.CheckboxSelectMultiple, choices=PET_CHOICES, )
   class Meta:
          model = Pets
          fields = '__all__' 
   class UsuarioForm(UserCreationForm):

   nome = forms.CharField()
   sobrenome = forms.CharField(
          widget=forms.TextInput(
                                      attrs={
                                             'placeholder': 'Sobrenome'}))
   email = forms.EmailField(
          widget=forms.TextInput(
                                      attrs={
                                             'placeholder': 'Email Válido', 'id': 'email'}))

py views.

def cadastro(request):
    usuario = Usuario.objects.all() 
    form = UsuarioForm()
    pets = Pets.objects.all()
    form2 = PetsForm()
    data = {'usuario': usuario, 'form': form}
    data2 = {'pets': pets, 'form2': form2}
    return render(request, 'cadastro.html', data, data2)


def cadastro_novo(request): 
    if request.method == 'POST':
        form = UsuarioForm(request.POST, request.FILES)
        form2 = PetsForm(request.POST)
        if form.is_valid() and form2.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.is_staff = True
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.usuario.nome = form.cleaned_data.get('nome')
            user.usuario.sobrenome = form.cleaned_data.get('sobrenome')
            user.usuario.email = form.cleaned_data.get('email')
            user.usuario.telefone = form.cleaned_data.get('telefone')
            user.usuario.cidade = form.cleaned_data.get('cidade')
            user.usuario.endereco = form.cleaned_data.get('endereco')
            user.usuario.cpf = form.cleaned_data.get('cpf')
            user.usuario.numero = form.cleaned_data.get('numero')
            user.usuario.bairro = form.cleaned_data.get('bairro')
            user.usuario.cep = form.cleaned_data.get('cep')
            user.usuario.password1 = form.cleaned_data.get('password1')
            user.usuario.data_nascimento = form.cleaned_data.get('data_nascimento')
            user.usuario.gallery_usuario = form.cleaned_data.get('gallery_usuario')
            user.usuario.pet = form.cleaned_data.get('pets')
            user.usuario.foto = form.cleaned_data.get('foto')
            user.usuario.sexo = form.cleaned_data.get('sexo')
            user.usuario.estado = form.cleaned_data.get('estado')
            user.usuario.about = form.cleaned_data.get('about')
            user.pets.pet = form.cleaned_data.get('pet')
            username = form.cleaned_data.get('username')
            user.username = username.lower()
            user.save()
            current_site = get_current_site(request)
            subject = 'Ative seu registro no PetAqui'
            message = render_to_string('account_activation_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token': account_activation_token.make_token(user),
            })
            user.email_user(subject, message)
            return redirect('account_activation_sent')
    else:
        form = UsuarioForm()
    return render(request, 'cadastro.html', {'form': form})


def account_activation_sent(request):
    return render(request, 'account_activation_sent.html')

html registration I’m calling it so

{{ form.nome | as_crispy_field }}
{{ form.sobrenome | as_crispy_field }}
{{ form.user | as_crispy_field }}
{{ form.email | as_crispy_field }}
{{ form2.pets | as_crispy_field }}

1 answer

0

Good morning,

Dude, I needed to do something similar on my system, I have several different tables in the database, so several different formats rendered on the same page. I don’t know if the shape I made is the most "correct" or better, but I created an Updateview and did the following:

def get_context_data(self, **kwargs):
    kwargs['franqueado'] = CadastroDeFranqueado.objects.get(pk=self.kwargs['pk'])
    kwargs['form_franqueado'] = CadastroDeFranqueadoCompletoForm(self.request.POST or None, instance=kwargs['franqueado'])
    kwargs['comentarios'] = ComentariosCrm.objects.filter(franquia__pk=self.kwargs['pk'])
    kwargs['form_comentario'] = ComentariosCrmForm(self.request.POST or None)
    return super().get_context_data(**kwargs)

In the above code I load the Forms and pre-existing data, then I used the "form_valid" method with an if for each form where I check one by one if there is data to be saved, see:

def form_valid(self, form, **kwargs):
    try:
        user = User.objects.get(username=self.franqueado().usuario)
    except:
        user = User.objects.get(email=self.franqueado().emailPrincipal)
    form = form.save()
    if self.franqueado().emailPrincipal != user.email:
        user.email = self.franqueado().emailPrincipal
        user.save()

    if self.franqueado().usuario != user.username:
        user.username = self.franqueado().usuario
        user.save()

    if self.franqueado().status != 'Operando' and self.franqueado().status != 'Em implantação':
        user.is_active = False
        user.save()
    else:
        user.is_active = True
        user.save()

    formcomentario = ComentariosCrmForm(self.request.POST or None)
    if formcomentario.is_valid():
        if len(
            formcomentario.cleaned_data.get('autor')
        ) > 3 and len(
            formcomentario.cleaned_data.get('comentario')
        ) > 5 and formcomentario.cleaned_data.get(
            'franquia'
        ):
            formcomentario.save()

    formdocumentos = DocumentosCrmForm(self.request.POST or None, self.request.FILES or None)
    if formdocumentos.is_valid():
        docs = self.request.FILES.getlist('documento')
        for doc in docs:
            documento = DocumentosCrm(franquia=self.franqueado(), documento=doc)
            documento.save()
    return super().form_valid(form)

I hope the code above can help you in solving the problem.

  • Friend, weekend I will try and anything I send you msg, very obliged

  • Show, I hope for certain the/

Browser other questions tagged

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