Changeset 6517


Ignore:
Timestamp:
Dec 30, 2008, 1:40:27 PM (16 years ago)
Author:
roland
Message:

Major code cleanup of views.py.
Changed old edit and delete links in view/node/ to the
admin interface.
The edit and delete links are only visible when loggen in.

Location:
trunk/exodus
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • trunk/exodus/settings.py

    r6477 r6517  
    5858)
    5959
     60TEMPLATE_CONTEXT_PROCESSORS = (
     61    'django.core.context_processors.auth',
     62    'django.core.context_processors.media',
     63    'exodus.utils.get_domain',
     64)
     65
    6066MIDDLEWARE_CLASSES = (
    6167    'django.middleware.common.CommonMiddleware',
  • trunk/exodus/templates/viewNode.html

    r6512 r6517  
    1212
    1313Master ip: {{ node.masterip }} <br>
    14 <a href="{% url exodus.views.genericNode "edit" node.name %}">EDIT</a>
    15 <a href="{% url exodus.views.genericNode "delete" node.name %}">DELETE</a>
     14
     15{% if user.is_authenticated %}
     16<a href="{{ domain }}/admin/exodus/node/{{ node.id }}/">EDIT</a>
     17<a href="{{ domain }}/admin/exodus/node/{{ node.id }}/delete/">DELETE</a>
     18{% endif %}
    1619</div>
    1720
    1821<h2>Interfaces</h2>
    19 <a href="{% url exodus.views.genericInterface "add" node.name "new" %}">Add new interface</a><p />
     22{% if user.is_authenticated %}
     23<a href="{{ domain }}/admin/exodus/interface/add/">Add new interface</a><p />
     24{% endif %}
    2025
    2126{% for nic in node.interface_set.all %}
     
    3237                Antenna: {{ nic.antenna }} <br>
    3338                Polar: {{ nic.get_polar_display }} <br>
     39        Direction: {{ nic.get_direction_display }} <br />
    3440                Mode: {{ nic.get_mode_display }} <br>
    3541        {% endifnotequal %}
    36         <a href="{% url exodus.views.genericInterface "edit" node.name nic.iface %}">EDIT</a>
    37         <a href="{% url exodus.views.genericInterface "delete" node.name nic.iface %}">DELETE</a>
     42    {% if user.is_authenticated %}
     43        <a href="{{ domain }}/admin/exodus/interface/{{ nic.id }}/">EDIT</a>
     44        <a href="{{ domain }}/admin/exodus/interface/{{ nic.id }}/delete/">DELETE</a>
     45    {% endif %}
    3846        </div>
    3947
  • trunk/exodus/urls.py

    r6447 r6517  
    1313            "root"),
    1414    (r'^view/nodelist/$', 'exodus.views.viewNodelist'),
    15     (r'^view/list/(?P<model>.+)/$', 'exodus.views.viewList'),
    1615    (r'^view/node/(?P<node>.+)/$', 'exodus.views.viewNode'),
    1716
    1817    # config urls
    1918    (r'^config/(?P<version>.+)/(?P<node>.+)/(?P<file>.+)$', 'exodus.views.configFile'),
    20 
    21     # Generic urls
    22     (r'^(?P<mode>(add|edit|delete))/node/(?P<node>.+)/$', 'exodus.views.genericNode'),
    23     (r'^(?P<mode>(add|edit|delete))/nic/(?P<node>.+)/(?P<interface>.+)/$', 'exodus.views.genericInterface'),
    24     #(r'^(?P<mode>(add|edit|delete))/dhcp/(?P<node>.+)/(?P<interface>.+)/(?P<publicAP>.+)/$', 'exodus.views.genericPublicAP'),
    25     (r'^(?P<mode>(add|edit|delete))/(?P<model>.+)/(?P<object>.+)/$', 'exodus.views.genericModel'),
    2619
    2720    # 3th party/embedded database browser
  • trunk/exodus/utils.py

    r6357 r6517  
    11from exodus.settings import DEBUG
     2from urlparse import urlsplit
    23
    34def pdebug(level, message):
    45    if level > 0 and DEBUG:
    56        print "DEBUG [%s] %s" % (level, message)
     7
     8def get_domain(request):
     9    """Gets the complete domain."""
     10    uri = request.build_absolute_uri()
     11    parsed = urlsplit(uri)
     12    domain = parsed.scheme + '://' + parsed.netloc
     13    return {'domain' : domain }
  • trunk/exodus/views.py

    r6481 r6517  
    11# (c) Roland van Laar 2006
    22
    3 from django.http import HttpResponseRedirect
    43from django.shortcuts import render_to_response
    5 from django.core.urlresolvers import reverse, NoReverseMatch
    6 from django import forms
     4from django.template import RequestContext
    75from socket import gethostname
    86
    9 from exodus.models import *
    10 from exodus.wllogic import free_master_ip, new_ssid
     7from exodus.models import Node
    118
    12 from exodus.utils import pdebug
    13 
    14 class GenericHandler(object):
    15     """Conventions used: type has to to the same name as the dependency
    16     object, delet template is named delete<type>.html
    17     """
    18     def __init__(self, request, mode):
    19         pdebug(100, "Function: GenericHandler.__init__")
    20         # Strip 'Handler' of name
    21         type = self.__class__.__name__[:-7:]
    22         formClass = eval(type + 'Form')
    23 
    24         self.object = eval('self.' + type[0].lower() + type[1::])
    25         self.title = self.object._meta.verbose_name
    26         self.request = request
    27         self.mode = mode
    28         self.is_changed = {}
    29        
    30         if request.POST.has_key('cancel'):
    31             pdebug(100, "Action cancel")
    32             self.form_action = 'cancel'
    33             # Allow overriding cancel call, in particular with regards to the
    34             # response call
    35             self._cancel()
    36         elif request.POST.has_key('proceed'):
    37             pdebug(100, "Action proceed")
    38             self.form_action = 'proceed'
    39            
    40             # Delete does not require a valid form
    41             if mode == 'delete':
    42                 self._delete()
    43             else:
    44                 # First checking whether form is valid, then add/edit actions
    45                 self.form = formClass(request.POST, instance=self.object)
    46                 try:
    47                     if self.form.is_valid():
    48                         pdebug(100, "Form valid")
    49                         # Set response on forehand, to allow override \
    50                         # in procedure
    51                         try:
    52                             self.response = HttpResponseRedirect(reverse( \
    53                                 'exodus.views.viewNode', args=[self.node.name]))
    54                         except (AttributeError, NoReverseMatch):
    55                             self.response = HttpResponseRedirect(reverse( \
    56                                 'exodus.views.viewNodelist'))
    57                        
    58                         #Checking whether data did change
    59                         _oldInstance = dict(self.object.as_list())
    60                         _instance  = dict(self.form.save(commit=False).as_list())
    61                         for key,value in _instance.items():
    62                             if value != _oldInstance[key]:
    63                                 pdebug(100, "Key %s changed value '%s' -> '%s'"\
    64                                     % (key, _oldInstance[key], value))
    65                                 self.is_changed[key] = value
    66                        
    67                         # Call override procedure
    68                         if mode == 'add':
    69                             self._add()
    70                         elif mode == 'edit':
    71                             self._edit()
    72                         else:
    73                             raise ValueError, 'Mode "%s" not defined' % mode
    74                     else:
    75                         raise ValueError, 'Form error, please edit and resubmit'
    76                 except ValueError, message:
    77                     self.response = render_to_response('genericForm.html', {
    78                         'form': self.form, 'message' : message,
    79                         'title' : self.title, 'mode' : mode,
    80                         'type' : type, 'object': self.object,
    81                         'delInclude' : "delete" + type.capitalize() + ".html",
    82                         'addInclude' : "add" + type.capitalize() + ".html",
    83                         'editInclude' : "edit" + type.capitalize() + ".html" })
    84         else:
    85             message = 'Please edit and submit'
    86            
    87             # Dirty? hack to allow initial form to be filled with date \
    88             # for GET request, no errors raised
    89             if request.GET and mode == 'add':
    90                 self.form = formClass(request.GET, instance=self.object)
    91                 self.form._errors = {}
    92             else:
    93                 self.form = formClass(instance=self.object)
    94            
    95             self.response = render_to_response('genericForm.html', {
    96                 'form': self.form, 'message' : message, 'title' : self.title,
    97                 'mode' : mode, 'type' : type, 'object': self.object,
    98                 'delInclude' : "delete" + type.capitalize() + ".html",
    99                 'addInclude' : "add" + type.capitalize() + ".html",
    100                 'editInclude' : "edit" + type.capitalize() + ".html" })
    101    
    102     def _add(self):
    103         pdebug(100, "Function: GenericHandler._add")
    104         self.form.save()
    105    
    106     def _edit(self):
    107         pdebug(100, "Function: GenericHandler._edit")
    108         self.form.save()
    109    
    110     def _delete(self):
    111         pdebug(100, "Function: GenericHandler._delete")
    112         self.object.delete()
    113         self.response = HttpResponseRedirect(reverse('exodus.views.viewNode',\
    114                 args=[self.node.name]))
    115    
    116     def _cancel(self):
    117         pdebug(100, "Function: GenericHandler._cancel")
    118         self.response = HttpResponseRedirect(reverse('exodus.views.viewNode',\
    119                  args=[self.node.name]))
    120         #self.response = HttpResponseRedirect(reverse('exodus.views.viewNodelist'))
    121    
    122     def render_to_response(self):
    123         pdebug(100, "Function: GenericHandler.render_to_response")
    124         return self.response
    125 
    126 
    127 #
    128 # PublicAP
    129 #class PublicAPForm(forms.ModelForm):
    130 #    class Meta:
    131 #        model = PublicAP
    132 #        exclude = ('shortdesc', 'desc', 'ip', 'dhcpstart', 'dhcpstop')
    133 #
    134 #class PublicAPHandler(GenericHandler):
    135 #
    136 #    def __init__(self, request, node, interface, publicAP, mode):
    137 #        pdebug(100, "Function: PublicAPHandler.__init__")
    138 #        self.node = Node.objects.get(name=node)
    139 #        self.interface = Interface.objects.get(node=self.node, iface=interface)
    140 #        if mode == 'add':
    141 #            self.publicAP = PublicAP(iface=self.interface)
    142 #        else:
    143 #            self.publicAP =  PublicAP.objects.get(iface=self.interface, \
    144 #                    pk=publicAP)
    145 #        super(PublicAPHandler, self).__init__(request, mode)
    146 #
    147 #    def _add(self):
    148 #        pdebug(100, "Function: PublicAPHandler._add")
    149 #        _instance = self.form.save(commit=False)
    150 #        # Find IP range inside interface range with disired size/subnet
    151 #        _instance.ip = free_publicap_ip(_instance.iface, _instance.netmask)
    152 #        _instance.dhcpstart = 1
    153 #        _instance.dhcpstop = 2
    154 #        # If wireless generate ssid name
    155 #        _instance.ssid = new_ssid(_instance.iface.node, _instance.iface, \
    156 #                'omni')
    157 #        _instance.save()
    158 #
    159 #def genericPublicAP(request, node, interface, publicAP, mode):
    160 #    pdebug(100, "Function: genericPublicAP")
    161 #    handler = PublicAPHandler(request, node, interface, publicAP, mode)
    162 #    return handler.render_to_response()
    163 #
    164 #
    165 # Interface
    166 class InterfaceForm(forms.ModelForm):
    167     class Meta:
    168         model = Interface
    169         exclude = ( 'ip', 'ssid', 'mode', 'channel', 'shortdesc', \
    170                 'netmask' )
    171 
    172 class InterfaceHandler(GenericHandler):
    173     def __init__(self, request, node, interface, mode):
    174         pdebug(100, "Function: InterfaceHandler.__init__")
    175         self.node = Node.objects.get(name=node)
    176         if mode == 'add':
    177             self.interface = Interface(node=self.node)
    178         else:
    179             self.interface = Interface.objects.get(node=self.node, \
    180                 iface=interface)
    181         super(InterfaceHandler, self).__init__(request, mode)
    182 
    183     def _add(self):
    184         pdebug(100, "Function: InterfaceHandler._add")
    185         self._saveInterface()
    186 
    187     def _edit(self):
    188         pdebug(100, "Function: InterfaceHandler._edit")
    189         self._saveInterface()
    190 
    191     def _saveInterface(self):
    192         pdebug(100, "Function: InterfaceHandler._saveInterface")
    193         _instance  = self.form.save(commit=False)
    194         if _instance.link and (_instance.type != _instance.link.type):
    195             raise ValueError,'Type of local and remote interface needs to match'
    196         if str(_instance.type) != "eth":
    197             _instance.ssid = new_ssid(_instance.node, _instance.iface, \
    198                     'unused')
    199             _instance.channel = '1'
    200             _instance.mode = 1 # set to master
    201        
    202         # Only change IP if changes in interface link/mask or new of course :-)
    203         if self.mode == 'add' or self.is_changed.has_key('link') or \
    204                 self.is_changed.has_key('netmask'):
    205             if not _instance.link:
    206                 #_instance.ip = free_interlink_ip(_instance)
    207                 pass
    208 
    209             else:
    210                 #_instance.ip = add_interlink_ip(_instance.link)
    211                 pass
    212 
    213         # XXX: Change in netmask requires full range of netmask changes \
    214         # on slaves
    215         _instance.save()
    216         #Dirty to hack to get reference to self working
    217         if not _instance.link:
    218             _instance.link = _instance
    219             _instance.save()
    220 
    221 def genericInterface(request, node, interface, mode):
    222     pdebug(100, "Function: genericInterface")
    223     handler = InterfaceHandler(request, node, interface, mode)
    224     return handler.render_to_response()
    225 
    226 #
    227 # Node
    228 class NodeForm(forms.ModelForm):
    229     class Meta:
    230         model = Node
    231         exclude = ( 'masterip' )
    232 
    233 class NodeHandler(GenericHandler):
    234     def __init__(self, request, node, mode):
    235         pdebug(100, "Function: NodeHandler.__init__")
    236         if mode == 'add':
    237             self.node = Node()
    238         else:
    239             self.node = Node.objects.get(name=node)
    240         super(NodeHandler, self).__init__(request, mode)
    241 
    242     def _add(self):
    243         pdebug(100, "Function: NodeHandler._add")
    244         # input a valid master ip into new_data
    245         _instance  = self.form.save(commit=False)
    246         _instance.masterip = free_master_ip(_instance.network)
    247         _instance.save()
    248         self.response = HttpResponseRedirect(reverse('exodus.views.viewNode', \
    249                 args=[_instance.name]))
    250 
    251     def _delete(self):
    252         pdebug(100, "Function: NodeHandler._delete")
    253         for _master in Interface.objects.filter(node=self.object):
    254             if _master.link == _master:
    255                 for _makeMaster in Interface.objects.filter(link=_master):
    256                     _makeMaster.link = _makeMaster
    257                     _makeMaster.save()
    258         self.object.delete()
    259         # As node is deleted, goto overview page
    260         self.response = HttpResponseRedirect(reverse( \
    261                     'exodus.views.viewNodelist'))
    262 
    263     def _cancel(self):
    264         pdebug(100, "Function: NodeHandler._cancel")
    265         if self.mode == 'new':
    266             self.response = HttpResponseRedirect(reverse( \
    267                     'exodus.views.viewNodelist'))
    268         else:
    269             self.response = HttpResponseRedirect(reverse( \
    270                     'exodus.views.viewNode', args=[self.node.name]))
    271 
    272 def genericNode(request, node, mode):
    273     pdebug(100, "Function: genericNode")
    274     handler = NodeHandler(request, node, mode)
    275     return handler.render_to_response()
    276 
    277 #
    278 # location
    279 class LocationForm(forms.ModelForm):
    280     class Meta:
    281         model = Location
    282 
    283 class LocationHandler(GenericHandler):
    284     def __init__(self, request, location, mode):
    285         pdebug(100, "Function: LocationHandler.__init__")
    286         if mode == 'add':
    287             self.location = Location()
    288         else:
    289             self.location = Location.objects.get(description=location)
    290    
    291         super(LocationHandler,self).__init__(request, mode)
    292 
    293     def _add(self):
    294         pdebug(100, "Function: LocationHandler._add")
    295         _instance = self.form.save()
    296         # After adding a location, allow adding a Node with this location
    297         self.response = HttpResponseRedirect( \
    298                 reverse('exodus.views.genericNode', args=["add", "new"]) + \
    299                 "?location=%i" % _instance.pk)
    300 
    301     def _delete(self):
    302         pdebug(100, "Function: LocationHandler._delete")
    303         self.object.delete()
    304         self.response = HttpResponseRedirect(reverse( \
    305                 'exodus.views.viewNodelist'))
    306 
    307     def _cancel(self):
    308         pdebug(100, "Function: LocationHandler._cancel")
    309         self.response = HttpResponseRedirect(reverse( \
    310                 'exodus.views.viewNodelist'))
    311 
    312 #
    3139# Views
    31410def viewNode(request, node):
    315     pdebug(100, "Function: viewNode")
    31611    node = Node.objects.get(name=node)
    317     return render_to_response('viewNode.html', {'node': node})
     12    return render_to_response('viewNode.html', {'node': node},
     13            context_instance=RequestContext(request))
    31814
    31915def viewNodelist(request):
    320     pdebug(100, "Function: viewNodelist")
    32116    nodes = Node.objects.all()
    32217    configFiles = (
     
    32621        'named.conf',
    32722        'resolv.conf' )
    328     return render_to_response('viewNodelist.html', {'nodes' : nodes, \
    329             'configFiles' : configFiles})
     23    return render_to_response('viewNodelist.html', {'nodes' : nodes,
     24            'configFiles' : configFiles}) 
    33025
    33126def configFile(request, version, node, file):
    332     pdebug(100, "Function: configFile")
    33327    node = Node.objects.get(name=node)
    33428   
     
    34135            mimetype='text/plain')
    34236
    343 #
    344 # DnsServer
    345 class DnsServerForm(forms.ModelForm):
    346     class Meta:
    347         model = DnsServer
    348 
    349 class DnsServerHandler(GenericHandler):
    350     def __init__(self, request, dnsServer, mode):
    351         pdebug(100, "Function: DnsServerHandler.__init__")
    352         if mode == 'add':
    353             self.dnsServer = DnsServer()
    354         else:
    355             self.dnsServer= DnsServer.objects.get(ipaddress=dnsServer)
    356         super(DnsServerHandler, self).__init__(request, mode)
    357 
    358     def _add(self):
    359         pdebug(100, "Function: DnsServerHandler._add")
    360         _instance = self.form.save()
    361         self.response = HttpResponseRedirect(reverse('exodus.views.viewList', \
    362                 args=['dnsServer']))
    363 
    364     def _delete(self):
    365         pdebug(100, "Function: DnsServerHandler._delete")
    366         self.object.delete()
    367         self.response = HttpResponseRedirect(reverse('exodus.views.viewList', \
    368                 args=['dnsServer']))
    369 
    370     def _cancel(self):
    371         pdebug(100, "Function: DnsServerHandler._cancel")
    372         self.response = HttpResponseRedirect(reverse('exodus.views.viewList', \
    373                 args=['dnsServer']))
    374 
    375 def genericModel(request, model, mode, object):
    376     pdebug(100, "Function: genericModel %s, %s, %s" % (model, mode, object))
    377     """Wrapper, to get to the function needed"""
    378     model = model[0].upper() + model[1::]
    379     model = eval(model + 'Handler')
    380     handler = model(request, object, mode)
    381     return handler.render_to_response()
    382 
    383 def viewList(request, model):
    384     pdebug(100, "Function: viewList")
    385     """Standard interface for simple overview pages, with view/edit/delete
    386     buttons on it
    387     """
    388     modelURL = model
    389     model = model[0].upper() + model[1::]
    390     modelName = model
    391     model = eval(model)
    392     objects = model.objects.all()
    393     return render_to_response('viewList.html', {'objects': objects, \
    394             'modelURL' : modelURL, 'modelName' : modelName})
Note: See TracChangeset for help on using the changeset viewer.