I have had a problem for several days that I hope to find a solution here. so I try to edit a model, in the template I submit data but nothing is saved although the form is valid. I share my files with you.
ticket/form.py
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from datetime import datetime
from comptes.models import User
from Entite1.models import Entite1
class Ticket(models.Model):
app_liste=(
('Amplitute Bank','Amplitude'),
('STRS','Stream serve'),
('Signature','Signature'),
('Adria','Adria'),
('CFT','CFT'),
('Autosys','Autosys'),
('SWIFT','SWIFT'),
('J-1','J-1'),
('Portal','Portal'),
('Anadefi','Anadefi'),
('BD Defaut','BD Defaut'),
('Amplitude RH','Amplitude RH'),
('Amplitude Immo','Amplitude immo'),
('Amplitude Achat','Amplitude Achat'),
('Telecom','Telecom'),
('Securite','Securite'),
('Mantis','Mantis'),
('Messagerie','Messagerie'),
('Autre','Autrre')
)
env_liste=(
('Prod','Prod'),
('Preprod','Preprod'),
('UAT','UAT'),
('DEV','DEV'),
('RI','RI'),
('J-1','J-1')
)
modul_liste=(
('REF/CPTA','REF/CPTA'),
('AGE','AGE'),
('ENG','ENG'),
('MDP','MDP'),
('INT','INT'),
('TRV','TRV'),
('TECH','TECH'),
('TFJ','TFJ'),
('POST-TFJ','POST-TFJ'),
('LEASING','LEASING'),
('TRESO','TRESO'),
('Conformité','Conformité')
)
Catego_liste=(
('Administraction','Administration'),
('BUG','BUG'),
('Probleme de parametrage','Probleme de parametrage'),
('Utilisation','Utilisation'),
('Administration Technique','Administration Technique')
)
statut_liste=(
('Cloturé','Cloturé'),
('A soumettre','A soumettre'),
("Complement d'information","Complement d'information"),
("Traité à confirmer","Traité à confirmer"),
("Affecté","Affecté"),
("En cours","En cours"),
)
entite_liste=(
('HelpDesk','HelpDesk'),
('ORGA','ORGA'),
("BOP","BOP"),
('DSM','DSM'),
)
reference = models.CharField(max_length=10, unique=True)
sujet = models.CharField(max_length=250)
description = models.TextField()
categorie = models.CharField(max_length=30, choices=Catego_liste, blank=True, null=True)
module = models.CharField(max_length=60, choices=modul_liste, blank=True, null=True)
application = models.CharField(max_length=60, choices=app_liste, blank=True, null=True)
statut = models.CharField(max_length=60, choices=statut_liste, blank=True, null=True, default='A soumettre')
soumettre_entite = models.ForeignKey(Entite1, on_delete=models.CASCADE, related_name='ticket_affecte_a',blank=True, null=True)
soumettre_a = models.CharField(max_length=60, choices=entite_liste)
ref_mantis = models.CharField(max_length=30, blank=True, null=True, default='Aucune')
dim = models.CharField(max_length=30, blank=True, null=True, default='Aucune')
date_creation = models.DateTimeField(auto_now_add=True)
date_modif = models.DateTimeField(auto_now=True)
fichier = models.FileField(upload_to='fichier/', blank=True, null=True)
soumis_par = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ticket_soumis', blank=True, null=True)
assigne_a = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ticket_traite_par', blank=True, null=True)
capture_ecran=models.ImageField(upload_to='captures/',blank=True,null=True)
def save(self, *args, **kwargs):
if not self.reference:
current_year = str(datetime.now().year)[-2:]
last_ticket = Ticket.objects.filter(reference__startswith=current_year).order_by('-reference').first()
if last_ticket:
last_reference_number = int(last_ticket.reference.split('-')[1])
new_reference_number = last_reference_number + 1
else:
new_reference_number = 1
self.reference = f"{current_year}-{new_reference_number:05d}"
super().save(*args, **kwargs)
def __str__(self):
return self.sujet
@receiver(pre_save, sender=Ticket)
def set_ticket_fields(sender, instance, **kwargs):
if instance.soumis_par is None:
instance.soumis_par = instance._request.user if hasattr(instance, '_request') and instance._request else None
pre_save.connect(set_ticket_fields, sender=Ticket)
comptes/model
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from Entite1.models import Entite1
from django.utils import timezone
class CustomUserManager(BaseUserManager):
def _create_user(self,email,password, **extra_fields):
if not email:
raise ValueError("Veuillez entrer un email valide")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self,email=None,password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email,password, **extra_fields)
def create_superuser(self,email=None,password=None, **extra_fields ):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self._create_user(email,password, **extra_fields)
class User(AbstractBaseUser,PermissionsMixin):
email = models.EmailField(blank = True, default='',unique=True)
nom = models.CharField(max_length=50, blank=True, null=True)
prenom = models.CharField(max_length=50, blank=True, null=True)
entite= models.ForeignKey(Entite1, related_name='attache_a', on_delete=models.CASCADE,blank=True, null=True)
is_superuser= models.BooleanField(default=False)
is_active= models.BooleanField(default=True)
is_staff= models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
last_login= models.DateTimeField(blank=True, null=True)
peu_access_entite = models.BooleanField(default=False) # Champ de case à cocher pour l'accès à l'entité
objects = CustomUserManager()
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS =[]
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
def get_full_name(self):
return self.nom
ticket/forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.forms import Textarea
from .models import Ticket
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class TicketForm(forms.ModelForm):
class Ticket_assigne(forms.ModelForm):
def __init__(self, entite_utilisateur, *args, **kwargs):
super(Ticket_assigne, self).__init__(*args, **kwargs)
User = get_user_model()
self.fields['assigne_a'].queryset = User.objects.filter(entite=entite_utilisateur)
# Filtrer les utilisateurs en fonction de l'entité de l'utilisateur connecté
self.fields['assigne_a'].queryset = User.objects.filter(entite=entite_utilisateur)
class Meta:
model = Ticket
fields = ['sujet', 'description', 'assigne_a','categorie','module','application','soumettre_entite','ref_mantis','dim']
widgets = {
'description': Textarea(attrs={'rows': 4, 'readonly': 'readonly'}),
'sujet': forms.TextInput(attrs={'readonly': 'readonly'}),
'assigne_a': forms.Select(attrs={'class': 'form-control', 'required': 'required'}),
'application':forms.Select(attrs={'class':'form-control','readonly': 'readonly'}),
'categorie':forms.Select(attrs={'class':'form-control','readonly': 'readonly'}),
'module':forms.Select(attrs={'class':'form-control','readonly': 'readonly'}),
'soumettre_entite':forms.Select(attrs={'class':'form-control','readonly': 'readonly'}),
}
my views
def entiteasigne(request, pk):
entite_utilisateur = request.user.entite
ticket = get_object_or_404(Ticket,reference=pk)
form=Ticket_assigne(entite_utilisateur,instance=ticket)
if request.method=='POST':
form=Ticket_assigne(entite_utilisateur,request.POST,instance=ticket)
if form.is_valid():
ticket.statut='Assigné'
form.save()
messages.success(request,'Ticket a été affecté avec succès.')
return redirect('profil_entite')
else:
messages.error(request,"Veuillez corriger l'errreur ci-dessous")
error_field=form.errors.keys
else:
form=Ticket_assigne(entite_utilisateur,instance=ticket)
context={'form':form,'ticket':ticket}
return render(request,'tikets/entité_effect_page.html',context)
my tamplate
{% extends 'main.html' %}
{% block content %}
{% load static %}
{% include 'nav.html' %}
<script>
window.onload=function(){
document.getElementById("id_sujet").readOnly=true;
document.getElementById("id_description").readOnly=true;
document.getElementById("id_application").readOnly=true;
document.getElementById("id_categorie").readOnly=true;
document.getElementById("id_module").readOnly=true;
document.getElementById("id_soumettre_entite").readOnly=true;
};
</script>
<div class="container">
<div class="row">
<h5><i class="fa-solid fa-file-import"></i> Assignation du Ticket N°: {{ticket.reference}}</h5>
</div>
</div>
<div class="container">
{% load django_bootstrap5 %}
<form action="{% url 'hd_affect' ticket.reference %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% bootstrap_button button_type="submit" content="Soumettre" %}
{% bootstrap_button button_type="reset" content="Annuler" %}
<a href="{% url 'profil_entite' %}"><button type="button" class="btn btn-outline-success"><i class="fa-solid fa-backward"> Retour</i></button></a>
</form>
<div class="container">
<footer class="d-flex flex-wrap justify-content-between align-items-center py-3 my-4 border-top">
<div class="col-md-4 d-flex align-items-center">
<a href="/" class="mb-3 me-2 mb-md-0 text-body-secondary text-decoration-none lh-1">
<svg class="bi" width="30" height="24"><use xlink:href="#bootstrap"/></svg>
</a>
<span class="mb-3 mb-md-0 text-body-secondary">© 2023 Union Gabonaise de Banque, MEKAMBO v 1.0</span>
</div>
</footer>
</div>
</div>
{%endblock%}
when I submit the form the assign_a field does not save the value I choose