problem modifying a field

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">&copy; 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

Other than that, what else happens? Do you get redirected to profil_entite? Or do you remain on the current page? (This indicates whether the form submission passed the is_valid test.

Note: I see where you’re changing the ticket.statut field, but you’re not saving that instance of ticket, which means that field isn’t going to get updated in the database.

Also note: Setting the readOnly attribute in JavaScript does not prevent a user from altering the values in those fields. If you want those values to be unalterable, you must set the disabled (or readonly) attribute on those fields in the form.

I am redirected to the profile_entite page. also thank you for the remark regarding javaScript.
I went far in wanting to modify the fields that I wanted it to be in simple reading; the modification was supported except the value that I introduced in the assigne_a field which was not taken into account

Then my next step would be looking to verify that the data is being supplied as expected. I’d be walking through this using a debugger, or adding print statements at various points in this process to ensure that I’m getting what I’m expecting to get. This includes checking request.POST immediately after the if request.method ... test, checking form.cleaned_data after the is_valid test, then saving the return value from form.save and checking the values of that returned instance.

like this?

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():
            assigne_a_value = form.cleaned_data['assigne_a']
            ticket.assigne_a = assigne_a_value
            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é_affect_page.html',context)
    

Not quite.

What I’m suggesting is that you print those values to see what data is being used, not to alter any of your existing logic.

You can do this either by adding print calls in your view, or use a debugger to single-step through the code and examine the variables at each line.

ok I added prints at the beginning

def entiteasigne(request, pk):
    entite_utilisateur = request.user.entite
    ticket = get_object_or_404(Ticket, reference=pk)
    
    # Ajoutez des instructions print pour vérifier les valeurs des champs
    print(f"entite_utilisateur: {entite_utilisateur}")
    print(f"ticket.statut avant traitement: {ticket.statut}")
    print(f"ticket.assigne_a avant traitement: {ticket.assigne_a if ticket.assigne_a else 'None'}")

    form = Ticket_assigne(entite_utilisateur, instance=ticket)

    if request.method == 'POST':
        form = Ticket_assigne(entite_utilisateur, request.POST, instance=ticket)
        print(f"POST data: {request.POST}")  # Vérifiez les données POST reçues

        if form.is_valid():
            print(f"Cleaned data: {form.cleaned_data}")  # Vérifiez les données après validation

            ticket = form.save(commit=False)
            print(f"Ticket instance before save: {ticket}")

            ticket.statut = 'En cours'
            ticket.save()

            print(f"Ticket instance after save: {ticket}")

            messages.success(request, 'Ticket a été affecté avec succès.')
            return redirect('profil_entite')
        else:
            print(f"Form errors: {form.errors}")  # Affichez les erreurs du formulaire
            messages.error(request, "Veuillez corriger l'erreur ci-dessous")

    context = {'form': form, 'ticket': ticket}
    return render(request, 'tikets/entité_affect_page.html', context)

    

here is the result I get when I add the prints before submitting the form, the variables have the expected data

entite_utilisateur: CEA SIEGE
ticket.statut avant traitement: Affecté
ticket.assigne_a avant traitement: None

What data did I suggest that you print?

Where in your code did I suggest placing those print statements?

what should I do specifically?

What I suggested above at problem modifying a field - #4 by KenWhitesell

ok, here is how I modified

def votre_vue(request, ticket_reference):
    if request.method == 'POST':
        form = Ticket_assigne(request.POST)
        print(f"POST data: {request.POST}")  # Vérifiez les données POST reçues

        if form.is_valid():
            print(f"Cleaned data: {form.cleaned_data}")  # Vérifiez les données après validation

            # Traitement des données du formulaire
            ticket_instance = form.save(commit=False)
            print(f"Ticket instance before save: {ticket_instance}")

            # Mettez à jour le statut si nécessaire
            ticket_instance.statut = 'En cours'
            ticket_instance.save()

            print(f"Ticket instance after save: {ticket_instance}")

            # Redirigez l'utilisateur vers une autre page si nécessaire
            return HttpResponseRedirect('url_de_redirection')
    else:
        form = Ticket_assigne()

    # Votre code existant pour le cas où la méthode n'est pas POST

Unless your __str__ method in Ticket prints all the details of a Ticket, you’ll want to print the values you’re interested in instead of the entire instance.

In other words, instead of:

you may want to print:
print(f"assigne_a value of Ticket instance after save: {ticket_instance.assigne_a}")

The purpose here is to verify that all the data that you’re expecting to see is actually present.

unfortunately we have nothing in assigne_a

Anywhere?

Please post the output from all the print statements.

Side note: The view you posted at problem modifying a field - #12 by Sirchemaya is significantly different than the view you originally posted.

It would be helpful if you posted the current view and form being used here. (Only those two items, we don’t need anything else yet.)

forms.py

class Ticket_assigne(forms.ModelForm):
    def __init__(self, entite_utilisateur, *args, **kwargs):
        super(Ticket_assigne, self).__init__(*args, **kwargs)
        User = get_user_model()

        # 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'}),
        }

views.py

   
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='En cours'
            form.save()
            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é_affect_page.html',context)
    

Thanks to this code, I was able to record in the given database the name of the person to whom the ticket was assigned.
only the ticket status does not take the value "In Progress"

def assigner_ticket(request, pk):
    ticket = get_object_or_404(Ticket, reference=pk)

    if ticket.statut == 'Affecté' and request.user.entite == ticket.soumettre_entite:
        # Préremplissez le formulaire avec les données actuelles du ticket et définissez le statut sur 'En cours'
        form = FullTicketForm(instance=ticket, initial={'assigne_a': request.user, 'statut': 'En cours'})
        print(f"ticket.assigne avant traitement: {ticket.assigne_a}")
        if request.method == 'POST':
            form = FullTicketForm(request.POST, instance=ticket)
            if form.is_valid():

                ticket.statut='En cours'
                form.save()  
                print(f"ticket.statut apres traitement: {ticket.statut}")

                messages.success(request, 'Le ticket a été assigné avec succès.{ticket.statut}')
                return redirect('profil_entite')
            else:
                messages.error(request, 'Veuillez corriger les erreurs ci-dessous.')

        context = {'form': form, 'ticket': ticket}
        return render(request, 'tikets/entité_affect_page.html', context)
    else:
        messages.error(request, "Vous n'avez pas les autorisations nécessaires pour assigner ce ticket.")
        return redirect('hd_home_page')

That goes back to my previous response at problem modifying a field - #2 by KenWhitesell

this my changements 

def assigner_ticket(request, pk):
    ticket = get_object_or_404(Ticket, reference=pk)

    if ticket.statut == 'Affecté' and request.user.entite == ticket.soumettre_entite:
        initial_data = {'assigne_a': request.user, 'statut': 'En cours'}
        form = FullTicketForm(instance=ticket, initial=initial_data)
        if request.method == 'POST':
            form = FullTicketForm(request.POST, instance=ticket)

            if form.is_valid():
                form.save()

                print(f"ticket.statut après traitement: {ticket.statut}")

                messages.success(request, 'Le ticket a été assigné avec succès. Statut : {ticket.statut}')
                return redirect('profil_entite')
            else:
                messages.error(request, 'Veuillez corriger les erreurs ci-dessous.')

        context = {'form': form, 'ticket': ticket}
        return render(request, 'tikets/entité_affect_page.html', context)
    else:
        messages.error(request, "Vous n'avez pas les autorisations nécessaires pour assigner ce ticket.")
        return redirect('hd_home_page')