Add form to modify user email.
authorAlexandre Segura <mex.zktk@gmail.com>
Wed, 15 Mar 2017 16:49:22 +0100
changeset 435 26338fe87deb
parent 434 924d95c07149
child 436 60d98f985e3b
Add form to modify user email.
src/iconolab/auth/forms.py
src/iconolab/templates/iconolab/user_home.html
src/iconolab/views/userpages.py
--- a/src/iconolab/auth/forms.py	Tue Mar 14 17:40:02 2017 +0100
+++ b/src/iconolab/auth/forms.py	Wed Mar 15 16:49:22 2017 +0100
@@ -0,0 +1,9 @@
+from django import forms
+from django.contrib.auth.models import User
+
+class UserForm(forms.ModelForm):
+    email = forms.EmailField(required=False)
+
+    class Meta:
+        model = User
+        fields = ('email',)
--- a/src/iconolab/templates/iconolab/user_home.html	Tue Mar 14 17:40:02 2017 +0100
+++ b/src/iconolab/templates/iconolab/user_home.html	Wed Mar 15 16:49:22 2017 +0100
@@ -9,9 +9,32 @@
 {% load notifications_tags %}
 
 {% block content %}
+  <div class="page-header">
+    <h1>{% if profile_user == request.user %}Mon espace:{% else %}Profil : {% endif %} {{profile_user.username}}</h1>
+  </div>
+  {% if profile_user == request.user %}
+  <div class="row">
+    <div class="col-md-12">
+      <h2>Coordonnées</h2>
+      <form method="post">
+        {% csrf_token %}
+        <fieldset class="form-group {% if user_form.email.errors %}has-error{% endif %}">
+          <label class="control-label" for="id_{{ user_form.email.name }}">Email</label>
+          <input type="text" class="form-control"
+            name="{{ user_form.email.name }}"
+            id="id_{{ user_form.email.name }}" value="{% if user_form.email.value %}{{ user_form.email.value }}{% endif %}">
+          {% if user_form.email.errors %}
+          <span class="help-block">{{ user_form.email.errors | striptags }}</span>
+          {% endif %}
+        </fieldset>
+        <button type="submit" class="btn btn-block btn-primary">Valider</button>
+      </form>
+    </div>
+  </div>
+  {% endif %}
   <div class="row">
     <div class="col-md-12 user-profile-block" >
-      <h3>{% if profile_user == request.user %}Mon espace:{% else %}Profil : {% endif %} {{profile_user.username}}</h3>
+      <h2>Notifications</h2>
       <div>
         {% if profile_user == request.user %}
         {% notifications_unread as unread_count %}
--- a/src/iconolab/views/userpages.py	Tue Mar 14 17:40:02 2017 +0100
+++ b/src/iconolab/views/userpages.py	Wed Mar 15 16:49:22 2017 +0100
@@ -10,6 +10,7 @@
 from django.urls import reverse
 from notifications.models import Notification
 from iconolab.models import Collection, Annotation, IconolabComment, Image, MetaCategoriesCountInfo
+from iconolab.auth.forms import UserForm
 from uuid import UUID
 import logging
 
@@ -17,7 +18,7 @@
 
 class UserHomeView(DetailView):
     """
-        Homepage for user account, displays latest unread notifications, latest annotations created recap, latest contributions on annotations recap, 
+        Homepage for user account, displays latest unread notifications, latest annotations created recap, latest contributions on annotations recap,
         latest annotations commented recap, also provides access to admin interface.
     """
     model = User
@@ -25,11 +26,6 @@
 
     def get_context_data(self, **kwargs):
         context = super(UserHomeView, self).get_context_data(**kwargs)
-        return context
-
-    def get(self, request, *args, **kwargs):
-        self.object = self.get_object()
-        context = self.get_context_data()
         profile_user = self.object
         context['profile_user'] = profile_user
         context['user_annotations'] = Annotation.objects.filter(author=profile_user).prefetch_related(
@@ -42,13 +38,35 @@
         context['user_contributed_annotations'] = Annotation.objects.get_annotations_contributed_for_user(profile_user)[:5]
         context['user_commented_annotations'] = Annotation.objects.get_annotations_commented_for_user(profile_user)[:5]
         # .exclude(annotation_guid__in=[annotation.annotation_guid for annotation in context['user_revisions_annotations']])
-        
+
+        return context
+
+    def get(self, request, *args, **kwargs):
+        self.object = self.get_object()
+        context = self.get_context_data()
+        context['user_form'] = UserForm(instance=request.user)
+
         if request.user.is_authenticated() and self.object == request.user:
             if request.GET.get('clear_notifications', False):
                 Notification.objects.filter(recipient=request.user).mark_all_as_read()
             logger.debug(Notification.objects.filter(recipient=request.user))
             context['notifications'] = Notification.objects.filter(recipient=request.user)
-        logger.debug(context)
+
+        return render(request, 'iconolab/user_home.html', context)
+
+    def post(self, request, *args, **kwargs):
+        self.object = self.get_object()
+        context = self.get_context_data()
+
+        user_form = UserForm(data=request.POST, instance=request.user)
+        context['user_form'] = user_form
+
+        if request.user.is_authenticated() and self.object == request.user:
+            if user_form.is_valid():
+                user = user_form.save(commit=False)
+                user.save()
+                return redirect(reverse('user_home', kwargs={'slug': user.id}))
+
         return render(request, 'iconolab/user_home.html', context)
 
 class UserNotificationsView(View):
@@ -76,11 +94,11 @@
     """
     model = User
     slug_field = 'id'
-    
+
     def get_context_data(self, **kwargs):
         context = super(UserAnnotationsView, self).get_context_data(**kwargs)
         return context
-    
+
     def get(self, request, *args, **kwargs):
         self.object = self.get_object()
         profile_user = self.object
@@ -103,18 +121,18 @@
         context['user_annotations'] = annotations_list
         context['profile_user'] = profile_user
         return render(request, 'iconolab/user_annotations.html', context)
-    
+
 class UserCommentedView(DetailView):
     """
         View that displays the full paginated list of annotations on which the considered user has commented
     """
     model = User
     slug_field = 'id'
-    
+
     def get_context_data(self, **kwargs):
         context = super(UserCommentedView, self).get_context_data(**kwargs)
         return context
-    
+
     def get(self, request, *args, **kwargs):
         self.object = self.get_object()
         profile_user = self.object
@@ -138,11 +156,11 @@
     """
     model = User
     slug_field = 'id'
-    
+
     def get_context_data(self, **kwargs):
         context = super(UserContributedView, self).get_context_data(**kwargs)
         return context
-    
+
     def get(self, request, *args, **kwargs):
         self.object = self.get_object()
         profile_user = self.object
@@ -166,25 +184,25 @@
     """
     model = User
     slug_field = 'id'
-    
+
     def get_context_data(self, **kwargs):
         context = super(UserCollectionAdminView, self).get_context_data(**kwargs)
         return context
-    
+
     def get(self, request, *args, **kwargs):
         self.object = self.get_object()
         profile_user = self.object
         context = self.get_context_data()
-        collection_name = kwargs.get("collection_name") 
+        collection_name = kwargs.get("collection_name")
         collection_qs = Collection.objects.filter(name=collection_name)
         if not request.user.is_staff and not request.user.is_authenticated or profile_user != request.user or not collection_qs.exists():
             return redirect(reverse_lazy('user_home', kwargs={'slug': profile_user.id}))
         collection = collection_qs.first()
         if collection not in profile_user.profile.managed_collections.all():
             return redirect(reverse_lazy('user_home', kwargs={'slug': profile_user.id}))
-        
+
         annotation_queryset = Annotation.objects.distinct().filter(image__item__collection=collection).prefetch_related('current_revision', 'stats', 'image', 'image__item')
-        
+
         # filtering
         comments_count_filter = request.GET.get("min_comments", "")
         if comments_count_filter and comments_count_filter.isdigit():
@@ -206,7 +224,7 @@
             min_accuracy = min(int(accuracy_filter), 5)
             context["qarg_min_accuracy"] = min_accuracy
             annotation_queryset = annotation_queryset.filter(current_revision__tagginginfo__accuracy__gte=min_accuracy)
-        
+
         metacategories_filter = []
         mtcg_annotations_ids = {}
         filtering_on_metacategories = False
@@ -215,7 +233,7 @@
             # Default filter is 0
             mtcg_filter = request.GET.get("min_metacategory_"+str(metacategory.id), "0")
             # We ignore filters that aren't integers
-            if mtcg_filter and mtcg_filter.isdigit(): 
+            if mtcg_filter and mtcg_filter.isdigit():
                 # For each metacategory we have a dict entry with key=id that will be a list of the annotation matching the filter
                 mtcg_annotations_ids[str(metacategory.id)] = []
                 # Queryarg for autocompleting the form on page load
@@ -234,15 +252,15 @@
                     ])
                 )
             )
-        
+
         # ordering
         ordering = []
         orderby_map = {
             "oldest": "created",
             "recent": "-created",
-            "most_commented": "-stats__comments_count", 
-            "most_tagged": "-stats__tag_count", 
-            "most_revised": "-stats__submitted_revisions_count", 
+            "most_commented": "-stats__comments_count",
+            "most_tagged": "-stats__tag_count",
+            "most_revised": "-stats__submitted_revisions_count",
             "most_viewed": "-stats__views_count"
         }
         for ordering_qarg in ["first", "second", "third", "fourth"]:
@@ -254,4 +272,4 @@
         context["collection"] = collection
         logger.debug(ordering)
         logger.debug(annotation_queryset)
-        return render(request, 'iconolab/user_collection_admin.html', context)
\ No newline at end of file
+        return render(request, 'iconolab/user_collection_admin.html', context)