Take input from view

Asked

Viewed 957 times

1

I have a form with the inputs: email, name and surname. The email will always have a defined format, so I want to take the elements and make it fill automatically in the other fields, example:

User type in email Email: [email protected] (emails will always have this format), so I want the form to fill in the other fields: Name: Field Last name: John Paul

py views.

def cadastro(request):
    if request.method == 'POST':
        return create(request)
    else:
        return new(request)


def new(request):
    return render(request, 'cadastro1.html',
                {'form': CadastroForm()})


def create(request):
    form = CadastroForm(request.POST)
    ponto = form.email.index(".")
    arroba = form.email.index("@")
    first = form.email[0:ponto]
    second = form.email[ponto + 1:arroba]

    obj = form.save()
    if not form.is_valid():
      return render(request, 'cadastro1.html',
                    {'form': form})

    return HttpResponseRedirect('/cadastro/%d/' % obj.pk)

I already have the code to go, but I can’t play in the fields

  • You want the information to appear in the form while the user type or just type the email and you save directly in the bank, without the need for the fields (name and surname) to appear dynamically for the user?

  • Dynamically appearing

  • Then you will have to use javascript, see that you should not do this on the server side (the view ) but on the client side (in the template rendering). Create a script and load it along with the template then manipulate the event onchange of the email input element to fill in the fields you want. If you want a complete example, clone of that repository on github, to reproduce it step by step with instructions in English, see that answer.

  • Okay, I’ll do that, thank you

1 answer

1

You can capture the field of email and break the string:

getEmail = request.POST['email'] #Pega o email
email = getEmail.split('@') #Quebra a string antes dps do @
nomes = email[0].split('.') #Quebra a string antes e dps do .
nome = nomes[0] #Aqui vc tem o primeiro nome
sobrenome = nomes[1] #Aqui vc tem o sobrenome

Now you save:

user = User()
user.email = getEmail
user.nome = nome
user.sobrenome = sobrenome
user.save()

But as they said, the best option is to front with js and automatically fill in the form and send it to back ready.

  • Hi Flávio - you went to a lot of trouble to try to fix your code, and ended up with it worse. For code blocks, simply paste the code into the interface, select it all, and use the button { } . The opposite quotation marks are only for "inline".

  • But I didn’t have the code, I was typing here based on something I had already done before. kkkkkk Mas vllw.

Browser other questions tagged

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