Commit 8e3eb1e2 authored by Skia's avatar Skia

Some templating and add webcam support for profile editing

parent 4cbfd586
Pipeline #134 failed with stage
in 2 minutes and 49 seconds
This diff is collapsed.
......@@ -96,6 +96,7 @@ $('.select_date').datepicker({
}).datepicker( $.datepicker.regional[ "{{ request.LANGUAGE_CODE }}"] );
$(document).keydown(function (e) {
if ($(e.target).is('input')) { return }
if ($(e.target).is('textarea')) { return }
if (e.keyCode == 83) {
$("#search").focus();
return false;
......
......@@ -10,9 +10,21 @@
{% csrf_token %}
{% for field in form %}
<p>{{ field.errors }}<label for="{{ field.name }}">{{ field.label }}
{%- if field.name == "profile_pict" and form.instance.profile_pict -%}
{%- if field.name == "profile_pict" -%}
<br>{% trans %}Current profile: {% endtrans %}
{% if form.instance.profile_pict %}
<img src="{{ form.instance.profile_pict.get_download_url() }}" title="{% trans %}Profile{% endtrans %}" /><br>
{% if user.is_in_group(settings.SITH_MAIN_BOARD_GROUP) %}
<a href="{{ url('core:file_delete', file_id=form.instance.profile_pict.id, popup="") }}">{% trans %}Delete{% endtrans %}</a>
{% endif %}
{% else %}
<img src="{{ static('core/img/unknown.jpg') }}" title="-" crossOrigin="Anonymous" id="new_profile"/><br>
<div id="take_picture">
<div id="camera_canvas" style="width:320; height:240; margin: 0px auto;"></div>
<a href="javascript:void(take_snapshot())">{% trans %}Take picture{% endtrans %}</a>
</div>
<p>
{% endif %}<br>
{%- elif field.name == "avatar_pict" and form.instance.avatar_pict -%}
<br>{% trans %}Current avatar: {% endtrans %}
<img src="{{ form.instance.avatar_pict.get_download_url() }}" title="{% trans %}Avatar{% endtrans %}" /><br>
......@@ -34,6 +46,39 @@
</form>
{% endblock %}
{% block script %}
{{ super() }}
{% if not form.instance.profile_pict %}
<script src="{{ static('core/js/webcam.js') }}"></script>
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
dest_width: 320,
dest_height: 240,
image_format: 'jpeg',
jpeg_quality: 90,
force_flash: false
});
Webcam.attach( '#camera_canvas' );
function take_snapshot() {
var data_uri = Webcam.snap();
var url = "{{ url('core:user_profile_upload', user_id=form.instance.id) }}";
Webcam.upload( data_uri, url, function(code, text) {
if (code == 200) {
$('#new_profile').attr('src', data_uri);
$('#take_picture').remove();
$('#id_profile_pict').remove();
} else {
console.log("Unknown error: ");
console.log(text);
}
}, "new_profile_pict", {name: 'csrfmiddlewaretoken', value: '{{ csrf_token }}'});
}
</script>
{% endif %}
{% endblock %}
......@@ -31,6 +31,7 @@ urlpatterns = [
url(r'^user/(?P<user_id>[0-9]+)/mini$', UserMiniView.as_view(), name='user_profile_mini'),
url(r'^user/(?P<user_id>[0-9]+)/$', UserView.as_view(), name='user_profile'),
url(r'^user/(?P<user_id>[0-9]+)/edit$', UserUpdateProfileView.as_view(), name='user_edit'),
url(r'^user/(?P<user_id>[0-9]+)/profile_upload$', UserUploadProfilePictView.as_view(), name='user_profile_upload'),
url(r'^user/(?P<user_id>[0-9]+)/groups$', UserUpdateGroupView.as_view(), name='user_groups'),
url(r'^user/tools/$', UserToolsView.as_view(), name='user_tools'),
url(r'^user/(?P<user_id>[0-9]+)/account$', UserAccountView.as_view(), name='user_account'),
......
# Image utils
from io import BytesIO
from PIL import Image
def scale_dimension(width, height, long_edge):
if width > height:
ratio = long_edge * 1. / width
else:
ratio = long_edge * 1. / height
return int(width * ratio), int(height * ratio)
def resize_image(im, edge, format): # TODO move that into a utils file
from django.core.files.base import ContentFile
(w, h) = im.size
(width, height) = scale_dimension(w, h, long_edge=edge)
content = BytesIO()
im.resize((width, height), Image.ANTIALIAS).save(fp=content, format=format, dpi=[72, 72])
return ContentFile(content.getvalue())
......@@ -83,26 +83,10 @@ class RegisteringForm(UserCreationForm):
user.save()
return user
# Image utils
from core.utils import resize_image
from io import BytesIO
from PIL import Image
def scale_dimension(width, height, long_edge):
if width > height:
ratio = long_edge * 1. / width
else:
ratio = long_edge * 1. / height
return int(width * ratio), int(height * ratio)
def resize_image(im, edge, format):
from django.core.files.base import ContentFile
(w, h) = im.size
(width, height) = scale_dimension(w, h, long_edge=edge)
content = BytesIO()
im.resize((width, height), Image.ANTIALIAS).save(fp=content, format=format, dpi=[72, 72])
return ContentFile(content.getvalue())
class UserProfileForm(forms.ModelForm):
"""
Form handling the user profile, managing the files
......
# This file contains all the views that concern the user model
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import logout as auth_logout, views
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist, ValidationError
from django.http import Http404
from django.views.generic.edit import UpdateView
from django.views.generic import ListView, DetailView, TemplateView
......@@ -16,7 +17,7 @@ import logging
from core.views import CanViewMixin, CanEditMixin, CanEditPropMixin
from core.views.forms import RegisteringForm, UserPropForm, UserProfileForm
from core.models import User
from core.models import User, SithFile
def login(request):
"""
......@@ -160,6 +161,35 @@ class UserListView(ListView):
model = User
template_name = "core/user_list.jinja"
class UserUploadProfilePictView(CanEditMixin, DetailView):
"""
Handle the upload of the profile picture taken with webcam in navigator
"""
model = User
pk_url_kwarg = "user_id"
template_name = "core/user_edit.jinja"
def post(self, request, *args, **kwargs):
from core.utils import resize_image
from io import BytesIO
from PIL import Image
self.object = self.get_object()
if self.object.profile_pict:
raise ValidationError(_("User already has a profile picture"))
print(request.FILES['new_profile_pict'])
f = request.FILES['new_profile_pict']
parent = SithFile.objects.filter(parent=None, name="profiles").first()
name = str(self.object.id) + "_profile.jpg" # Webcamejs uploads JPGs
im = Image.open(BytesIO(f.read()))
new_file = SithFile(parent=parent, name=name,
file=resize_image(im, 400, f.content_type.split('/')[-1]),
owner=self.object, is_folder=False, mime_type=f.content_type, size=f._size)
new_file.file.name = name
new_file.save()
self.object.profile_pict = new_file
self.object.save()
return redirect("core:user_edit", user_id=self.object.id)
class UserUpdateProfileView(CanEditMixin, UpdateView):
"""
Edit a user's profile
......
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('counter', '0019_auto_20160820_2053'),
]
operations = [
migrations.AlterField(
model_name='product',
name='buying_groups',
field=models.ManyToManyField(to='core.Group', related_name='products', verbose_name='buying groups'),
),
]
......@@ -86,10 +86,17 @@
{% endif %}
</div>
<div id="products">
<ul>
{% for t in categories -%}
{%- if counter.products.filter(product_type=t).exists() -%}
<li><a href="#cat_{{ t|slugify }}">{{ t }}</a></li>
{%- endif -%}
{%- endfor %}
</ul>
{% for t in categories -%}
{%- if counter.products.filter(product_type=t).exists() -%}
<h5>{{ t }}</h5>
<div id="cat_{{ t }}">
<div id="cat_{{ t|slugify }}">
<h5>{{ t }}</h5>
{% for p in counter.products.filter(product_type=t).all() -%}
{% set file = None %}
{% if p.icon %}
......@@ -148,9 +155,7 @@ $( function() {
$("#bar_ui").accordion({
heightStyle: "content",
});
$("#products").accordion({
heightStyle: "content",
});
$("#products").tabs();
});
</script>
{% endblock %}
......
......@@ -375,15 +375,10 @@ def migrate_refillings():
""")
root_cust = Customer.objects.filter(user__id=0).first()
mde = Counter.objects.filter(id=1).first()
threshold_date = datetime.datetime(year=2006, month=3, day=21, hour=22, minute=17)
Refilling.objects.filter(payment_method="CASH").delete()
Refilling.objects.filter(payment_method="CHECK").delete()
Refilling.objects.filter(date__lte=threshold_date.replace(tzinfo=timezone('Europe/Paris'))).delete()
print("Sith account refillings deleted")
Refilling.objects.all().delete()
print("Refillings deleted")
fail = 100
for r in cur:
if r['type_paiement_rech'] == 2 and r['date_rech'] > threshold_date:
continue # There are no invoices before threshold_date when paid with credit card
try:
cust = Customer.objects.filter(user__id=r['id_utilisateur']).first()
user = User.objects.filter(id=r['id_utilisateur']).first()
......@@ -607,24 +602,24 @@ def migrate_permanencies():
cur.close()
def main():
migrate_users()
migrate_profile_pict()
migrate_clubs()
migrate_club_memberships()
migrate_subscriptions()
update_customer_account()
migrate_counters()
migrate_permanencies()
migrate_typeproducts()
migrate_products()
migrate_product_pict()
migrate_products_to_counter()
reset_customer_amount()
migrate_refillings()
reset_index('counter')
migrate_invoices()
migrate_sellings()
reset_index('core', 'club', 'subscription', 'accounting', 'eboutic', 'launderette', 'counter')
# migrate_users()
# migrate_profile_pict()
# migrate_clubs()
# migrate_club_memberships()
# migrate_subscriptions()
# update_customer_account()
# migrate_counters()
# migrate_permanencies()
# migrate_typeproducts()
# migrate_products()
# migrate_product_pict()
# migrate_products_to_counter()
# reset_customer_amount()
# migrate_invoices()
# migrate_refillings()
# migrate_sellings()
reset_index('core')
# reset_index('core', 'club', 'subscription', 'accounting', 'eboutic', 'launderette', 'counter')
if __name__ == "__main__":
main()
......@@ -58,7 +58,7 @@ class Subscription(models.Model):
self.member.make_home()
def get_absolute_url(self):
return reverse('core:user_profile', kwargs={'user_id': self.member.pk})
return reverse('core:user_edit', kwargs={'user_id': self.member.pk})
def __str__(self):
if hasattr(self, "member") and self.member is not None:
......
......@@ -11,8 +11,8 @@
{% csrf_token %}
<p>{{ form.member.errors }}<label for="{{ form.member.name }}">{{ form.member.label }}</label> {{ form.member }}</p>
<div id="new_member">
<p>{{ form.last_name.errors }}<label for="{{ form.last_name.name }}">{{ form.last_name.label }}</label> {{ form.last_name }}</p>
<p>{{ form.first_name.errors }}<label for="{{ form.first_name.name }}">{{ form.first_name.label }}</label> {{ form.first_name }}</p>
<p>{{ form.last_name.errors }}<label for="{{ form.last_name.name }}">{{ form.last_name.label }}</label> {{ form.last_name }}</p>
<p>{{ form.email.errors }}<label for="{{ form.email.name }}">{{ form.email.label }}</label> {{ form.email }}</p>
</div>
<p>{{ form.subscription_type.errors }}<label for="{{ form.subscription_type.name }}">{{ form.subscription_type.label }}</label> {{ form.subscription_type }}</p>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment