Rework account create

- Affichage des erreurs en cas... d'erreurs !
This commit is contained in:
Aurélien Delobelle 2016-09-01 05:01:59 +02:00
parent cbf9018bb9
commit 9534771cd9
4 changed files with 105 additions and 77 deletions

View file

@ -83,7 +83,8 @@ class CofRestrictForm(CofForm):
class UserForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
new_user = kwargs.get('instance') is None
from_clipper = kwargs.pop('from_clipper', False)
new_user = kwargs.get('instance') is None and not from_clipper
super(UserForm, self).__init__(*args, **kwargs)
if new_user:
self.fields['username'].validators = [MinLengthValidator(9)]

View file

@ -14,11 +14,14 @@
{% include 'kfet/base_messages.html' %}
<form action="{% url "kfet.account.create" %}" method="post">
{{ account_trigramme_form }}
{% csrf_token %}
{{ trigramme_form }}
<div id="trigramme_valid"></div>
<input type="text" name="q" id="search_autocomplete" spellcheck="false" placeholder="Chercher un utilisateur par nom, prénom ou identifiant clipper">
<div id="search_results"></div>
<div id="form-placeholder"></div>
<div id="form-placeholder">
{% include 'kfet/account_create_form.html' %}
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {

View file

@ -1,4 +1,3 @@
{% csrf_token %}
{{ user_form.as_p }}
{{ cof_form.as_p }}
{{ account_form.as_p }}

View file

@ -86,34 +86,27 @@ def account_is_validandfree_ajax(request):
@teamkfet_required
def account_create(request):
# A envoyer au template
data_template = {
'account_trigramme_form': AccountTriForm(),
}
# Enregistrement
if request.method == "POST":
# Pour indiquer la tentative d'enregistrement au template
# Checking permission
if not request.user.has_perm('kfet.add_account'):
raise PermissionDenied
trigramme_form = AccountTriForm(request.POST)
# Peuplement des forms
username = request.POST.get('username')
try:
user = User.objects.get(username=username)
(cof, _) = CofProfile.objects.get_or_create(user=user)
user_form = UserForm(request.POST, instance=user)
cof_form = CofForm(request.POST, instance=cof)
except User.DoesNotExist:
user_form = UserForm(request.POST)
cof_form = CofForm(request.POST)
trigramme_form = AccountTriForm(request.POST)
account_form = AccountNoTriForm(request.POST)
login_clipper = request.POST.get('login_clipper')
forms = get_account_create_forms(
request, username=username, login_clipper=login_clipper)
account_form = forms['account_form']
cof_form = forms['cof_form']
user_form = forms['user_form']
if all((user_form.is_valid(), cof_form.is_valid(),
trigramme_form.is_valid(), account_form.is_valid())):
# Checking permission
if not request.user.has_perm('kfet.add_account'):
messages.error(request, 'Permission refusée')
else:
data = {}
# Fill data for Account.save()
put_cleaned_data_in_dict(data, user_form)
@ -124,26 +117,31 @@ def account_create(request):
account_form = AccountNoTriForm(request.POST, instance=account)
account_form.save()
messages.success(request, 'Compte créé : %s' % account.trigramme)
return redirect('kfet.account.create')
except Account.UserHasAccount as e:
messages.error(request, \
"Cet utilisateur a déjà un compte K-Fêt : %s" % e.trigramme)
else:
messages.error(request, user_form.errors)
messages.error(request, cof_form.errors)
messages.error(request, trigramme_form.errors)
messages.error(request, account_form.errors)
trigramme_form = AccountTriForm()
account_form = None
cof_form = None
user_form = None
return render(request, "kfet/account_create.html", data_template)
return render(request, "kfet/account_create.html", {
'trigramme_form': trigramme_form,
'account_form': account_form,
'cof_form': cof_form,
'user_form': user_form,
})
def account_form_set_readonly_fields(user_form, cof_form):
user_form.fields['username'].widget.attrs['readonly'] = True
cof_form.fields['login_clipper'].widget.attrs['readonly'] = True
cof_form.fields['is_cof'].widget.attrs['disabled'] = True
@login_required
@teamkfet_required
def account_create_ajax(request, username=None, login_clipper=None):
def get_account_create_forms(request=None, username=None, login_clipper=None):
user = None
clipper = None
if login_clipper:
# à partir d'un clipper
# le user associé à ce clipper ne devrait pas encore exister
@ -157,53 +155,82 @@ def account_create_ajax(request, username=None, login_clipper=None):
except User.DoesNotExist:
# Clipper (sans user déjà existant)
# UserForm - Prefill + Création
user_initial_data = {
# UserForm - Prefill
user_initial = {
'username' : login_clipper,
'email' : "%s@clipper.ens.fr" % login_clipper}
if clipper.fullname:
# Prefill du nom et prénom
names = clipper.fullname.split()
# Le premier, c'est le prénom
user_initial_data['first_name'] = names[0]
user_initial['first_name'] = names[0]
if len(names) > 1:
# Si d'autres noms -> tous dans le nom de famille
user_initial_data['last_name'] = " ".join(names[1:])
user_form = UserForm(initial = user_initial_data)
user_initial['last_name'] = " ".join(names[1:])
# CofForm - Prefill
cof_initial = { 'login_clipper': login_clipper }
# CofForm - Prefill + Création
cof_initial_data = { 'login_clipper': login_clipper }
cof_form = CofForm(initial = cof_initial_data)
# AccountForm
account_form = AccountForm()
# Form créations
if request:
user_form = UserForm(request.POST, initial=user_initial, from_clipper=True)
cof_form = CofForm(request.POST, initial=cof_initial)
else:
user_form = UserForm(initial=user_initial)
cof_form = CofForm(initial=cof_initial)
# Protection (read-only) des champs username et login_clipper
account_form_set_readonly_fields(user_form, cof_form)
if username:
if username and not login_clipper:
try:
user = User.objects.get(username=username)
# le user existe déjà
user = get_object_or_404(User, username=username)
# récupération du profil cof
(cof, _) = CofProfile.objects.get_or_create(user=user)
# UserForm + CofForm - Création à partir des instances existantes
if request:
user_form = UserForm(request.POST, instance = user)
cof_form = CofForm(request.POST, instance = cof)
else:
user_form = UserForm(instance=user)
cof_form = CofForm(instance=cof)
# AccountForm
account_form = AccountNoTriForm()
# Protection (read-only) des champs username et login_clipper
# Protection (read-only) des champs username, login_clipper et is_cof
account_form_set_readonly_fields(user_form, cof_form)
elif not login_clipper:
except User.DoesNotExist:
# le username donnée n'existe pas -> Création depuis rien
# (éventuellement en cours avec erreurs précédemment)
pass
if not user and not clipper:
# connaît pas du tout, faut tout remplir
if request:
user_form = UserForm(request.POST)
cof_form = CofForm(request.POST)
else:
user_form = UserForm()
cof_form = CofForm()
account_form = AccountNoTriForm()
# mais on laisse le username en écriture
cof_form.fields['login_clipper'].widget.attrs['readonly'] = True
cof_form.fields['is_cof'].widget.attrs['disabled'] = True
return render(request, "kfet/account_create_form.html", {
if request:
account_form = AccountNoTriForm(request.POST)
else:
account_form = AccountNoTriForm()
return {
'account_form': account_form,
'cof_form': cof_form,
'user_form': user_form,
}
@login_required
@teamkfet_required
def account_create_ajax(request, username=None, login_clipper=None):
forms = get_account_create_forms(request=None, username=username, login_clipper=login_clipper)
return render(request, "kfet/account_create_form.html", {
'account_form' : forms['account_form'],
'cof_form' : forms['cof_form'],
'user_form' : forms['user_form'],
})
# Account - Read
@ -280,7 +307,6 @@ def account_update(request, trigramme):
# Fill data for Account.save()
put_cleaned_data_in_dict(data, user_form)
put_cleaned_data_in_dict(data, cof_form)
print(vars(account.negative))
# Updating
account_form.save(data = data)
@ -289,7 +315,6 @@ def account_update(request, trigramme):
if (request.user.has_perm('kfet.manage_perms')
and group_form.is_valid()):
group_form.save()
print(vars(account.negative))
# Checking perm to manage negative
if hasattr(account, 'negative'):