Commit 43962cc5 authored by Flavio TARSETTI's avatar Flavio TARSETTI

Merge branch 'cleanup_ui' into 'django3_migration'

Cleanup ui

See merge request !368
parents dcdeb845 97020b42
Pipeline #42702 passed with stage
in 15 minutes and 9 seconds
......@@ -32,10 +32,12 @@
from django import forms
from django.core.files.base import ContentFile
from .widgets import CodeMirrorFileWidget, CodeMirrorTextarea
from ..common.models import Contribution
from ..common.utils import validate_restructuredtext
from .widgets import CodeMirrorFileWidget
from .widgets import CodeMirrorTextarea
class NameField(forms.CharField):
"""A specialization of the CharField that runs algo name validation"""
......@@ -46,11 +48,11 @@ class NameField(forms.CharField):
def to_python(self, value):
"""Converts the name to a valid python value"""
if not value:
raise forms.ValidationError(u'A non-blank name is required.')
raise forms.ValidationError(u"A non-blank name is required.")
return Contribution.sanitize_name(value)
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
class CodeMirrorCharField(forms.CharField):
......@@ -61,57 +63,62 @@ class CodeMirrorCharField(forms.CharField):
codemirror_kwargs = dict(codemirror_kwargs)
# handles the readonly attribute gracefully
if 'readonly' in kwargs:
if kwargs['readonly']:
config = codemirror_kwargs.get('config', {})
config['readOnly'] = True
codemirror_kwargs['config'] = config
del kwargs['readonly']
kwargs.update({'widget': CodeMirrorTextarea(**codemirror_kwargs)})
if "readonly" in kwargs:
if kwargs["readonly"]:
config = codemirror_kwargs.get("config", {})
config["readOnly"] = True
codemirror_kwargs["config"] = config
del kwargs["readonly"]
kwargs.update({"widget": CodeMirrorTextarea(**codemirror_kwargs)})
super(CodeMirrorCharField, self).__init__(*args, **kwargs)
def to_python(self, data):
clean_data = data.replace('\r', '') if data else ''
clean_data = data.replace("\r", "") if data else ""
return super(CodeMirrorCharField, self).to_python(clean_data)
class CodeMirrorRSTCharField(CodeMirrorCharField):
"""Allows editing a text field with a source code editor"""
def __init__(self, codemirror_kwargs={}, *args, **kwargs):
codemirror_kwargs = dict(codemirror_kwargs)
addon_js = list(codemirror_kwargs.get('addon_js', []))
addon_js = list(codemirror_kwargs.get("addon_js", []))
addon_js += [
"display/rulers",
]
codemirror_kwargs['addon_js'] = addon_js
codemirror_kwargs["addon_js"] = addon_js
codemirror_kwargs['mode'] = 'rst'
config = codemirror_kwargs.get('config', {})
config['foldGutter'] = False
config['gutters'] = ["CodeMirror-linenumbers"]
codemirror_kwargs['config'] = config
codemirror_kwargs["mode"] = "rst"
config = codemirror_kwargs.get("config", {})
config["foldGutter"] = False
config["gutters"] = ["CodeMirror-linenumbers"]
codemirror_kwargs["config"] = config
super(CodeMirrorRSTCharField, self).__init__(codemirror_kwargs, *args, **kwargs)
def to_python(self, data):
validate_restructuredtext(data)
return super(CodeMirrorRSTCharField, self).to_python(data)
class CodeMirrorPythonCharField(CodeMirrorCharField):
"""Allows editing a file instead of a plain content"""
def __init__(self, codemirror_kwargs={}, *args, **kwargs):
codemirror_kwargs = dict(codemirror_kwargs)
addon_js = list(codemirror_kwargs.get('addon_js', []))
addon_js = list(codemirror_kwargs.get("addon_js", []))
addon_js += [
"fold/indent-fold",
"display/rulers",
]
codemirror_kwargs['addon_js'] = addon_js
codemirror_kwargs["addon_js"] = addon_js
codemirror_kwargs["mode"] = "python"
super(CodeMirrorPythonCharField, self).__init__(
codemirror_kwargs, *args, **kwargs
)
codemirror_kwargs['mode'] = 'python'
super(CodeMirrorPythonCharField, self).__init__(codemirror_kwargs, *args, **kwargs)
class CodeMirrorJSONCharField(CodeMirrorCharField):
"""Allows editing a file instead of a plain content"""
......@@ -119,19 +126,21 @@ class CodeMirrorJSONCharField(CodeMirrorCharField):
def __init__(self, codemirror_kwargs={}, *args, **kwargs):
codemirror_kwargs = dict(codemirror_kwargs)
addon_js = list(codemirror_kwargs.get('addon_js', []))
addon_js = list(codemirror_kwargs.get("addon_js", []))
addon_js += [
"fold/brace-fold",
"display/rulers",
]
codemirror_kwargs['addon_js'] = addon_js
codemirror_kwargs["addon_js"] = addon_js
codemirror_kwargs['mode'] = {'name': 'javascript', 'json': True}
codemirror_kwargs["mode"] = {"name": "javascript", "json": True}
super(CodeMirrorJSONCharField, self).__init__(codemirror_kwargs, *args, **kwargs)
super(CodeMirrorJSONCharField, self).__init__(
codemirror_kwargs, *args, **kwargs
)
#-----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
class CodeMirrorFileField(forms.FileField):
......@@ -141,59 +150,64 @@ class CodeMirrorFileField(forms.FileField):
codemirror_kwargs = dict(codemirror_kwargs)
# handles the readonly attribute gracefully
if 'readonly' in kwargs:
if kwargs['readonly']:
config = codemirror_kwargs.get('config', {})
config['readOnly'] = True
codemirror_kwargs['config'] = config
del kwargs['readonly']
kwargs.update({'widget': CodeMirrorFileWidget(**codemirror_kwargs)})
if "readonly" in kwargs:
if kwargs["readonly"]:
config = codemirror_kwargs.get("config", {})
config["readOnly"] = True
codemirror_kwargs["config"] = config
del kwargs["readonly"]
kwargs.update({"widget": CodeMirrorFileWidget(**codemirror_kwargs)})
super(CodeMirrorFileField, self).__init__(*args, **kwargs)
def to_python(self, data):
data = ContentFile(data.replace('\r',''))
data.name = '__ignore__'
data = ContentFile(data.replace("\r", ""))
data.name = "__ignore__"
return super(CodeMirrorFileField, self).to_python(data)
class CodeMirrorRSTFileField(CodeMirrorFileField):
"""Allows editing a text field with a source code editor"""
def __init__(self, codemirror_kwargs={}, *args, **kwargs):
codemirror_kwargs = dict(codemirror_kwargs)
addon_js = list(codemirror_kwargs.get('addon_js', []))
addon_js = list(codemirror_kwargs.get("addon_js", []))
addon_js += [
"display/rulers",
]
codemirror_kwargs['addon_js'] = addon_js
codemirror_kwargs["addon_js"] = addon_js
codemirror_kwargs['mode'] = 'rst'
config = codemirror_kwargs.get('config', {})
config['foldGutter'] = False
config['gutters'] = ["CodeMirror-linenumbers"]
codemirror_kwargs['config'] = config
codemirror_kwargs["mode"] = "rst"
config = codemirror_kwargs.get("config", {})
config["foldGutter"] = False
config["gutters"] = ["CodeMirror-linenumbers"]
codemirror_kwargs["config"] = config
super(CodeMirrorRSTFileField, self).__init__(codemirror_kwargs, *args, **kwargs)
def to_python(self, data):
validate_restructuredtext(data)
return super(CodeMirrorRSTFileField, self).to_python(data)
class CodeMirrorPythonFileField(CodeMirrorFileField):
"""Allows editing a file instead of a plain content"""
def __init__(self, codemirror_kwargs={}, *args, **kwargs):
codemirror_kwargs = dict(codemirror_kwargs)
addon_js = list(codemirror_kwargs.get('addon_js', []))
addon_js = list(codemirror_kwargs.get("addon_js", []))
addon_js += [
"fold/indent-fold",
"display/rulers",
]
codemirror_kwargs['addon_js'] = addon_js
codemirror_kwargs["addon_js"] = addon_js
codemirror_kwargs["mode"] = "python"
super(CodeMirrorPythonFileField, self).__init__(
codemirror_kwargs, *args, **kwargs
)
codemirror_kwargs['mode'] = 'python'
super(CodeMirrorPythonFileField, self).__init__(codemirror_kwargs, *args, **kwargs)
class CodeMirrorJSONFileField(CodeMirrorFileField):
"""Allows editing a file instead of a plain content"""
......@@ -201,13 +215,15 @@ class CodeMirrorJSONFileField(CodeMirrorFileField):
def __init__(self, codemirror_kwargs={}, *args, **kwargs):
codemirror_kwargs = dict(codemirror_kwargs)
addon_js = list(codemirror_kwargs.get('addon_js', []))
addon_js = list(codemirror_kwargs.get("addon_js", []))
addon_js += [
"fold/brace-fold",
"display/rulers",
]
codemirror_kwargs['addon_js'] = addon_js
codemirror_kwargs["addon_js"] = addon_js
codemirror_kwargs['mode'] = {'name': 'javascript', 'json': True}
codemirror_kwargs["mode"] = {"name": "javascript", "json": True}
super(CodeMirrorJSONFileField, self).__init__(codemirror_kwargs, *args, **kwargs)
super(CodeMirrorJSONFileField, self).__init__(
codemirror_kwargs, *args, **kwargs
)
......@@ -26,30 +26,28 @@
###############################################################################
from django import template
from django.templatetags.static import StaticNode
from django.contrib.staticfiles.storage import staticfiles_storage
from django.templatetags.static import StaticNode
from ... import __version__
register = template.Library()
#--------------------------------------------------
# --------------------------------------------------
class FingerprintedFilesNode(StaticNode):
def url(self, context):
path = self.path.resolve(context)
url = staticfiles_storage.url(path)
return url + '?v' + __version__
return url + "?v" + __version__
#--------------------------------------------------
# --------------------------------------------------
@register.tag('fingerprint')
@register.tag("fingerprint")
def do_fingerprint(parser, token):
"""
A template tag that returns the URL to a file
......
......@@ -25,17 +25,16 @@
# #
###############################################################################
from django.conf import settings
from django import template
from django.template.defaultfilters import stringfilter
import hashlib
from django import template
from django.conf import settings
from django.template.defaultfilters import stringfilter
register = template.Library()
#--------------------------------------------------
# --------------------------------------------------
@stringfilter
......@@ -43,13 +42,13 @@ def gravatar_hash(email):
""" Computes the hash of an e-mail address to be recognized by gravatar.com
"""
to_hash = email.lower().encode("utf-8")
return hashlib.md5(to_hash).hexdigest()
return hashlib.md5(to_hash).hexdigest() # nosec: B303
register.filter('gravatar_hash', gravatar_hash)
register.filter("gravatar_hash", gravatar_hash)
#--------------------------------------------------
# --------------------------------------------------
@stringfilter
......@@ -57,9 +56,9 @@ def gravatar_url(email):
""" Returns the Gravatar URL of an e-mail address
"""
if settings.USE_HTTPS_GRAVATAR:
return 'https://secure.gravatar.com/avatar/' + gravatar_hash(email)
return "https://secure.gravatar.com/avatar/" + gravatar_hash(email)
else:
return 'http://www.gravatar.com/avatar/' + gravatar_hash(email)
return "http://www.gravatar.com/avatar/" + gravatar_hash(email)
register.filter('gravatar_url', gravatar_url)
register.filter("gravatar_url", gravatar_url)
......@@ -36,18 +36,19 @@ markup syntaxes to HTML; currently there is support for:
Source copied from: https://github.com/django/django/blob/stable/1.5.x/django/contrib/markup/templatetags/markup.py
"""
from django import template
from django.conf import settings
from django.utils.encoding import force_bytes, force_text
from django.utils.safestring import mark_safe
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_bytes
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter(is_safe=True)
@stringfilter
def markdown(value, arg=''):
def markdown(value, arg=""):
"""
Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
......@@ -68,31 +69,34 @@ def markdown(value, arg=''):
import markdown
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in 'markdown' filter: The Python markdown library isn't installed.")
raise template.TemplateSyntaxError(
"Error in 'markdown' filter: The Python markdown library isn't installed."
)
return force_text(value)
else:
markdown_vers = getattr(markdown, "version_info", 0)
if markdown_vers < (2, 1):
if settings.DEBUG:
raise template.TemplateSyntaxError(
"Error in 'markdown' filter: Django does not support versions of the Python markdown library < 2.1.")
"Error in 'markdown' filter: Django does not support versions of the Python markdown library < 2.1."
)
return force_text(value)
else:
extensions = [e for e in arg.split(",") if e]
if extensions and extensions[0] == "safe":
extensions = extensions[1:]
return mark_safe(markdown.markdown(
return mark_safe( # nosec: B703
markdown.markdown(
force_text(value),
extensions,
safe_mode=True,
enable_attributes=False,
))
)
)
else:
return mark_safe(markdown.markdown(
force_text(value),
extensions,
safe_mode=False,
))
return mark_safe( # nosec: B703
markdown.markdown(force_text(value), extensions, safe_mode=False,)
)
@register.filter(is_safe=True)
......@@ -102,12 +106,21 @@ def restructuredtext(value, full=False):
from docutils.core import publish_parts
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in 'restructuredtext' filter: The Python docutils library isn't installed.")
raise template.TemplateSyntaxError(
"Error in 'restructuredtext' filter: The Python docutils library isn't installed."
)
return force_text(value)
else:
docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})
parts = publish_parts(source=force_bytes(value), writer_name="html4css1", settings_overrides=docutils_settings)
parts = publish_parts(
source=force_bytes(value),
writer_name="html4css1",
settings_overrides=docutils_settings,
)
if full:
return mark_safe(force_text(parts["html_body"])) #with h1 title
text = parts["html_body"] # with h1 title
else:
return mark_safe(force_text(parts["fragment"])) #contains no title
text = parts["fragment"] # contains no title
return mark_safe(force_text(text)) # nosec: B703
This diff is collapsed.
......@@ -25,16 +25,15 @@
# #
###############################################################################
from django.conf.urls import url
from django.conf import settings
from django.views.generic.base import TemplateView
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.views.generic.base import TemplateView
from . import views
from .registration.forms import PreregistrationForm
from .registration.views import activate
from .registration.views import register
from .registration.forms import PreregistrationForm
app_name = "ui"
......
......@@ -26,34 +26,32 @@
###############################################################################
from django.shortcuts import get_object_or_404
from django.shortcuts import render
import datetime
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.models import User
from django.contrib import messages
from django.core.mail import EmailMessage
from django.db.models import Q
from django.http import Http404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.db.models import Q
from django.core.mail import EmailMessage
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.template.loader import render_to_string
from django.conf import settings
from django.urls import reverse
from rest_framework.authtoken.models import Token
from .. import __version__
from ..common.models import Shareable
from ..accounts.models import Profile
from ..accounts.models import SupervisionTrack
from ..accounts.models import TemporaryUrl
from ..common.models import Shareable
from ..utils import mail
from .registration.forms import BlockedUserRevalidationForm
import datetime
try:
from urlparse import urlparse
except ImportError:
......@@ -75,6 +73,7 @@ def index(request):
# ----------------------------------------------------------
class LoginView(auth_views.LoginView):
def post(self, request, *args, **kwargs):
authentication_match = False
......@@ -88,7 +87,9 @@ class LoginView(auth_views.LoginView):
authentication_match = user.check_password(request.POST["password"])
if authentication_match and user.profile.status == Profile.BLOCKED:
reactivation_url = request.build_absolute_uri(reverse('blocked_user_reactivation'))
reactivation_url = request.build_absolute_uri(
reverse("blocked_user_reactivation")
)
context = {
"user": user,
"reactivation_url": reactivation_url,
......@@ -225,16 +226,16 @@ def blocked_user_reactivation(request):
def gather_contributions(requestor, author):
"""Gather contributions that are accessible to a certain requestor"""
from ..experiments.models import Experiment
from ..toolchains.models import Toolchain
from ..algorithms.models import Algorithm
from ..libraries.models import Library
from ..dataformats.models import DataFormat
from ..team.models import Team
from ..attestations.models import Attestation
from ..reports.models import Report
from ..dataformats.models import DataFormat
from ..experiments.models import Experiment
from ..libraries.models import Library
from ..plotters.models import Plotter
from ..reports.models import Report
from ..search.models import Search
from ..team.models import Team
from ..toolchains.models import Toolchain
experiments = Experiment.objects.for_user(requestor).filter(author=author)
toolchains = Toolchain.objects.for_user(requestor).filter(author=author)
......@@ -277,7 +278,8 @@ def activity_stream(request, author_name):
author = get_object_or_404(User, username=author_name)
# gather leaderboards for the following conditions:
from ..search.models import Search, Leaderboard
from ..search.models import Leaderboard
from ..search.models import Search
if request.user == author:
# 1. request.user == author AND user is subscribed
......
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