from django.shortcuts import redirect
from django.shortcuts import render
from django.contrib.auth.models import User
from django.views.generic.base import View
from perfis.models import Perfil
from usuarios.forms import RegistrarUsuarioForm


class RegistrarUsuarioView(View):

    template_name = 'registrar.html'

    def get(self, request):
        return render(request, self.template_name)

    def post(self, request):

            # preenche o from
            form = RegistrarUsuarioForm(request.POST)

            # verifica se eh valido
            if form.is_valid():

                dados_form = form.data

                # cria o usuario
                usuario = User.objects.create_user(dados_form['nome'],
                                                   dados_form['email'],
                                                   dados_form['senha'])

                # cria o perfil
                perfil = Perfil(nome=dados_form['nome'],
                                telefone=dados_form['telefone'],
                                nome_empresa=dados_form['nome_empresa'],
                                usuario=usuario)

                # grava no banco
                perfil.save()

                # redireciona para index
                return redirect('index')

            # so chega aqui se nao for valido
            # vamos devolver o form para mostrar o formulario preenchido
            return render(request, self.template_name, {'form': form})


[((14, 15, 14, 50), 'django.shortcuts.render', 'render', ({(14, 22, 14, 29): 'request', (14, 31, 14, 49): 'self.template_name'}, {}), '(request, self.template_name)', False, 'from django.shortcuts import render\n'), ((19, 19, 19, 53), 'usuarios.forms.RegistrarUsuarioForm', 'RegistrarUsuarioForm', ({(19, 40, 19, 52): 'request.POST'}, {}), '(request.POST)', False, 'from usuarios.forms import RegistrarUsuarioForm\n'), ((45, 19, 45, 70), 'django.shortcuts.render', 'render', ({(45, 26, 45, 33): 'request', (45, 35, 45, 53): 'self.template_name', (45, 55, 45, 69): "{'form': form}"}, {}), "(request, self.template_name, {'form': form})", False, 'from django.shortcuts import render\n'), ((27, 26, 29, 71), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', ({(27, 51, 27, 69): "dados_form['nome']", (28, 51, 28, 70): "dados_form['email']", (29, 51, 29, 70): "dados_form['senha']"}, {}), "(dados_form['nome'], dados_form['email'],\n    dados_form['senha'])", False, 'from django.contrib.auth.models import User\n'), ((32, 25, 35, 48), 'perfis.models.Perfil', 'Perfil', (), '', False, 'from perfis.models import Perfil\n'), ((41, 23, 41, 40), 'django.shortcuts.redirect', 'redirect', ({(41, 32, 41, 39): '"""index"""'}, {}), "('index')", False, 'from django.shortcuts import redirect\n')]