<commit_before># Copyright (c) 2022, Djaodjin Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Views to update login credentials and display information about a User."""

import logging

from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.views.generic.edit import UpdateView

from .. import settings
from ..compat import gettext_lazy as _, is_authenticated, reverse, six
from ..forms import (PasswordChangeForm, PublicKeyForm, UserForm,
    UserNotificationsForm)
from ..helpers import has_invalid_password
from ..mixins import UserMixin
from ..models import Contact, Notification
from ..utils import update_db_row


LOGGER = logging.getLogger(__name__)


class UserProfileView(UserMixin, UpdateView):
    """
    If a user is manager for an Organization, she can access the Organization
    profile. If a user is manager for an Organization subscribed to another
    Organization, she can access the product provided by that organization.
    """
    form_class = UserForm
    template_name = 'users/index.html'

    def form_valid(self, form):
        contact = self.object.contacts.filter(email=self.object.email).first()
        if not contact:
            contact = self.object.contacts.order_by('pk').first()
        with transaction.atomic():
            # `form.save(commit=False)` will copy the form fields values
            # to the instance without committing to the database.
            # `update_db_row` will commit to the database.
            form.save(commit=False)
            if update_db_row(self.object, form):
                return self.form_invalid(form)
            if contact:
                contact.slug = form.cleaned_data['username']
                contact.full_name = form.cleaned_data['full_name']
                contact.nick_name = form.cleaned_data['nick_name']
                contact.lang = form.cleaned_data['lang']
                if contact.email != form.cleaned_data['email']:
                    contact.email = form.cleaned_data['email']
                    contact.email_verified_at = None
                if contact.phone != form.cleaned_data['phone']:
                    contact.phone = form.cleaned_data['phone']
                    contact.phone_verified_at = None
                if update_db_row(contact, form):
                    return self.form_invalid(form)
            else:
                contact = Contact.objects.create(
                    user=self.object,
                    slug=form.cleaned_data['username'],
                    full_name=form.cleaned_data['full_name'],
                    nick_name=form.cleaned_data['nick_name'],
                    lang=form.cleaned_data['lang'],
                    email=form.cleaned_data['email'],
                    phone=form.cleaned_data['phone'])
        return HttpResponseRedirect(self.get_success_url())

    def get_initial(self):
        initial = super(UserProfileView, self).get_initial()
        if self.object:
            initial.update({'full_name': self.object.get_full_name()})
        return initial

    def get_context_data(self, **kwargs):
        context = super(UserProfileView, self).get_context_data(**kwargs)
        setattr(context['user'], 'full_name', context['user'].get_full_name())<commit_msg>supports override of `form_invalid` making SQL query<commit_after># Copyright (c) 2022, Djaodjin Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Views to update login credentials and display information about a User."""

import logging

from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.views.generic.edit import UpdateView

from .. import settings
from ..compat import gettext_lazy as _, is_authenticated, reverse, six
from ..forms import (PasswordChangeForm, PublicKeyForm, UserForm,
    UserNotificationsForm)
from ..helpers import has_invalid_password
from ..mixins import UserMixin
from ..models import Contact, Notification
from ..utils import update_db_row


LOGGER = logging.getLogger(__name__)


class UserProfileView(UserMixin, UpdateView):
    """
    If a user is manager for an Organization, she can access the Organization
    profile. If a user is manager for an Organization subscribed to another
    Organization, she can access the product provided by that organization.
    """
    form_class = UserForm
    template_name = 'users/index.html'

    def form_valid(self, form):
        contact = self.object.contacts.filter(email=self.object.email).first()
        if not contact:
            contact = self.object.contacts.order_by('pk').first()
        failed = False
        with transaction.atomic():
            # `form.save(commit=False)` will copy the form fields values
            # to the instance without committing to the database.
            # `update_db_row` will commit to the database.
            form.save(commit=False)
            if update_db_row(self.object, form):
                failed = True
            else:
                if contact:
                    contact.slug = form.cleaned_data['username']
                    contact.full_name = form.cleaned_data['full_name']
                    contact.nick_name = form.cleaned_data['nick_name']
                    contact.lang = form.cleaned_data['lang']
                    if contact.email != form.cleaned_data['email']:
                        contact.email = form.cleaned_data['email']
                        contact.email_verified_at = None
                    if contact.phone != form.cleaned_data['phone']:
                        contact.phone = form.cleaned_data['phone']
                        contact.phone_verified_at = None
                    if update_db_row(contact, form):
                        failed = True
                else:
                    contact = Contact.objects.create(
                        user=self.object,
                        slug=form.cleaned_data['username'],
                        full_name=form.cleaned_data['full_name'],
                        nick_name=form.cleaned_data['nick_name'],
                        lang=form.cleaned_data['lang'],
                        email=form.cleaned_data['email'],
                        phone=form.cleaned_data['phone'])
        if failed:
            return self.form_invalid(form)
        return HttpResponseRedirect(self.get_success_url())

    def get_initial(self):
        initial = super(UserProfileView, self).get_initial()
        if self.object:
            initial.update({'full_name': self.object.get_full_name()})
        return initial

    def get_context_data(self, **kwargs):
        context = super(UserProfileView, self).get_context_data(**kwargs)
        setattr(context['user'], 'full_name', context['user'].get_full_name())
{'fraction_non_alphanumeric': 0.07656845059130087, 'fraction_numerical': 0.0012026458208057728, 'mean_word_length': 2.9194815396700706, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5592197', 'n_tokens_mistral': 2607, 'n_tokens_neox': 2440, 'n_words': 864}