def done(self,request,form_list):
        
        form_data = {}
        for form in form_list:
            for field, value in form.cleaned_data.iteritems():
                form_data[field] = value
                print field,":",value
        
        form_usr = UserForm(form_data)
        form_profile = UserProfileForm(form_data)
        print "here!!1"
        form_sys = SystemForm(request.session['system'],form_data)
        form_sett = SettingsForm(form_data,request.FILES)
        
        if form_usr.is_valid() and form_profile.is_valid() and form_sys.is_valid() and form_sett.is_valid():
        
          if form_usr.is_valid():
              new_user = form_usr.save(commit=False)
              new_user.set_password(form_data["password"])
              new_user.save()
            
            
          if form_profile.is_valid():
              new_profile = form_profile.save(commit=False)
              new_profile.profile_id = new_user.id
              new_profile.save()

          sys_id = request.session["system"] 
          system = System.objects.get(pk=sys_id) 
        

          new_user.groups.add(1)
        
          if form_sys.is_valid():
              new_sys = form_sys.save(commit=False)
              new_sys.parent_id = system.id
              new_sys.administrator_id = new_user.id

              new_sys.save()
              form_sys.save_m2m()

          if form_sett.is_valid():
              new_setting = form_sett.save(commit=False)
              new_setting.system_id = new_sys.id
              new_setting.title = new_sys.name
              new_setting.save()
              new_setting  = change_css(new_setting)              
              new_setting.save()

              cfn_set = CustomFieldName.objects.filter(system = system)
              for cfn in cfn_set:
                cfn2 = CustomFieldName(system = new_sys, custom_field=cfn.custom_field, name = cfn.name)
                cfn2.save()
              
              request.session.update({'system_being_created':True})
              return HttpResponseRedirect('/equipment/associations/'+str(new_sys.id))
              
          else:
            return render_to_response("system/templates/create_wizard.html",locals(),context_instance=RequestContext(request))
def create_user(request,offset):
    
    if request.method == 'POST':
        
        form_user = UserForm(request.POST)
        form_profile = UserProfileForm(request.POST)
        
        try:
            adm = request.POST['Administrador']
        except:
            adm = None
        
        
        if ( form_user.is_valid() and form_profile.is_valid() ):
          system_id = int(offset)
          system = System.objects.get(pk=int(system_id))
          
          new_user = form_user.save(commit=False)
          
          # Aplica o Hash na senha
          new_user = form_user.save()
          user = User.objects.get(username__exact=new_user)
          password = user.password

          user.set_password(password)
          
          message = u"Você foi cadastrado no sistema Infotrack com sucesso. \n\n"
          message += "Login: "******"\n"
          message += u"Senha provisória: "+password+"\n\n"
          
          send_mail('Cadastro em Infotrack', smart_str(message, encoding='utf-8', strings_only=False, errors='strict'), '*****@*****.**',[user.email], fail_silently=False)
                    
          user.save()
          
          try:
            alert = request.POST["alert"]
          except:
            alert = None
        
          try:
            command = request.POST["command"]
          except:
            command = None
            
          if adm is not None:
            user.groups.add(1)
            
          elif (alert is not None and command is not None) and adm is None:
            user.groups.add(2)
            user.groups.add(3)
            
          elif command is not None and adm is None:
            user.groups.add(3)
            
          elif alert is not None and adm is None:
            user.groups.add(2)
          
          new_profile = form_profile.save(commit=False)
          new_profile.profile_id = new_user.id
          new_profile.is_first_login = True
          new_profile.save()
          
          system.users.add(new_user)

          users = User.objects.filter(system=system)
                
          return HttpResponseRedirect("/accounts/create/finish")

        else:
          form = UserCompleteForm(request.POST)
          return render_to_response("accounts/templates/create.html",locals(),context_instance=RequestContext(request),)

    else:
        #form_user = UserForm()
        #form_profile = UserProfileForm()
        form = UserCompleteForm(profile = None)
        form.fields["Administrador"] = forms.CharField(widget=forms.CheckboxInput(),help_text="Marque a caixa para atribuir privilégios administrativos ao usuário")
        return render_to_response("accounts/templates/create.html",locals(),context_instance=RequestContext(request),)
def edit(request,offset):
  
  user = User.objects.get(pk=int(offset))
  profile = UserProfile.objects.get(profile=int(offset))
  first_login = profile.is_first_login
  if request.method == 'POST':
    request.session["dont_check_first_login"] = True
    form = UserCompleteForm(request.POST,instance= user,profile=profile)
    form_user = UserForm(request.POST, instance = user)
    form_profile = UserProfileForm(request.POST, instance = profile)
    
    
    if form_user.is_valid() and form_profile.is_valid():
        new_user = form_user.save(commit=False)
        new_user.set_password(new_user.password)
        new_user.save()
        
        try:
            alert = request.POST["alert"]
        except:
            alert = None
            
        try:
          command = request.POST["command"]
        except:
          command = None

        try:
          adm = request.POST['Administrador']
        except:
          adm = None

        
        if adm is not None:
          user.groups.add(1)
          
        elif alert is not None and command is not None:
          user.groups.add(2)
          user.groups.add(3)
          
        elif command is not None:
          user.groups.add(3)
          
        elif alert is not None:
          user.groups.add(2)
        
        new_profile = form_profile.save()
        if (first_login == False):
            return HttpResponseRedirect ("/accounts/edit/finish")
        else:
            profile.is_first_login == False
            profile.save()
            return HttpResponseRedirect ("/accounts/edit/finish_firstlogin")

    return render_to_response("accounts/templates/edit.html",locals(),context_instance=RequestContext(request))
    
  else:
    request.session["dont_check_first_login"] = False
    system = request.session['system']
    users = User.objects.filter(system=system)
    profile = UserProfile.objects.get(profile=user)
    
    try:
        s = System.objects.get(users__id=user.id)
    except:
        s = System.objects.get(administrator__id = user.id)
    if isChild(s.id,[system,findChild(system)]):

        form = UserCompleteForm(instance = user,profile = profile)
      
        # ROOOTS BLOODY ROOTS
        if profile.is_first_login == False:
            form.fields["Administrador"] = forms.CharField(widget=forms.CheckboxInput(),help_text="Marque a caixa para atribuir privilégios administrativos ao usuário")
      
        else:
            title1 = "Primeiro acesso"
            
            title2 = "Para sua segurança solicitamos que mude sua senha antes de acessar o sistema."
            
        form.initial = dict( form.initial.items() + profile.__dict__.items())
        form.initial["password"] = ""
        return render_to_response("accounts/templates/edit.html",locals(),context_instance=RequestContext(request))
      
    else:
      return HttpResponseForbidden(u'Você não tem permissão para editar este usuário.')