src/hdalab/views/profile.py
changeset 649 434737bd64e5
parent 640 939461cc322b
child 675 d68e7b3a2e4f
--- a/src/hdalab/views/profile.py	Thu Sep 24 13:40:54 2015 +0200
+++ b/src/hdalab/views/profile.py	Sat Sep 26 11:55:11 2015 +0200
@@ -48,12 +48,12 @@
 
 
 class BaseRenkanList(TemplateView):
-    
+
     default_sort_field = "date"
     default_sort_order = "desc"
 
     def update_context(self, context, renkan_queryset):
-        
+
         filters = ""
         filter_title = self.request.GET.get("title", "")
         if(len(filter_title)>0):
@@ -105,32 +105,32 @@
             page = p.page(1)
         except EmptyPage:
             page = p.page(p.num_pages)
-        
-        context.update({"page": page, "sort_param":sort_param, "order_param":order_param, "opposite":opposite, 
+
+        context.update({"page": page, "sort_param":sort_param, "order_param":order_param, "opposite":opposite,
                         "filters":filters, "title": filter_title, "username": filter_username, "state": filter_state,
                         "startdate":filter_startdate, "enddate":filter_enddate, "favorite": filter_favorite})
-        
+
         return context
 
 
 
 class ProfileHome(BaseRenkanList):
-    
+
     template_name = "profile_home.html"
-    
+
     def get_context_data(self, **kwargs):
         return self.update_context( super(ProfileHome, self).get_context_data(**kwargs), HdalabRenkan.objects.select_related("renkan").filter(renkan__owner=self.request.user))
 
 
 class RenkanPublicList(BaseRenkanList):
-    
+
     template_name = "renkan_list.html"
-    
+
     def get_context_data(self, **kwargs):
         context = super(RenkanPublicList, self).get_context_data(**kwargs)
         #Liste des renkans publics
         renkan_list = HdalabRenkan.objects
-        
+
         context['hide_favorite'] = True
         context['show_username'] = self.request.user.is_staff
         if self.request.user.is_staff:
@@ -142,13 +142,13 @@
 
 
 class RenkanFavoriteList(BaseRenkanList):
-    
+
     template_name = "renkan_list_favorite.html"
-    
+
     def get_context_data(self, **kwargs):
         context = super(RenkanFavoriteList, self).get_context_data(**kwargs)
         renkan_list = HdalabRenkan.objects
-        
+
         context['hide_favorite'] = True
         context['show_username'] = self.request.user.is_staff
         if self.request.user.is_staff:
@@ -160,7 +160,7 @@
 
 
 class RenkanNew(TemplateView):
-    
+
     template_name="renkan_new_confirm.html"
 
     def post(self, request):
@@ -169,7 +169,8 @@
         rk.rk_id = rk_id
         rk.owner = request.user
         rk.content = '{}'
-        rk.title = "Nouveau Renkan "
+        rk.title = "Nouveau Renkan"
+        rk.schema_version = "2"
         rk.save()
         hr = HdalabRenkan()
         hr.renkan = rk
@@ -179,9 +180,9 @@
 
 
 class RenkanEdit(TemplateView):
-    
+
     template_name="renkan_edit.html"
-    
+
     def get_context_data(self, **kwargs):
         switch_shape_url= {}
         context = super(RenkanEdit, self).get_context_data(**kwargs)
@@ -210,32 +211,32 @@
             context["switch_shape_url"] = switch_shape_url
         form = AuthenticationForm(self.request)
         context["form"] = form
-        
+
         return context
 
 
 
 class HdalabRenkanGetPut(RenkanGetPut):
-    
+
     @csrf_exempt
     def dispatch(self, *args, **kwargs):
         return super(HdalabRenkanGetPut, self).dispatch(*args, **kwargs)
-    
+
     def get(self, request):
-        
+
         # If a renkan id is set
         rk_id = request.GET.get("rk_id", "")
         if rk_id!="":
             rk = get_object_or_404(Renkan, rk_id=rk_id)
             return HttpResponse(rk.content, content_type="application/json")
-        
+
         shape = request.GET.get("shape", "")
         no_translate_langs = [ 'fr' ]
         lang = request.GET.get('lang',request.LANGUAGE_CODE)
-        
+
         # Start dict for renkan json
         now = datetime.now().strftime("%Y-%m-%d %H:%M")
-        
+
         content = {
           "id": unicode(uuid.uuid1()),
           "schema_version": 2,
@@ -248,22 +249,22 @@
           "views": [],
           "users": [],
         }
-        
+
         # category image dict
         cat_dict = {u"Créateur": static("hdalab/img/category_creator.png"),
                     u"Datation": static("hdalab/img/category_datation.png"),
                     u"Discipline artistique": static("hdalab/img/category_discipline.png"),
                     u"Localisation": static("hdalab/img/category_localisation.png"),
                     u"Ecole/Mouvement": static("hdalab/img/category_movement.png")}
-        
+
         # category image dict
         shapes = { "tag1": "polygon", "notice": "rectangle", "tag2": "star" }
-        
-        
+
+
         # Renkan Project ID
         project_id = unicode(uuid.uuid1())
-        
-        
+
+
         # If a notice id is set
         notice_id = request.GET.get("notice", "")
         if notice_id!="":
@@ -276,7 +277,7 @@
                 np = HorLineNodePlacer()
             elif shape=="vert":
                 np = LineNodePlacer()
-                
+
             np.init({"datasheet": (1, 1), "tags": (2, len(ordered_tags))})
             # Place notice :
             content["nodes"].append({
@@ -294,13 +295,13 @@
                 "shape": shapes["notice"]
             })
             notice_id = content["nodes"][0]["id"]
-            
+
             # Get translated labels
             translations = {}
             if lang not in no_translate_langs:
                 transqs = DbpediaFieldsTranslation.objects.filter(master__in = [ot.tag.dbpedia_fields if hasattr(ot.tag, 'dbpedia_fields') and ot.tag.dbpedia_fields else None for ot in ordered_tags], language_code = lang)
                 translations = dict([(trans.master_id,trans) for trans in transqs])
-            
+
             for ot in ordered_tags:
                 t = ot.tag
                 img_url = t.dbpedia_fields.thumbnail if hasattr(t, 'dbpedia_fields') and t.dbpedia_fields and t.dbpedia_fields.thumbnail else None
@@ -325,7 +326,7 @@
                   },
                   "shape": shapes["tag2"]
                 })
-                
+
             # Place edges
             for node in content["nodes"]:
                 content["edges"].append({
@@ -340,11 +341,11 @@
                     "to": node["id"],
                     "project_id": project_id,
                 })
-            
+
             response = json.dumps(content)
             return HttpResponse(response, content_type="application/json")
-        
-        
+
+
         # If a folder id is set
         folder_id = request.GET.get("folder", "")
         if folder_id!="":
@@ -363,23 +364,23 @@
                     n_tags.append(t)
             n_tags = [t.pk for t in n_tags]
             all_tags = Tag.objects.filter( pk__in=n_tags ).select_related("dbpedia_fields", "category")
-            
+
             # Get translated labels
             translations = {}
             if lang not in no_translate_langs:
                 transqs = DbpediaFieldsTranslation.objects.filter(master__in = [t.dbpedia_fields if hasattr(t, 'dbpedia_fields') and t.dbpedia_fields else None for t in all_tags], language_code = lang)
                 translations = dict([(trans.master_id,trans) for trans in transqs])
-            
+
             # Prepare Node placer :
             np = CircleNodePlacer()
             if shape=="horiz":
                 np = HorLineNodePlacer()
             elif shape=="vert":
                 np = LineNodePlacer()
-                
+
             np.init({"datasheet": (1, len(notices)), "tags": (2, len(all_tags))})
 
-            
+
             # Place notices
             for n in notices:
                 content["nodes"].append({
@@ -396,7 +397,7 @@
                   },
                   "shape": shapes["notice"]
                 })
-            
+
             # Place tags
             for t in all_tags:
                 img_url = t.dbpedia_fields.thumbnail if hasattr(t, 'dbpedia_fields') and t.dbpedia_fields and t.dbpedia_fields.thumbnail else None
@@ -422,7 +423,7 @@
                     },
                     "shape": shapes["tag2"]
                 })
-            
+
             # Place edges
             for n_pk in notice_tag_dict:
                 for tag_id in notice_tag_dict[n_pk]["tags"]:
@@ -439,11 +440,11 @@
                         "project_id": project_id,
                         #"created_by": "de68xf75y6hs5rgjhgghxbm217xk"
                     })
-            
+
             response = json.dumps(content)
             return HttpResponse(response, content_type="application/json")
-            
-        
+
+
         # Otherwise we build the datas
         # Get tags and countries
         labels = request.GET.get("label", "").split(",")
@@ -453,12 +454,12 @@
         label_list = [t for t in labels if t!=""]
         country_list = [c for c in countries if c!=""]
         all_tags = Tag.objects.filter( Q(label__in=label_list) | Q(dbpedia_uri__in=country_list) ).select_related("dbpedia_fields", "category")
-        
+
         # Get datasheets from ajax filter search
         temp_fitler = filter_generic(lang, period, ",".join(label_list), ",".join(country_list), content_count=18)
         filter_output = json.loads(temp_fitler)
         filter_output_to_bin = json.loads(temp_fitler)
-        
+
         #Keep only the 8 first ressources to create the graph
         #the 10 next are sent to the bins
         for i in range(len(filter_output["contents"])):
@@ -472,7 +473,7 @@
           "title": _("Plus de Ressources"), #TODO: Translate
           "list": filter_output_to_bin["contents"]
         }
-        
+
         # Prepare other tags
         related_tags = []
         all_labels = [t.label for t in all_tags]
@@ -493,8 +494,8 @@
                     related_tags.append({"label": t["label"], "thumbnail":thumbnail_url, "id":t["id"], "url":t["url"], 'wkpd_url': t['wkpd_url']})
                     all_labels.append(t["label"])
                 related_tags_dict[c["id"]].append(t["id"])
-        
-        
+
+
         # If possible, we search a dbpedia_fields thumbnail or category thumbnail for related tags
         r_tags = [t["label"] for t in related_tags if t["thumbnail"] is None or t["thumbnail"]=="" ]
         r_tags = Tag.objects.filter( label__in=r_tags ).select_related("dbpedia_fields", "category")
@@ -509,28 +510,28 @@
         for t in related_tags:
             if (t["thumbnail"] is None or t["thumbnail"]=="") and (t["label"] in r_tags_dict):
                 t["thumbnail"] = r_tags_dict[t["label"]]
-        
-        
+
+
         # Prepare Node placer :
         np = CircleNodePlacer()
         if shape=="horiz":
             np = HorLineNodePlacer()
         elif shape=="vert":
             np = LineNodePlacer()
-            
+
         len_tags = len(all_tags)
         if period:
             len_tags += 1
         np.init({"tags": (1, len_tags), "datasheet": (2, len(filter_output["contents"])), "related": (3, len(related_tags)), "northwest":(3 if shape=="circle" else 1, 1)})
-        
+
         #get tag abstract and label translations
-        
+
         tags_id = [t.id for t in all_tags] + [t['id'] for t in related_tags]
         translations = {}
         transqs = DbpediaFieldsTranslation.objects.filter(master__tag__in = tags_id, language_code = lang)
         translations = dict([(trans.master.tag.id,trans) for trans in transqs])
 
-        
+
         for t in all_tags:
             img_url = t.dbpedia_fields.thumbnail if hasattr(t, 'dbpedia_fields') and t.dbpedia_fields and t.dbpedia_fields.thumbnail else None
             if img_url is None and t.category is not None:
@@ -540,7 +541,7 @@
                 'label': filter_output["tagtranslations"][t.label] if t.label in filter_output["tagtranslations"] else t.label,
                 'abstract': translation_obj.abstract if translation_obj else ""
             }
-            
+
             content["nodes"].append({
               "id": unicode(uuid.uuid1()),
               "title": translation['label'],
@@ -570,7 +571,7 @@
               },
               "shape": shapes["tag1"]
             })
-        
+
         for c in filter_output["contents"]:
             content["nodes"].append({
               "id": c["id"],
@@ -586,7 +587,7 @@
               },
               "shape": shapes["notice"]
             })
-        
+
         for t in related_tags:
             translation_obj = translations.get(t['id'], None)
             translation = {
@@ -608,7 +609,7 @@
               },
               "shape": shapes["tag2"]
             })
-        
+
         for c_id in related_tags_dict:
             for tag_id in related_tags_dict[c_id]:
                 content["edges"].append({
@@ -624,14 +625,14 @@
                     "project_id": project_id,
                     #"created_by": "de68xf75y6hs5rgjhgghxbm217xk"
                 })
-        
+
         response = json.dumps(content)
-        
+
         return HttpResponse(response, content_type="application/json")
-    
-    
+
+
     def post(self, request):
-        
+
         rk_id = request.GET.get("rk_id", "")
         #data = json.loads(request.body)
         #logger.debug(data["edges"])
@@ -666,14 +667,14 @@
                     hr.state = HdalabRenkan.EDITION
                     hr.save()
                     return HttpResponse("rk_id=" + rk_id)
-         
-            
+
+
         return HttpResponse("NOT SAVED")
 
 
 
 class HdalabRenkanCopy(View):
-    
+
     def post(self, request, rk_id):
         rk = renkan_copier(request.user, rk_id)
         hr = HdalabRenkan()
@@ -686,7 +687,7 @@
 
 
 class HdalabRenkanDelete(View):
-    
+
     def post(self, request, rk_id):
         try:
             hr = HdalabRenkan.objects.get(renkan__rk_id=rk_id)
@@ -700,7 +701,7 @@
 
 
 class HdalabRenkanModerate(View):
-    
+
     def post(self, request, rk_id):
         form = HdalabRenkanStateForm(request.POST)
         if form.is_valid():
@@ -717,7 +718,7 @@
             return HttpResponseBadRequest("State form invalid")
 
 class HdalabRenkanFavorite(View):
-    
+
     def post(self, request, rk_id):
         form = HdalabRenkanFavoriteForm(request.POST)
         if form.is_valid():
@@ -736,10 +737,10 @@
 
     def get_object(self, queryset=None):
         return self.request.user
-    
+
     def get_success_url(self):
         return reverse('profile_home')
-    
+
 
 # Function copied from django.contrib.auth.views to simplify ajax login
 @sensitive_post_parameters()