Mobil Mewah

Salah satu sumber Inspirasi.

Mobil Sport terbaik

Anda pasti bisa memilikinya.

Bermain dengan pesawat

Salah satu ide yang gila, Balapan di udara.

Bermain di angkasa

Apakah ini salah satu Goals dalam hidup anda? anda pasti bisa mencapainya

Saturday, 29 August 2015

Django Choice form filtered base on logged username


With Django we have form which have many feature to faster development. I usually use Django Model Form, which get the meta data from a model and spit out a form ready to use and rendered to client in HTML form.

Django Select Form
Now i need to get a choice field in django , but the choice field get from a foreign key, and need to filter it base on the username logged in to system.

So the purpose is to get a list of choice which only available for the specific user, let say the user belong to VIP user group. So user only see the choice only available to VIP user group defined before by admin.


So lets get the how to do it. Here are the model code :
  class Usergroup(models.Model):
    """Models for User Group"""
    group_name = models.CharField(max_length=64, null = False, default = '')
    owner = models.CharField(max_length=64, null = False, default = ''  )
    update_by = models.CharField(max_length=250,null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
            db_table = 'Usergroup'
            ordering = ['-created_at']
            verbose_name_plural = 'usergroup'
            permissions = (
                ("view_usergroup", "Can see detail of the User Group"),
                ("list_usergroup", "Can list all the User Group"),
            )

    def __unicode__(self):
        return self.group_name

    @models.permalink
    def get_absolute_url(self):
        return ('user_group', (),{'group_name':self.group_name})




here are the form code :
   class AdminVIPUsersModelForm(forms.ModelForm):
     """For new and edit model"""
     def __init__(self, *args, **kwargs):
        super(AdminVIPUsersModelForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if field.widget.__class__ == forms.widgets.TextInput:
                if field.widget.attrs.has_key('class'):
                    field.widget.attrs['class'] += ' form-control input-medium'
                else:
                    field.widget.attrs.update({'class':'form-control input-medium'})

     class Meta:
         model = VIPuser
         fields = ('user_name','passwd','user_group','access_type','owner')
     user_name = forms.CharField(widget=forms.TextInput(attrs={ \
                    'class':'form-control input-medium'}),label='User Name' \
                    ,help_text="Used for login on Wifi")
     passwd = forms.CharField(widget=forms.PasswordInput(attrs={ \
                    'class':'form-control input-medium'}),label='Password' \
                    ,help_text="Passoword for user login from HotSpot")
     user_group = forms.ModelChoiceField(widget=forms.Select(attrs={ \
                    'class':'form-control input-medium'}),label='Group' \
                    ,help_text="Group the user belong", \
                    queryset = Groupchoices.objects.all())
     access_type = forms.CharField(widget=forms.TextInput(attrs={ \
                    'class':'form-control input-medium'}),label='Access Type' \
                    ,help_text="User access type description")
     owner = forms.CharField(widget=forms.TextInput(attrs={ \
                    'class':'form-control input-small'}),label='Owner' \
                    ,help_text="The creator of the group and will used only \
                    by the creator")

And in the views.py :
        form = AdminVIPUsersModelForm()
        form.fields["user_group"].queryset = Usergroup.objects.filter(owner=request.user.username)


This usecase will be used when there is foreign key relation on each table.

Hope this help someone as i documented for my future reference in this blog.

Tuesday, 18 August 2015

Check windows process with Nagios Monitoring

I need to check a process running on windows machine from a monitoring server. The monitoring using Nagios. I want to get alert when the process is not running on the windows machine.

This can be achieved by using Nagios NRPE client++ .

Assume NRPE client++ already installed.
To test on nagios machine do this :

./check_nt -H 10.10.10.10 -p 12489 -v PROCSTATE -d SHOWALL -l w3wp.exe

If running, it will return :

w3wp.exe: Running

if not running, it will return :

w3wp: not running

this so simple is it?


Tuesday, 11 August 2015

Monitoring DNS with a vbscript

DNS on windows usually come with Active directory service. But also can used to query external Domain name as long as the server have internet connection.


Hostname entries in DNS also rarely changed and some use local cache with TTL from server. Somehow, we need to monitor a change in DNS query result with alert when these changes happend.

Let say it is other Domain name which not in our control, we want to know immidiately when the Address changed in DNS. And also alert with email that the query result changed with the query info inside the email.

Within windows 7 as client, we can do this using a VBScript and a task scheduler, and access to SMTP mail server to sent out the alert.

Below are the script to be used. The script will query the domain to be monitor, and check if the result as expected. then it will sent email with the query result, and change subject if host name is changed for the monitored domain.

strEmailTo="anyong@superbadmin.com"
strEmailFrom="dnsmonitor@superbadmin.com"
strDomain="superdomain.com"
strDNSServer="192.168.1.111"
strSMTPServer="192.168.1.232"
iSMTPPort=25
strLogs = "c:\scripts\dnsmon\logs\"
Const ForAppending = 8 'for loggin
Dim strLogFile, objFSO, strDate, objLogFile

arrRecords = Array( _
 "Name:    " & strDomain ,_
 "Address:  " &  "172.10.120.121" _
)

Set objShell = CreateObject("WScript.Shell")
'Set objNSLookup = objShell.Exec("nslookup -q=MX " & strDomain & " " & strDNSServer)
Set objNSLookup = objShell.Exec("nslookup " & strDomain & " " & strDNSServer)
Set objStdOut = objNSLookup.StdOut
strOutput = objStdOut.ReadAll

strMsg = "NSLookup Output: " & VbCrLf & VbCrLf & strOutput & VbCrLf & "Test Results:" & vbCrLf

bChanged = False
For Each strRecord In arrRecords
 bRecordChanged = False
 If InStr(strOutput, strRecord) = 0 Then
  bRecordChanged = True
  bChanged = True
 End If
 strMsg = strMsg & VbCrLf & "Changed: " & bRecordChanged & " - " & strRecord
Next

strMsg = strMsg & VbCrLf & VbCrLf & "Overall result of change: " & bChanged & VbCrLf & "############################"

'Logging Part
strLogFile = strLogs & "superdomain.com-check-logs-" & Year(strDate) & "-" & Month(strDate) & "-" & Day(strDate) & ".log" 'for log file
set objFSO = CreateObject("Scripting.FileSystemObject")
set objLogFile = objFSO.OpenTextFile(strLogFile, ForAppending, True)
objLogfile.WriteLine Now & " ## " &strMsg 
objLogFile.Close
set objLogFile = Nothing
set objFSO = Nothing
'//////////
'end logging

'WScript.Echo strMsg

'Context.LogMessage strMsg
'bChanged = True
'If bChanged = True then
If True then
 Set objEmail = CreateObject("CDO.Message")
 objEmail.From = strEmailFrom
 objEmail.To = strEmailTo
 if bChanged = True then
  objEmail.Subject = "[Mon] superweb.com DNS Changed"
 else
  objEmail.Subject = "[Mon] superweb.com DNS Change"
 End If
 objEmail.Textbody = "Checked : " & Now & VbCrLf & strOutput
 objEmail.Configuration.Fields.Item _
     ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
 objEmail.Configuration.Fields.Item _
     ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTPServer
 objEmail.Configuration.Fields.Item _
     ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = iSMTPPort
 objEmail.Configuration.Fields.Update
 objEmail.Send
 'Context.SetResult = 1
Else
 'Context.SetResult = 0
End If

This simple vbscript can be executed on windows and need have access to smtp server to sent out emails.


Sunday, 17 May 2015

Generate Highchart with Ajax request


Highchart Dashboard
Bar Chart
Recently i have to create a dashboard. And a dashboard should have a graphical interface that showing chart.

I look for the alternative solution from Flotr , goggle chart, and Highchart. After some search, i conclude to use highchart.

Some criteria i made in the search are :
  1. Running in javascript
  2. Work in any web browser
  3. Can use ajax to load data
  4. Have multiple chart options
  5. Good documentation
  6. Full feature and basic needs for display report chart with data
The most important one is, i need to generate the chart via ajax and load json data. so here some of my documentation to generate highchart with ajax loading json data. Many other way to generate the chart in the net, you can found others in the net.


var myAjaxChart;

$(document).ready(function () {

    monthlyChart = new Highcharts.Chart({
       chart: {
            renderTo: 'monthlyChart',
            type: 'column'
            },
       title: {
            text: 'Profit per month'
            }, 
       xAxis: {
            categories: ['Jan','Feb','Mar']
            }, 
       yAxis: {
            title: {
                text: 'USD'
                 }
            }
      });

 
  setIntervalAndExecute(function(){

    $.getJSON('/Ajax/profit-per-month', function(data) {
         monthlyChart.clearSeries();
         $.each(data, function (key, value) {
             monthlyChart.addSeries({
                name: value.Name,
                data: value.Values
             }); ;
          });
     });
  }, 5000);

});

You will have the code to have data from the ajax url /Ajax/profit-per-month

For the json generation, will be on other blog page discussion i guess.

Hope this help you with highchart coding.

Tuesday, 2 December 2014

Lightweight Battery Monitoring in Debian

I use Fluxbox in my desktop laptop with Debian 7 OS. I need a battery status monitor which is easy to spot the battery status.

So i found this small application, xbattbar which can monitor battery status via acpi which many laptop support nowdays.

Just install and run it with the startup of the fluxbox.

To run it call the application with :

$xbattbar

To run with acpi :

$xbattbar -c

Here are some preview of my desktop. The green bar below is the battery status.

Xbattbar Status in desktop



Friday, 14 November 2014

Centralized vs Decentralized application portfolio strategy

In managing IT startegy, especially Application portfolio, there are 2 management style which are Centralized and Decentralized in decision making. And for better understanding deeper about the 2 style, there are 4 type matrix for the strategy in detailed view using below matrix.

Source: John Ward and Joe Peppard, Strategic Planning for Information System p.336


Tuesday, 11 November 2014

Highlight text in PDF

We all use pdf, because many documents also use pdf for their publishing formats. Even ebooks come with pdf, and sometimes when reading it, we need to jot down notes on it or highlight it as we used to with a books.

So with pdf, we can do highlight the important one, and even the original pdf still intanct. Here come the application that can do this. Xournal is a pdf highlight application, which create a new file to overlay the highlight of pdf. Even you can create your own version of pdf which already been highlihted.


PDF Highlight
Xournal run in Unix BSD, Linux, MacOS , and Windows with source code.

Visit their website xournal

Happy Highlight in PDF.

Twitter Delicious Facebook Digg Stumbleupon Favorites More