简体   繁体   中英

Instance on Django form not working

I am trying to do the second part of the sign up process in which the person (in portuguese Pessoa) would give some extra info about himself and also would register some info about the car he owns (checked by a checkbox in the template called 'tem_carro', in english would be 'has_car'). In this step the person would already have a username and password as well as some basic info such as name, that are mandatory and would fill the non mandatory info.

The problem that the instance=pessoa (which supposedly gets the mandatory info from that person) is not working and I thus I can't validade the form.

In views.py:

def continuar_cadastro(request):
    pessoa = request.user.pessoa # this is working
    # and changing the above line to pessoa = Pessoa.objects.get(id = 1) for exemple doesn't solve either the validation problem
    if request.method == 'POST':
        pessoaForm = CadastroPessoaForm(request.POST, instance=pessoa)  # the form isn't getting the pessoa's info (primeiro_nome and sobrenome)
        if pessoaForm.is_valid():   # I can't get past here!
            try:
                request.POST['tem_carro']
                carro = Carro(motorista=pessoa)
                carroForm = CadastroCarroForm(request.POST, instance=carro)
                if carroForm.is_valid():
                    carroForm.save()
                    pessoaForm.save()
                else:
                    print(carroForm)
                    return HttpResponse("<script>alert('Form do carro inválido.');javascript:history.back();</script>")
            except:
                pessoaForm.save()
        else:
            print(pessoaForm)
            return HttpResponse("<script>alert('Form de informações pessoais inválido.');javascript:history.back();</script>")
    return render_to_response('continuar_cadastro.html', locals(), context_instance=RequestContext(request))

In forms.py:

class CadastroPessoaForm(forms.ModelForm):
    class Meta:
        model = Pessoa
        exclude =('usuario', 'nome_completo')

In models.py:

class Pessoa(models.Model):
    usuario = models.OneToOneField(User, related_name= 'pessoa')
    primeiro_nome = models.CharField("Primeiro nome", max_length= 64)
    sobrenome = models.CharField("Sobrenome", max_length=64)
    celular = models.CharField("Calular", max_length= 16, null=True, blank=True)
    residencial = models.CharField("Residencial", max_length=16, null=True, blank=True)

Thank you!

Edit 1: The error I am getting when validating the form is this (I printed the form):

<tr><th><label for="id_primeiro_nome">Primeiro nome:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_primeiro_nome" maxlength="64" name="primeiro_nome" type="text" /></td></tr>
<tr><th><label for="id_sobrenome">Sobrenome:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_sobrenome" maxlength="64" name="sobrenome" type="text" /></td></tr>
<tr><th><label for="id_celular">Calular:</label></th><td><input id="id_celular" maxlength="16" name="celular" type="text" /></td></tr>
<tr><th><label for="id_residencial">Residencial:</label></th><td><input id="id_residencial" maxlength="16" name="residencial" type="text" value="khsdjgf" /></td></tr>

Your view is not creating the form for get requests - how are you rendering the initial form?

If the form is not valid, print pessoaForm.errors to see what the problem is. Print request.POST to make sure the expected data is there. It looks like there's a problem with the sobernome field, so check that especially closely.

I think the main problem here is the approach you're using to implememt an "user profile" . See Storing additional information about users . You already are half way.

When you have configured the user profile correctly then you can associate the form to your profile class -- Pessoa in this case --.

On the other hand, you are excluding usuario and nome_completo but the last is not a field of Pessoa class.

Also, your Pessoa class has fields which porpuse are the same of some User model fields for instance: primeiro_nome .

Recommendation:

  1. Visite the link I posted.
  2. Review you design, maybe you don't want to define the field primeiro_nome in the Pessoa class.
  3. Check that the data in request.user.pessoa is what your're expecting for. Meaning that primeiro_nome and sobrenome fields have some data.

Finally in this answer -- at last comment -- you can see this OP was struggling with something like your problem.

He said: For the record I also tried user_form = UserForm(request.POST, instance=user, prefix='user') : No error but that always returns an empty form .

Maybe you can try to load your form the way this answer propossed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM