在同一页面上保存两个表单

时间:2019-04-21 20:06:05

标签: django django-views

总结:我需要与保存Usuario表同时保存Pets表中的Pets字段。 并且用户可以在Pets表中成为FK

这两个表单位于同一页面上,只有一个提交按钮

然后在系统中创建用户时,该用户的FK已同时在Pets表中链接

models.py

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'}))

views.py

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


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.pets.pets = form.cleaned_data.get('pets')
            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')

cadastro.html

{{ 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 }}

0 个答案:

没有答案