def __init__(self,system, *args, **kwargs):
     super(AlertForm,self).__init__(*args,**kwargs)
     
     sys = System.objects.get(pk=system)
     adm_id = sys.administrator.id
     
     childs = findChildInstance(system)
     flatgenerator =  flatten(childs)
     
     flatlist = []
     for i in flatgenerator:
         flatlist.append(i)
     
     destinataries_id = sum(map(lambda x: sum([list(map(lambda y: y.id,x.users.all())),[x.administrator.id]],[]), flatlist),[])
     
     e_set = Equipment.objects.filter(system = system)
     v_set = []
     for e in e_set:
         try:
             v_set.append(Vehicle.objects.get(equipment=e.id).id)
         except:
             pass
     
     self.fields["vehicle"].queryset = Vehicle.objects.filter(id__in=v_set)
     self.fields["vehicle"].label = "Veículo"
     self.fields["trigger"].queryset = CustomFieldName.objects.filter((Q(custom_field__type = 'Input')|Q(custom_field__type = 'LinearInput')) & Q(system = system) & Q(custom_field__availablefields__system = system)).distinct()
     self.fields["trigger"].empty_label = "(selecione o evento)"
     self.fields['destinataries'].queryset=User.objects.filter((Q(system=system) | Q(pk=adm_id)) | Q(pk__in=destinataries_id) )
     if not sys.can_sms:
         self.fields['receive_sms'].widget.attrs['disabled'] = True
def get_sms_count(request):
    
    try:
        s = System.objects.get(pk=int(request.session['system']))
        
        child_list=flatten(findChildInstance(s.id))
            
        sms_total = 0
        for it in child_list:
            sms_total += it.sms_count
            
        sms_total += s.sms_count
        
        request.session['sms_sent'] = s.sms_count
        request.session['sms_total'] = sms_total
        json_output = {'sms_sent':s.sms_count, 'sms_total':sms_total}
        json_output = simplejson.dumps(json_output)
    
        return HttpResponse(json_output, mimetype='application/json')
    except:
        return HttpResponse('fail')
def login(request):
  
  if request.POST:
    username = request.POST['username']
    password = request.POST['password']
    user = auth.authenticate(username=username, password=password)
    if user is not None and user.is_active:
        # Correct password, and the user is marked "active"
        auth.login(request, user)
        
        #searches first in the administrators
        try:
            system = System.objects.get(administrator__username = request.user.username)
            system_id = system.id
            domain = system.domain
            system_name = system.name
        except:
        #if the user is not an admin, search in the users     
            system = System.objects.get(users__username__exact=request.user.username)            

            #if the user doesn't have a system
            if (system == None):
              erro = u"Usuário não possui Cliente associado."
              return render_to_response("accounts/templates/login.html",locals(),context_instance=RequestContext(request),)
            
            
            system_id = system.id
            domain = system.domain
            system_name = system.name
                    
        user_settings = Settings.objects.filter(system__id=system_id)
      	for item in user_settings:
      	    css = item.css
      	    
      	user = User.objects.get(username__exact=username)
        user_id = user.id
        
        request.session['system'] = system_id
        request.session['css'] = css
        request.session['domain'] = domain
        request.session['username'] = username
        request.session['user_id'] = user_id
        request.session['system_name'] = system_name
        request.session['system_being_created'] = False
        request.session.set_expiry(system.sessiontime)
        
        child_list=flatten(findChildInstance(system_id))
        
        sms_total = 0
        for it in child_list:
            sms_total += it.sms_count
        
        
        request.session['sms_sent'] = system.sms_count
        request.session['sms_total'] = sms_total + system.sms_count
        
        #if is user's first login
        profile = UserProfile.objects.get(profile=user)
        request.session["dont_check_first_login"] = False

        if (profile.is_first_login == True):
            request.session["dont_check_first_login"] = True
            return HttpResponseRedirect("/accounts/edit/" + str(user.id) + "/")
            #return render_to_response("accounts/templates/edit.html",locals(),context_instance=RequestContext(request))
              
        else:
            return render_to_response('rastreamento/templates/rastreamento.html',locals(),context_instance=RequestContext(request))
    else:
        # Show an error page
        erro = u"Usuário ou senha incorretos."
        return render_to_response('accounts/templates/login.html',locals(),context_instance=RequestContext(request))
  else:
    return render_to_response('accounts/templates/login.html',locals(),context_instance=RequestContext(request))