Un seul formulaire pour tout éditer

This commit is contained in:
Evarin 2017-04-13 22:50:00 +02:00
parent ebfd293b0e
commit d0ac58e5da
4 changed files with 65 additions and 66 deletions

View file

@ -4,6 +4,17 @@ from django import forms
from avisstage.models import Normalien, Stage, Lieu, AvisLieu, AvisStage
from widget import LatLonField
class AvisStageForm(forms.ModelForm):
class Meta:
model = AvisStage
fields = ['chapo', 'avis_ambiance', 'avis_sujet', 'avis_admin', 'les_plus', 'les_moins']
class AvisLieuForm(forms.ModelForm):
class Meta:
model = AvisLieu
fields = ['lieu', 'chapo', 'avis_lieustage', 'avis_pratique', 'avis_tourisme', 'les_plus', 'les_moins']
class StageForm(forms.ModelForm):
date_widget = forms.DateInput(attrs={"class":"datepicker"})
date_debut = forms.DateField(input_formats=["%d/%m/%Y"], widget=date_widget)
@ -11,60 +22,19 @@ class StageForm(forms.ModelForm):
class Meta:
model = Stage
fields = ['sujet', 'date_debut', 'date_fin', 'type_stage', 'thematiques', 'matieres', 'encadrants', 'lieux']
fields = ['sujet', 'date_debut', 'date_fin', 'type_stage', 'thematiques', 'matieres', 'encadrants']
def __init__(self, *args, **kwargs):
if "request" in kwargs:
self.request = kwargs.pop("request")
super(StageForm, self).__init__(*args, **kwargs)
if hasattr(self, 'instance'):
self.prev_lieux = self.instance.avislieu_set.all()
else:
self.prev_lieux = None
def save(self, commit=True):
if self.instance.id is None:
if self.instance.id is None and hasattr(self, 'request'):
self.instance.auteur = self.request.user.profil
stage = super(StageForm, self).save(commit=False)
if commit:
stage.save()
# Lecture des lieux, conservation des critiques précédentes
alieux = self.cleaned_data['lieux']
new_lieux = []
#print self.instance.lieux
if not (self.prev_lieux is None) and len(self.prev_lieux) > 0:
old_avislieux = {avis.lieu_id: avis for avis in self.prev_lieux}
for (k, nlieu) in enumerate(alieux):
if nlieu in old_avislieux:
# Ce lien existait déjà avant
# mise à jour de l'ordre
old_avislieu[nlieu].order = k
old_avi_lieu[nlieu].save()
# Rien d'autre à faire
del old_avislieux[nlieu]
else:
# C'est un nouveau lien
new_lieux.append((k, nlieu))
old_avislieux = old_avislieux.values()
for k, avislieu in enumerate(old_avislieux):
if k > len(new_lieux):
# Avis à supprimer
avislieu.delete()
else:
# On récupère le(s) avis pour le(s) nouveau(x) lieu(x)
avislieu.lieu, avislieu.order = new_lieux[k]
avislieu.save()
new_lieux = new_lieux[len(old_avislieux):]
else:
new_lieux = enumerate(alieux)
print(new_lieux)
# On crée les nouveaux avislieu qui vont bien
AvisLieu.objects.bulk_create([AvisLieu(lieu=lieu, stage=stage, order=k)
for (lieu, k) in new_lieux])
stage = super(StageForm, self).save(commit=commit)
return stage
class LieuForm(forms.ModelForm):
@ -74,17 +44,3 @@ class LieuForm(forms.ModelForm):
model = Lieu
fields = ['nom', 'type_lieu', 'ville', 'pays', 'coord']
class AvisStageForm(forms.ModelForm):
class Meta:
model = AvisStage
fields = ['chapo', 'avis_ambiance', 'avis_sujet', 'avis_admin', 'les_plus', 'les_moins']
class AvisLieuForm(forms.ModelForm):
class Meta:
model = AvisLieu
fields = ['chapo', 'avis_lieustage', 'avis_pratique', 'avis_tourisme', 'les_plus', 'les_moins']

View file

@ -19,6 +19,8 @@
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
{{ avis_stage_form.as_p }}
{{ avis_lieu_formset.as_p }}
<input type="submit" value="Enregistrer" />
</form>
{% endblock %}

View file

@ -4,9 +4,9 @@ from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^perso/$', views.perso, name='perso'),
url(r'^stage/nouveau/$', views.StageAjout.as_view(), name='stage_ajout'),
url(r'^stage/nouveau/$', views.manage_stage, name='stage_ajout'),
url(r'^stage/(?P<pk>\w+)/$', views.StageView.as_view(), name='stage'),
url(r'^stage/(?P<pk>\w+)/edit/$', views.StageEdit.as_view(), name='stage_edit'),
url(r'^stage/(?P<id_stage>\w+)/edit/$', views.manage_stage, name='stage_edit'),
url(r'^lieu/ajout/$', views.LieuAjout.as_view(), name='lieu_ajout'),
url(r'^profil/show/(?P<username>\w+)/$', views.ProfilView.as_view(),

View file

@ -1,6 +1,6 @@
# coding: utf-8
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.views.generic import DetailView
from django.views.generic.edit import UpdateView, CreateView
@ -45,6 +45,43 @@ class ProfilView(DetailView, LoginRequiredMixin):
return Normalien.objects.get(user__username=self.kwargs.get('username'))
# Stages
@login_required
def manage_stage(request, id_stage=None):
if id_stage is None:
stage = Stage(auteur=request.user.profil)
avis_stage = AvisStage(stage=stage)
c_del = False
else:
stage = Stage.objects.filter(auteur=request.user.profil).get(pk=id_stage)
avis_stage, _ = AvisStage.objects.get_or_create(stage=stage)
c_del = True
AvisLieuFormSet = forms.inlineformset_factory(
Stage, AvisLieu, form=AvisLieuForm, can_delete=c_del)
if request.method == "POST":
form = StageForm(request.POST, request=request, instance=stage, prefix="stage")
avis_stage_form = AvisStageForm(request.POST,
instance=avis_stage, prefix="avis")
avis_lieu_formset = AvisLieuFormSet(request.POST, instance=stage,
prefix="lieux")
if (form.is_valid() and
avis_stage_form.is_valid() and
avis_lieu_formset.is_valid()):
stage = form.save()
avis_stage_form.instance.stage = stage
avis_stage_form.save()
avis_lieu_formset.save()
return redirect(reverse('avisstage:stage', kwargs={'pk':stage.id}))
else:
form = StageForm(instance=stage, prefix="stage")
avis_stage_form = AvisStageForm(instance=avis_stage, prefix="avis")
avis_lieu_formset = AvisLieuFormSet(instance=stage, prefix="lieux")
return render(request, "avisstage/formulaires/stage.html",
{'form': form, 'avis_stage_form': avis_stage_form,
'avis_lieu_formset': avis_lieu_formset})
class StageAjout(CreateView, LoginRequiredMixin):
model = Stage
form_class = StageForm
@ -72,7 +109,12 @@ class StageEdit(UpdateView, LoginRequiredMixin):
def get_success_url(self):
return reverse('avisstage:stage', self.instance.id)
def get_context_data(self, *args, **kwargs):
ctx = super(StageEdit, self).get_context_data(*args, **kwargs)
print ctx
return ctx
class StageView(DetailView, LoginRequiredMixin):
model = Stage
template_name = 'avisstage/detail/stage.html'
@ -83,7 +125,6 @@ class LieuAjout(CreateView, LoginRequiredMixin):
model = Lieu
form_class = LieuForm
template_name = 'avisstage/formulaires/lieu.html'
def recherche(request):
return render(request, 'avisstage/recherche.html')