summaryrefslogtreecommitdiff
path: root/main/views.py
blob: 0aadb1891381a743f1f1e04335c2da7e30902717 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008  Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.

"""
Views of the project
"""

import datetime

from django.shortcuts import render_to_response
from django.template import loader
from django.http import HttpResponseRedirect, HttpResponse
from django.core import serializers

from chimere import settings
from chimere.main.actions import actions
from chimere.main.models import SubCategory, PropertyModel, Marker, Route, News
from chimere.main.widgets import getMapJS, PointChooserWidget, \
                                 RouteChooserWidget, URL_OSM_JS
from chimere.main.forms import MarkerForm, RouteForm

def index(request):
    """
    Main page
    """
    subcategories = SubCategory.getAvailable()
    # by default all subcategories are checked
    for cat, sub_cats in subcategories:
        all_checked = True
        for sub_category in sub_cats:
            if sub_category.id in settings.DEFAULT_CATEGORIES:
                sub_category.selected = True
            elif all_checked:
                all_checked = False
        if all_checked:
            cat.selected = True
    extra_js = ""
    for url in URL_OSM_JS + ["%smain_map.js" % settings.MEDIA_URL]:
        extra_js += '<script src="%s"></script>\n' % url
    extra_js += '<script src="/chimere/jsi18n/"></script>\n'
    # show the welcome page
    today = datetime.date.today().strftime('%y-%m-%d')
    display_welcome = None
    if not 'last_visit' in request.session or \
       request.session['last_visit'] != today:
        request.session['last_visit'] = today
        display_welcome = True
    response_dct = {'actions':actions, 'action_selected':'view',
                    'error_message':'',
                    'sub_categories':subcategories,
                    'extra_head':extra_js + getMapJS(),
                    'media_path':settings.MEDIA_URL,
                    'welcome':welcome(request, display_welcome),
                    }
    return render_to_response('main_map.html', response_dct)

def edit(request):
    """
    Edition page
    """
    # If the form has been submited
    if request.method == 'POST':
        form = MarkerForm(request.POST, request.FILES)
        # All validation rules pass
        if form.is_valid():
            marker = form.save()
            # set the submited status
            marker.status = 'S'
            marker.save()
            return HttpResponseRedirect('/chimere/submited/edit')
    else:
        # An unbound form
        form = MarkerForm()
    # get the « manualy » declared_fields. Ie: properties
    declared_fields = form.declared_fields.keys()
    response_dct = {'actions':actions, 'action_selected':'edit',
                  'error_message':'',
                  'media_path':settings.MEDIA_URL,
                  'form':form,
                  'extra_head':form.media,
                  'sub_categories':SubCategory.getAvailable(['M', 'B']),
                  'point_widget':PointChooserWidget().render('point', None),
                  'properties':declared_fields
                   }
    # manualy populate the custom widget
    if 'subcategory' in form.data and form.data['subcategory']:
        response_dct['current_category'] = int(form.data['subcategory'])
    return render_to_response('edit.html', response_dct)

def editRoute(request):
    """
    Route edition page
    """
    # If the form has been submited
    if request.method == 'POST':
        form = RouteForm(request.POST, request.FILES)
        # All validation rules pass
        if form.is_valid():
            route = form.save()
            # set the submited status
            route.status = 'S'
            route.save()
            return HttpResponseRedirect('/chimere/submited/edit_route')
    else:
        # An unbound form
        form = RouteForm()
    # get the « manualy » declared_fields. Ie: properties
    declared_fields = form.declared_fields.keys()
    response_dct = {'actions':actions, 'action_selected':'edit_route',
                  'error_message':'',
                  'media_path':settings.MEDIA_URL,
                  'form':form,
                  'extra_head':form.media,
                  'sub_categories':SubCategory.getAvailable(['R', 'B']),
                  'route_widget':RouteChooserWidget().render('route', None),
                  'properties':declared_fields
                   }
    # manualy populate the custom widget
    if 'subcategory' in form.data and form.data['subcategory']:
        response_dct['current_category'] = int(form.data['subcategory'])
    return render_to_response('edit_route.html', response_dct)

def welcome(request, display=None):
    """
    Welcome string
    """
    response_dct = {'display':display}
    response_dct['news_lst'] = News.objects.filter(available=True)
    return loader.render_to_string('welcome.html', response_dct)

def submited(request, action):
    """
    Successful submission page
    """
    response_dct = {'actions':actions, 'action_selected':action,
                    'media_path':settings.MEDIA_URL,}
    return render_to_response('submited.html', response_dct)

def getDetail(request, marker_id):
    '''
    Get the detail for a marker
    '''
    try:
        marker = Marker.objects.filter(id=int(marker_id), status='A')[0]
    except (ValueError, IndexError):
        return HttpResponse('no results')
    response_dct= {'media_path':settings.MEDIA_URL, 'marker':marker}
    return render_to_response('detail.html', response_dct)

def getGeoObjects(request, category_ids, status='A'):
    '''
    Get the JSON for a route
    '''
    status = status.split('_')
    try:
        query = Route.objects.filter(status__in=status,
                                    subcategory__in=category_ids.split('_'))
    except:
        return HttpResponse('no results')
    geo_objects = list(query)
    try:
        query = Marker.objects.filter(status__in=status,
                                    subcategory__in=category_ids.split('_'))
    except:
        return HttpResponse('no results')
    geo_objects += list(query)
    if not geo_objects:
        return HttpResponse('no results')
    data = '{"type": "FeatureCollection", "features":[%s]}' % \
           ",".join([geo_object.getGeoJSON() for geo_object in geo_objects])
    return HttpResponse(data)