Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRogelio Mita <rogeliomita@activitycentral.com>2013-03-09 05:46:01 (GMT)
committer Rogelio Mita <rogeliomita@activitycentral.com>2013-03-09 05:57:27 (GMT)
commit0c90434221ecabb8c6eea207cba7a8a403b0d947 (patch)
treeac04ce61204c16cf14eb70b0599824b7ca885d24
parentd0895bd5ad8521a6f36fb5a06b3c8a1448e77dbb (diff)
Poll list correction, poll structure modification.
-rw-r--r--webapp/deploy/dev_testing/nginx.conf4
-rw-r--r--webapp/deploy/staging/nginx.conf4
-rw-r--r--webapp/deploy/testing/nginx.conf4
-rw-r--r--webapp/polls/forms.py5
-rw-r--r--webapp/polls/models.py95
-rw-r--r--webapp/polls/templates/poll-form.html (renamed from webapp/polls/templates/poll-add.html)12
-rw-r--r--webapp/polls/templates/poll-list.html23
-rw-r--r--webapp/polls/templates/poll-structure-form.html (renamed from webapp/polls/templates/poll-structure.html)35
-rw-r--r--webapp/polls/templates/poll-success.html19
-rw-r--r--webapp/polls/templates/sucess.html28
-rw-r--r--webapp/polls/templates/tags/structure.html2
-rw-r--r--webapp/polls/templatetags/poll_tags.py2
-rw-r--r--webapp/polls/tests.py47
-rw-r--r--webapp/polls/urls.py8
-rw-r--r--webapp/polls/views.py116
-rw-r--r--webapp/webapp/media/output/empty0
-rw-r--r--webapp/webapp/settings.py8
-rw-r--r--webapp/webapp/templates/base-main.html17
-rw-r--r--webapp/webapp/urls.py2
19 files changed, 281 insertions, 150 deletions
diff --git a/webapp/deploy/dev_testing/nginx.conf b/webapp/deploy/dev_testing/nginx.conf
index cca4a7b..5adf4a6 100644
--- a/webapp/deploy/dev_testing/nginx.conf
+++ b/webapp/deploy/dev_testing/nginx.conf
@@ -5,10 +5,6 @@ server {
error_log /var/log/nginx/polls-dev_testing.net_error.log;
root /home/ceibal/virtualenvs/polls/dev_testing/webapp/webapp;
- location /media/output {
- autoindex on;
- }
-
location / {
uwsgi_pass unix:///var/run/uwsgi/app/polls_webapp_testing/socket;
include uwsgi_params;
diff --git a/webapp/deploy/staging/nginx.conf b/webapp/deploy/staging/nginx.conf
index 11a8d70..a5c53a5 100644
--- a/webapp/deploy/staging/nginx.conf
+++ b/webapp/deploy/staging/nginx.conf
@@ -5,10 +5,6 @@ server {
error_log /var/log/nginx/polls-staging.net_error.log;
root /home/ceibal/virtualenvs/polls/staging/webapp/webapp;
- location /media/output {
- autoindex on;
- }
-
location / {
uwsgi_pass unix:///var/run/uwsgi/app/polls_webapp_staging/socket;
include uwsgi_params;
diff --git a/webapp/deploy/testing/nginx.conf b/webapp/deploy/testing/nginx.conf
index 10b4b9c..8c5b45e 100644
--- a/webapp/deploy/testing/nginx.conf
+++ b/webapp/deploy/testing/nginx.conf
@@ -5,10 +5,6 @@ server {
error_log /var/log/nginx/polls-testing.net_error.log;
root /home/ceibal/virtualenvs/polls/testing/webapp/webapp;
- location /media/output {
- autoindex on;
- }
-
location / {
uwsgi_pass unix:///var/run/uwsgi/app/polls_webapp_testing/socket;
include uwsgi_params;
diff --git a/webapp/polls/forms.py b/webapp/polls/forms.py
index db387f2..875a5ae 100644
--- a/webapp/polls/forms.py
+++ b/webapp/polls/forms.py
@@ -6,7 +6,10 @@ from polls.models import Poll
class PollAddForm(forms.Form):
- name = forms.CharField(required=True, label="Nombre")
+ id = forms.RegexField(
+ required=False, regex=r'[0-9A-Fa-f]{24}', widget=forms.HiddenInput())
+ name = forms.CharField(
+ required=True, label="Nombre")
def save(self):
# require: run is_valid method first
diff --git a/webapp/polls/models.py b/webapp/polls/models.py
index ee62380..6d049c2 100644
--- a/webapp/polls/models.py
+++ b/webapp/polls/models.py
@@ -1,8 +1,9 @@
# -*- encoding: utf-8 -*-
import time
+import json
from exceptions import *
-from bson import ObjectId
+from bson import ObjectId, DBRef
from utils.mongo_connection import get_db
@@ -23,12 +24,14 @@ class AbstracErrorObject(object):
class Poll(AbstracErrorObject):
+ collection_name = 'polls'
+
def __init__(self, data={}):
super(Poll, self).__init__()
self.id = None
_id = data.get('id', None) or data.get('_id', None)
- if _id and isinstance(_id, str):
+ if _id and (isinstance(_id, str) or isinstance(_id, unicode)):
self.id = ObjectId(_id)
elif _id and isinstance(_id, ObjectId):
self.id = _id
@@ -39,7 +42,7 @@ class Poll(AbstracErrorObject):
_dict = {}
if self.id:
- _dict.update({'_id': str(id)})
+ _dict.update({'_id': self.id})
if self.name:
_dict.update({'name': self.name})
@@ -61,8 +64,7 @@ class Poll(AbstracErrorObject):
poll_id = None
- if not self.id:
- poll_id = get_db().polls.save(self.to_dict())
+ poll_id = get_db().polls.save(self.to_dict())
return poll_id
@@ -78,6 +80,29 @@ class Poll(AbstracErrorObject):
return poll
+ # TODO: Test
+ @staticmethod
+ def all():
+ _all = []
+ for poll_data in get_db().polls.find():
+ _all.append(Poll(poll_data))
+
+ return _all
+
+ def to_json(self):
+ structure_data = get_db().structures.find_one(
+ {'poll.$id': self.id}, fields={'_id': False, 'poll': False})
+
+ _json = json.dumps(
+ structure_data,
+ sort_keys=True,
+ indent=4,
+ separators=(',', ': '),
+ ensure_ascii=False
+ )
+
+ return _json
+
class AbastractObject(AbstracErrorObject):
@@ -250,12 +275,21 @@ class Structure(AbastractObject):
}
"""
- def __init__(self, data=None):
+ def __init__(self, data=None, poll=None):
super(Structure, self).__init__()
self.data = data
self.groups = []
+ self.poll = poll
+ self.id = None
+
+ _id = data.get('id', None) or data.get('_id', None)
+ if _id and (isinstance(_id, str) or isinstance(_id, unicode)):
+ self.id = ObjectId(_id)
+ elif _id and isinstance(_id, ObjectId):
+ self.id = _id
if self.data:
+ # TODO: Revisar la key groups
groups_info = data['groups']
for group_order, group_data in groups_info.iteritems():
group = Group(name=group_data['name'])
@@ -317,13 +351,17 @@ class Structure(AbastractObject):
def to_dict(self, with_errors=False):
_dict = dict()
for group_order, group_obj in enumerate(self.groups):
- _dict[group_order] = {'name': group_obj.name, 'fields': {}}
+ group_order = str(group_order)
+ _dict[group_order] = {
+ 'name': group_obj.name, 'fields': {}
+ }
if with_errors:
_dict[group_order].update({'errors': group_obj.errors})
for field_order, field_obj in enumerate(group_obj.fields):
+ field_order = str(field_order)
_dict[group_order]['fields'].update({
- field_order: {
+ '%s' % field_order: {
'name': field_obj.name,
'widget_type': field_obj.widget_type,
'dependence': field_obj.dependence,
@@ -338,6 +376,43 @@ class Structure(AbastractObject):
for option in options:
_dic_field = _dict[group_order]['fields'][field_order]
_dic_field['options'].update(
- {option.id: {'text': option.text}}
+ {'%s' % option.id: {'text': option.text}}
)
- return _dict
+ return {'groups': _dict}
+
+ def save(self):
+ structure_id = None
+
+ self.validate()
+
+ _dict = self.to_dict()
+
+ # Prepare dbref to poll object
+ if not self.poll:
+ raise ValidationError("Need a parent poll.")
+ else:
+ dbref = DBRef(Poll.collection_name, ObjectId(self.poll.id))
+ _dict.update({'poll': dbref})
+
+ # Prepare id if is a existing Structure object
+ if self.id:
+ _dict.update({'_id': ObjectId(self.id)})
+
+ # Save process -> Update if it have id, else insert
+ structure_id = get_db().structures.save(_dict)
+
+ return structure_id
+
+ @staticmethod
+ def get(id=None):
+ structure = None
+
+ objects = get_db().structures.find({'_id': ObjectId(id)})
+ if objects.count():
+ obj = objects[0]
+ poll_id = obj['poll'].id
+
+ structure = Structure(obj)
+ structure.poll = Poll.get(poll_id)
+
+ return structure
diff --git a/webapp/polls/templates/poll-add.html b/webapp/polls/templates/poll-form.html
index 6fdb709..7114864 100644
--- a/webapp/polls/templates/poll-add.html
+++ b/webapp/polls/templates/poll-form.html
@@ -1,16 +1,24 @@
{% extends "base-poll.html" %}
{% load i18n %}
+{% block title %}Formulario de encuesta{% endblock %}
+
{% block main_container %}
<div class="center">
- <h2>{% trans 'Creación de encuesta' %}</h2>
+ <h2>{% trans 'Formulario de encuesta' %}</h2>
</div>
<form class="form-inline" action="" method="post">{% csrf_token %}
+
+ {% if poll.id %}
+ <input type="hidden" name="id" value="{{ poll.id }}" />
+ {% endif %}
+
<div class="control-group {% if form.name.errors %}error{% endif %}">
<div class="controls">
- <input type="text" name="name" id="id_name" placeholder="{{ form.name.label }}" />
+ <label class="control-label" for="id_name">{{ form.name.label }}:</label>
+ <input type="text" name="name" id="id_name" placeholder="{{ form.name.label }}" value="{{ poll.name }}" />
<span class="help-inline">{{ form.name.errors }}</span>
</div>
</div>
diff --git a/webapp/polls/templates/poll-list.html b/webapp/polls/templates/poll-list.html
index 2474b4e..500cb55 100644
--- a/webapp/polls/templates/poll-list.html
+++ b/webapp/polls/templates/poll-list.html
@@ -1,17 +1,32 @@
{% extends "base-poll.html" %}
{% block main_container %}
- <table class="table table-hover">
+ <table class="table table-hover table-bordered">
<thead>
<tr>
- <th>Nombre</th>
- <th colspan="4"><center>Acciones</center></th>
+ <th class="span6">Nombre</th>
+ <th colspan="3"><center>Acciones</center></th>
</tr>
</thead>
<tbody>
{% for poll in polls %}
<tr>
- <td>{{ poll.name }}</td>
+ <td>{{ poll.name|capfirst }}</td>
+ <td>
+ <a class="btn" href="{% url polls:edit id=poll.id %}">
+ <i class="icon-edit"></i>&nbsp;Modificar datos de encuesta
+ </a>
+ </td>
+ <td>
+ <a class="btn" href="{% url polls:structure.builder poll_id=poll.id %}">
+ <i class="icon-wrench"></i>&nbsp;Modificar estructura
+ </a>
+ </td>
+ <td>
+ <a class="btn" href="{% url polls:download poll_id=poll.id %}">
+ <i class="icon-download-alt"></i>&nbsp;Descargar encuesta
+ </a>
+ </td>
</tr>
{% endfor %}
</tbody>
diff --git a/webapp/polls/templates/poll-structure.html b/webapp/polls/templates/poll-structure-form.html
index 853816b..149e58d 100644
--- a/webapp/polls/templates/poll-structure.html
+++ b/webapp/polls/templates/poll-structure-form.html
@@ -1,7 +1,7 @@
{% extends "base-poll.html" %}
{% load i18n poll_tags %}
-{% block title %}Builder{% endblock %}
+{% block title %}Estructura de encuesta{% endblock %}
{% block extra_css %}
<style type="text/css">
@@ -12,11 +12,11 @@
{% endblock %}
{% block main_container %}
- <div style="margin-top: 41px;" class="alert alert-info navbar-fixed-top">Para generar dependencias, arrastré el ID de la opción hacia el campo "Depende de la opción". Las dependencias validas se realizan desde una opción de una pregunta de menor orden hacia una pregunta de mayor orden.</div>
+ <div style="margin-top: 40px;" class="alert alert-info navbar-fixed-top">Para generar dependencias, arrastré el ID de la opción hacia el campo "Depende de la opción". Las dependencias validas se realizan desde una opción de una pregunta de menor orden hacia una pregunta de mayor orden.</div>
- <h2>Encuesta: {{ poll.name }}</h2>
+ <center><h2>{{ poll.name|capfirst }}</h2></center>
- <center><h3>Estructura</h3></center>
+ <h3>Estructura</h3>
{% if errors %}
<div class="control-group error">
@@ -32,6 +32,10 @@
<form class="form-inline" method="post" action="">
+ {% if structure.id %}
+ <input type="hidden" name="id" value="{{ structure.id }}" />
+ {% endif %}
+
{% render_structure structure %}
<div class="ps-form-toolbar btn-toolbar clearfix">
@@ -44,27 +48,4 @@
</form>
-<script type="text/javascript">
- (function($){
- /*$(document).ready(function() {
- $(".field_area").toggle();
- $(".toggle").on('click', function(event) {
- event.preventDefault();
- var group_index = $(this).attr("group_index");
- $("#Group" + group_index).toggle("showOrHide");
-
- // Hide groups that are visible and have no errors
- $("fieldset[id!='Group" + group_index +"']:visible")
- .not(":has('.error')")
- .toggle("slow");
- });
-
- // Keep visible the groups that have errors
- $('fieldset:has(".error"):hidden').toggle("fast");
-
- });
- */
- })(jQuery);
-</script>
-
{% endblock %} \ No newline at end of file
diff --git a/webapp/polls/templates/poll-success.html b/webapp/polls/templates/poll-success.html
new file mode 100644
index 0000000..5d92d17
--- /dev/null
+++ b/webapp/polls/templates/poll-success.html
@@ -0,0 +1,19 @@
+{% extends "base-poll.html" %}
+
+{% block title %}Exito!{% endblock %}
+
+{% block main_container %}
+
+ <div class="row-fuild span12">
+ <form class="form-inline" method="post" action="">{% csrf_token %}
+
+ <div class="ps-form-toolbar btn-toolbar clearfix">
+ <div class="btn-group">
+ <button class="btn btn-primary"><i class="icon-white icon-download-alt"></i>&nbsp;Descargar encuesta</button>
+ </div>
+ </div>
+
+ </form>
+ </div>
+
+{% endblock %} \ No newline at end of file
diff --git a/webapp/polls/templates/sucess.html b/webapp/polls/templates/sucess.html
deleted file mode 100644
index 364b31b..0000000
--- a/webapp/polls/templates/sucess.html
+++ /dev/null
@@ -1,28 +0,0 @@
-{% extends "base-main.html" %}
-
-{% block title %}Success!{% endblock %}
-
-{% block main_container %}
-
- <div class="row-fuild alert alert-success span10">
- La estructura de la encuesta se generó con exito, puede descargarla.
- </div>
-
- <div class="row-fuild span12">
- <form class="form-inline" method="post" action="">
-
- <div class="ps-form-toolbar btn-toolbar clearfix">
- <div class="btn-group">
- <button class="btn btn-primary"><i class="icon-white icon-download-alt"></i>&nbsp;Descargar encuesta</button>
- </div>
- <div class="btn-group">
- <a class="btn btn-warning " href="{% url polls:builder %}"><i class="icon-white icon-wrench"></i>&nbsp;Volver al constructor de estructuras</a>
- </div>
- </div>
-
- {% csrf_token %}
-
- </form>
- </div>
-
-{% endblock %} \ No newline at end of file
diff --git a/webapp/polls/templates/tags/structure.html b/webapp/polls/templates/tags/structure.html
index d9687b4..2a37be2 100644
--- a/webapp/polls/templates/tags/structure.html
+++ b/webapp/polls/templates/tags/structure.html
@@ -46,7 +46,7 @@
<!-- Template: Field -->
<script type="text/x-mustache-template" name="field">
- <div class="row-fluid field well">
+ <div class="row-fluid field well well-small">
<input type="hidden" name="groups.[[ group_order ]].fields.[[ order ]].order" value="[[ order ]]" class="field_order" />
diff --git a/webapp/polls/templatetags/poll_tags.py b/webapp/polls/templatetags/poll_tags.py
index f3ff5ce..ec7f6b6 100644
--- a/webapp/polls/templatetags/poll_tags.py
+++ b/webapp/polls/templatetags/poll_tags.py
@@ -13,7 +13,7 @@ register = template.Library()
@register.simple_tag(takes_context=True)
def render_structure(context, structure):
structure = structure.to_dict(with_errors=True)
- groups = SafeUnicode(json.dumps(structure))
+ groups = SafeUnicode(json.dumps(structure.get("groups", {})))
widget_types = SafeUnicode(json.dumps(
[{'key': k, 'value': v} for k, v in WIDGET_TYPES]))
diff --git a/webapp/polls/tests.py b/webapp/polls/tests.py
index 22002ec..51247ca 100644
--- a/webapp/polls/tests.py
+++ b/webapp/polls/tests.py
@@ -230,7 +230,27 @@ class GroupTests(TestCase):
self.assertEqual(1, len(group.errors))
-class StructureTests(TestCase):
+class StructureTests(MongoTestCase):
+
+ def setUp(self):
+ poll = Poll(data={'name': 'name'})
+ poll_id = poll.save()
+
+ self.poll = Poll.get(id=poll_id)
+
+ self.data = {
+ 'groups': {
+ '0': {
+ 'name': 'group_0',
+ 'fields': {
+ '0': {
+ 'widget_type': 'TextInput',
+ 'name': 'field_0_0'
+ }
+ }
+ }
+ }
+ }
def test_from_dict(self):
data = {
@@ -264,7 +284,7 @@ class StructureTests(TestCase):
}
}
- structure = Structure(data=data)
+ structure = Structure(data=data, poll=self.poll)
group_0 = structure.groups[0]
self.assertEqual('group_0', group_0.name)
@@ -306,7 +326,7 @@ class StructureTests(TestCase):
}
}
- structure = Structure(data=data)
+ structure = Structure(data=data, poll=self.poll)
self.assertFalse(structure.is_valid())
@@ -321,8 +341,27 @@ class StructureTests(TestCase):
def test_invalid_structure(self):
data = {}
- structure = Structure(data=data)
+ structure = Structure(data=data, poll=self.poll)
self.assertFalse(structure.is_valid())
self.assertEqual(1, len(structure.errors))
+
+ def test_save(self):
+
+ structure = Structure(data=self.data)
+
+ self.assertRaises(structure.ValidationError, structure.save)
+
+ structure = Structure(data=self.data, poll=self.poll)
+ structure.save()
+
+ self.assertEqual(1, self.db.structures.count())
+
+ def test_get(self):
+ structure = Structure(data=self.data, poll=self.poll)
+ structure_id = structure.save()
+
+ structure = Structure.get(id=structure_id)
+
+ self.assertEqual(self.poll.id, structure.poll.id)
diff --git a/webapp/polls/urls.py b/webapp/polls/urls.py
index 1657523..b4f1a65 100644
--- a/webapp/polls/urls.py
+++ b/webapp/polls/urls.py
@@ -6,11 +6,15 @@ from polls.views import *
urlpatterns = patterns('',
# Poll
url(r'^$', PollListView.as_view(), name="list"),
- url(r'^add/$', PollAddView.as_view(), name="add"),
+ url(r'^add/$', PollFormView.as_view(), name="add"),
+ url(r'^edit/(?P<id>[0-9A-Fa-f]{24})/$',
+ PollFormView.as_view(), name="edit"),
# Poll structure
url(r'^structure/(?P<poll_id>[0-9A-Fa-f]{24})/$',
StructureFormView.as_view(), name="structure.builder"),
- url(r'^success/(?P<file_name>[a-zA-Z0-9_.-]+)/$',
+ url(r'^success/(?P<poll_id>[0-9A-Fa-f]{24})/$',
SucessView.as_view(), name="success"),
+ url(r'^download/(?P<poll_id>[0-9A-Fa-f]{24})/$',
+ 'polls.views.download_poll', name="download"),
)
diff --git a/webapp/polls/views.py b/webapp/polls/views.py
index 01efa95..18b2eeb 100644
--- a/webapp/polls/views.py
+++ b/webapp/polls/views.py
@@ -1,15 +1,11 @@
# -*- encoding: utf-8 -*-
-import io
-import json
from datetime import datetime
-from django.conf import settings
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.utils.datastructures import DotExpandedDict
from django.utils.safestring import SafeUnicode
from django.http import HttpResponse, HttpResponseRedirect, Http404
-from django.core.servers.basehttp import FileWrapper
from django.core.urlresolvers import reverse
from django.views.generic.edit import FormView
from django.contrib import messages
@@ -22,7 +18,7 @@ from polls.forms import PollAddForm
__all__ = [
- 'StructureFormView', 'SucessView', 'PollAddView', 'PollListView',
+ 'StructureFormView', 'SucessView', 'PollFormView', 'PollListView',
]
@@ -56,11 +52,23 @@ def clean_data(value):
return value
-class PollAddView(FormView):
+class PollFormView(FormView):
- template_name = "poll-add.html"
+ template_name = "poll-form.html"
form_class = PollAddForm
+ def get_context_data(self, **kwargs):
+ context = super(PollFormView, self).get_context_data(**kwargs)
+
+ # If id and Wrong id => 404
+ _id = self.kwargs.get('id', None)
+ poll = Poll.get(id=_id) if _id else None
+ if _id and not poll:
+ raise Http404()
+
+ context.update({"poll": poll})
+ return context
+
def form_valid(self, form):
try:
poll = form.save()
@@ -90,28 +98,35 @@ class PollListView(ListView):
context_object_name = "polls"
def get_queryset(self, *args, **kwargs):
- return get_db().polls.find()
+ return Poll.all()
class StructureFormView(TemplateView):
- template_name = "poll-structure.html"
+ template_name = "poll-structure-form.html"
+
+ def get(self, request, *args, **kwargs):
+ context = self.get_context_data()
+
+ # TODO: Metodo para obtener la estructura a partir de una encuesta
+ structure_data = get_db().structures.find_one(
+ {'poll.$id': self.poll.id})
+ structure_data = structure_data if structure_data else {}
+
+ context.update({'structure': Structure(data=structure_data)})
+
+ return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(StructureFormView, self).get_context_data(**kwargs)
# Wrong id => 404
_id = self.kwargs.get('poll_id', None)
- poll = Poll.get(id=_id)
- if not _id or not poll:
+ self.poll = Poll.get(id=_id)
+ if not _id or not self.poll:
raise Http404()
- context.update({
- 'WIDGET_TYPES': WIDGET_TYPES,
- 'structure': Structure(),
- 'poll': poll,
- })
-
+ context.update({'WIDGET_TYPES': WIDGET_TYPES, 'poll': self.poll})
return context
def post(self, request, *args, **kwargs):
@@ -122,26 +137,24 @@ class StructureFormView(TemplateView):
for key, value in data.items():
data[key] = clean_data(value)
- structure = Structure(data={"groups": data.get('groups', {})})
+ _id = data.get('id', None)
+ structure = Structure(
+ data={"groups": data.get('groups', {}), 'id': _id},
+ poll=self.poll
+ )
if structure.is_valid():
- _json = json.dumps(
- structure.to_dict(),
- sort_keys=True,
- indent=4,
- separators=(',', ': '),
- ensure_ascii=False
- )
- file_name = datetime.now().strftime("%d_%m_%Y_%H_%M_%S")
- file_path = '%soutput/%s.json' % (settings.MEDIA_ROOT, file_name)
-
- # Saving json file
- with io.open(file_path, 'w', encoding='utf-8') as f:
- f.write(unicode(_json))
- f.close()
+ structure.save()
+ messages.add_message(
+ self.request,
+ messages.SUCCESS,
+ u'La estructura de la encuesta "%s" fué'
+ ' guardada correctamente.' % self.poll.name
+ )
return HttpResponseRedirect(
- reverse('polls:success', kwargs={"file_name": file_name}))
+ reverse('polls:success', kwargs={"poll_id": str(self.poll.id)})
+ )
else:
context.update({'errors': structure.errors})
@@ -151,20 +164,27 @@ class StructureFormView(TemplateView):
class SucessView(TemplateView):
- template_name = "sucess.html"
-
- def get(self, request, *args, **kwargs):
- return self.render_to_response(self.get_context_data())
+ template_name = "poll-success.html"
def post(self, request, *args, **kwargs):
- file_name = kwargs.get('file_name', None)
-
- if file_name:
- file_path = '%soutput/%s.json' % (settings.MEDIA_ROOT, file_name)
- # Download json file
- f = file(file_path)
- response = HttpResponse(
- FileWrapper(f), content_type='application/json')
- response['Content-Disposition'] = (
- 'attachment; filename=%s.json' % file_name)
- return response
+ poll_id = kwargs.get('poll_id', None)
+
+ return download_poll(request, poll_id)
+
+
+def download_poll(request, poll_id=None):
+
+ # Wrong id => 404
+ _id = poll_id
+ poll = Poll.get(id=_id)
+ if not _id or not poll:
+ raise Http404()
+
+ file_name = datetime.now().strftime("%d_%m_%Y_%H_%M_%S")
+
+ # Download json file
+ response = HttpResponse(
+ poll.to_json(), content_type='application/json')
+ response['Content-Disposition'] = (
+ 'attachment; filename=%s.json' % file_name)
+ return response
diff --git a/webapp/webapp/media/output/empty b/webapp/webapp/media/output/empty
deleted file mode 100644
index e69de29..0000000
--- a/webapp/webapp/media/output/empty
+++ /dev/null
diff --git a/webapp/webapp/settings.py b/webapp/webapp/settings.py
index 88f43e4..aac92a8 100644
--- a/webapp/webapp/settings.py
+++ b/webapp/webapp/settings.py
@@ -102,6 +102,14 @@ MIDDLEWARE_CLASSES = (
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
+TEMPLATE_CONTEXT_PROCESSORS = (
+ 'django.core.context_processors.media',
+ 'django.core.context_processors.static',
+ #'django.contrib.auth.context_processors.auth',
+ 'django.contrib.messages.context_processors.messages',
+ 'django.core.context_processors.request',
+)
+
ROOT_URLCONF = 'webapp.urls'
# Python dotted path to the WSGI application used by Django's runserver.
diff --git a/webapp/webapp/templates/base-main.html b/webapp/webapp/templates/base-main.html
index 034d0dc..8574575 100644
--- a/webapp/webapp/templates/base-main.html
+++ b/webapp/webapp/templates/base-main.html
@@ -47,16 +47,15 @@
<a class="brand" href="#">Sitema de encuestas</a>
<div class="nav-collapse collapse">
<ul class="nav">
- <li class="">
- <a href="{% url polls:list %}"><i class="icon-white icon-list-alt"></i>&nbsp;Listado de encuestas</a>
- </li>
- <li class="">
- <a href="{% url polls:add %}"><i class="icon-white icon-plus"></i>&nbsp;Nueva encuesta</a>
+
+ {% url polls:list as polls_list_url %}
+ <li class="{% if request.path == polls_list_url %}active{% endif %}">
+ <a href="{{ polls_list_url }}"><i class="icon-white icon-list-alt"></i>&nbsp;Listado de encuestas</a>
</li>
- </ul>
- <ul class="pull-right">
- <li class="">
- <a id="lista_encuestas" class="btn btn-warning" href="{{ MEDIA_URL }}output" target="_blank" data-original-title="Directorio de archivos"><i class="icon-white icon-list-alt"></i></a>
+
+ {% url polls:add as polls_add_url %}
+ <li class="{% if request.path == polls_add_url %}active{% endif %}">
+ <a href="{{ polls_add_url }}"><i class="icon-white icon-plus"></i>&nbsp;Nueva encuesta</a>
</li>
</ul>
</div>
diff --git a/webapp/webapp/urls.py b/webapp/webapp/urls.py
index d46ccc2..9a26880 100644
--- a/webapp/webapp/urls.py
+++ b/webapp/webapp/urls.py
@@ -5,7 +5,7 @@ from django.conf import settings
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace="polls")),
- url(r'^$', RedirectView.as_view(url='polls/builder/'))
+ url(r'^$', RedirectView.as_view(url='polls/'))
)
if settings.DEBUG: