Method POST don't work to add data

When i try to post data with submit button, i get nothing no reverse to (/) and no data send to the database. Normaly, i am expecting to submit data with datetimefield auto and auto add. when it finished (data sent), i will redirect the page to the previous page(/).

html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!--
    <title>CRM Youtube</title>
    CSS only -->
    <title>Groupe Utilisateurs</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

    <style>

		#logo{
		}

		body{
			background-color: #ebeff5;
		}


		#total-orders{
			background-color: #4cb4c7;
		}


		#orders-delivered{
			background-color: #7abecc;
		}

		#orders-pending{
			background-color: #7CD1C0;
		}

	</style>

</head>
<body>
<!DOCTYPE html>

<!-- YouTube or Website - CodingLab -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!---<title>Sidebar Menu for Admin Dashboard</title>-->
    <!--link rel="stylesheet"  href="/static/css/stylev3adminspec.css"-->
    <!-- Fontawesome CDN Link -->
    <link rel="stylesheet"  href="/static/css/all.min.css">
    <!--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />-->
    <!---NEW---->
    <title> Tableau de bord </title>
    <!-- MDB icon -->
    <link rel="icon" href="img/mdb-favicon.ico" type="image/x-icon" />
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"
    />
    <!-- Google Fonts Roboto -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700;900&display=swap"
    />
    <!-- MDB -->
    <link rel="stylesheet" href="/static/css/mdb.min.css" >
    <script src="https://code.jquery.com/jquery-3.7.1.slim.min.js" integrity="sha256-kmHvs0B+OpCW5GVHUNjv9rOmY0IvSIRcf7zGUDTDQM8=" crossorigin="anonymous">
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light font-weight-bold text-uppercase">
      <!---->
        <!---->
      <!---->
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
          <i class="fa fa-circle" aria-hidden="true"></i>
          <a class="navbar-brand" href="/AccessAdmin/EspaceAdministrator" style="font-weight-bold" >TDB</a>
          <div class="collapse navbar-collapse">
          </div>
          <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
              <li class="nav-item active">
                <a class="nav-link" >Ajout utilisateur </a>
              </li>
            </ul>
          </div>
          <ul class="navbar-nav d-flex flex-row">
            
            <li class="nav-item">
              <span class="nav-link">admin</span>
            </li>
            

            <li class="nav-item me-3 me-lg-0 dropdown">
              <a data-mdb-dropdown-init
                 class="nav-link dropdown-toggle"
                 href="#"
                 id="navbarDropdown"
                 role="button"
                 aria-expanded="false"
              >
                <i class="fas fa-user" id="usericone"></i>
              </a>

              <ul class="dropdown-menu">
                <li>
                  
                  <a class="dropdown-item" href="/auth/logout">Déconnexion</a>
                  
                </li>
                <li><a class="dropdown-item" href="/auth/logout"><i class="fa fa-pencil fa-fw"></i> Edit</a></li>
                <li><a class="dropdown-item" href="#"><i class="fa fa-trash-o fa-fw"></i> Delete</a></li>
                <li><a class="dropdown-item" href="#"><i class="fa fa-ban fa-fw"></i> Ban</a></li>
                <li class="divider"></li>
                <li><a class="dropdown-item" href="#"><i class="fa fa-unlock"></i> Make admin</a></li>
              </ul>

            </li>
          </ul>
    </nav>
    <script src="/static/js/mdb.umd.min.js"></script>
    <script src="/static/src/script3adminspec.js"></script>
  </body>
</html>



	<br>

<form action="" method="POST">
	<input type="hidden" name="csrfmiddlewaretoken" value="FZIspgaZwnt4fzOZqWnbK1RVceKTQyLbC68Nvc1F9rUygsP9Lcrymw4SEEbcwQ9x">
	<div class="row">
		<div class="col-md">
			<div class="card card-body" >
				<h5>Informations</h5>
				<hr>

				<br>
				<fieldset>
					<label for="IDF_GROUPE_USER">Nom du groupe :</label>

					<!--input name="IDF_GROUPE_USER" type="text" id="IDF_GROUPE_USER"  size="35"
							   placeholder="Nom du groupe" tabindex="1" >
					-->

					<select name="IDF_GROUPE_USER" id="IDF_GROUPE_USER"
							   tabindex="1" >*
						
							<option value=1>prends ma main</option>
						
							<option value=2>take way</option>
						
							<option value=3>dffhgh</option>
						
							<option value=4>dieu</option>
						
							<option value=5>pour cause</option>
						
							<option value=6>fghj</option>
						
							<option value=7>hhkkk</option>
						
							<option value=8>ferier</option>
						
							<option value=9>dfgg</option>
						
							<option value=10>derier</option>
						
							<option value=11>fare</option>
						
							<option value=12>fghgh</option>
						
							<option value=13>fghgh</option>
						
							<option value=14>prenez</option>
						
							<option value=15>der</option>
						
					</select>
				</fieldset>

				<br>
				<fieldset>
					<label for="user">username :</label>
					<input name="user" type="text" id="user"  size="35"
							   placeholder="User" tabindex="2" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="LOGIN">LOGIN :</label>
					<input name="LOGIN" type="text" id="LOGIN"  size="35"
							   placeholder="LOGIN" tabindex="3" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="name">Nom :</label>
					<input name="name" type="text" id="name"  size="35"
							   placeholder="Nom" tabindex="4" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="prenom">Prenom :</label>
					<input name="prenom" type="text" id="prenom"  size="35"
							   placeholder="Prenom" tabindex="5" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="MOtpasse">Password :</label>
					<input name="MOtpasse" type="password" id="MOtpasse"  size="35"
							   placeholder="Password" tabindex="6" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="USERCONNECTE">Connecté ? :</label>
					<select name="USERCONNECTE"  id="USERCONNECTE"
							tabindex="7"  >*
							<option value="true">Oui</option>
							<option value ="false">Non</option>
					</select>
				</fieldset>

				<br>
				<fieldset>
					<label for="COMPTEACTIF">Compte Actif ? :</label>
					<select name="COMPTEACTIF" id="COMPTEACTIF"
							   tabindex="8" >*
							<option value=1>Oui</option>
							<option value =2>Non</option>
					</select>
				</fieldset>

				<br>
				<fieldset>
					<label for="mOtpassWorkFlow"> mOtpassWorkFlow</label>
					<input name="mOtpassWorkFlow" type="password" id="mOtpassWorkFlow"  size="35"
							   placeholder="Pwd Wflow" tabindex="9" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="CODeSecret"> CODeSecret</label>
					<input name="CODeSecret" type="password" id="CODeSecret"  size="35"
							   placeholder="Code Secret" tabindex="10" >*
				</fieldset>


				<br>
				<fieldset>
					<label for="EMAIL"> EMAIL</label>
					<input name="EMAIL" type="email" id="EMAIL"  size="35"
							   placeholder="EMAIL" tabindex="11" >*
				</fieldset>
				<br>
				<fieldset>
					<label for="Telephone"> Telephone </label>
					<input name="Telephone" type="tel" id="Telephone"  size="35"
							   placeholder="Telephone" tabindex="12" >*
				</fieldset>
				<br>
				<fieldset>
					<label for="Activer"> Activer ?</label>
					<input name="Activer" type="checkbox" id="Activer"
							   value="Activer" tabindex="13" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="PROFILSIGN"> PROFILSIGN</label>
					<input name="Activer" type="text" id="PROFILSIGN"  size="35"
							   placeholder="PROFIL SIGN" tabindex="14" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="DATEEXPIRATION"> DATE EXPIRATION</label>
					<input name="DATEEXPIRATION" type="date" id="DATEEXPIRATION"  size="35"
							   placeholder="DATE EXPIRATION" tabindex="15" >*
				</fieldset>


				<br>
				<fieldset>
					<label for="PICTURE"> PICTURE</label>
					<input name="PICTURE" type="image" id="PICTURE"  size="35"
							   placeholder="PICTURE" tabindex="16" >*
				</fieldset>


				<br>
				<fieldset>
					<label for="DROIT"> DROIT</label>
					<input name="DROIT" type="text" id="DROIT"  size="35"
							   placeholder="DROIT" tabindex="17" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="MAJ"> MAJ</label>
					<input name="MAJ" type="text" id="MAJ"  size="35"
							   placeholder="MAJ" tabindex="18" >*
				</fieldset>

				<br>
				<fieldset>
					<label for="NUMCLT"> NUMCLT</label>
					<input name="NUMCLT" type="text" id="NUMCLT"  size="35"
							   placeholder="NUMCLT" tabindex="19" >*
				</fieldset>


				<br>
				<fieldset>
					<label for="Multisite"> Multisite</label>

					<select name="Multisite" id="Multisite"
							   tabindex="20" >*
							<option value=1>Oui</option>
							<option value =2>Non</option>
					</select>
				</fieldset>

				<fieldset>
					<input name="created_at" type="date" id="created_at"  placeholder=""
						   tabindex="21" style="display:None;">
				</fieldset>
				<fieldset>
					<input name="updated_at" type="date" id="updated_at" value="5 octobre 2024 21:02"  placeholder=""
						   tabindex="22" style="display:None;">
				</fieldset>
				<fieldset>
					<input name="UTIL_CREATION" type="text" id="UTIL_CREATION" value="admin" size="35"
						   placeholder="" tabindex="23" style="display:None;">
				</fieldset>
				<fieldset>
					<input name="UTIL_MODIF" type="text" id="UTIL_MODIF" value="admin" size="35" placeholder=""
						   tabindex="24" style="display:None;">
				</fieldset>
				<fieldset>
					<input name="Soc_sigle" type="text" id="Soc_sigle" value="ABI" size="35" placeholder=""
						   tabindex="25" style="display:None;">
				</fieldset>

			</div>

		</div>



		<div class="col-md">
			<div class="card card-body" style="width:200px; margin-left:50%;">
				<!--<h5>Client:</h5>-->

				<hr>

				
				<button class="btn btn-outline-success  btn-sm btn-block" href=""
				   style="font-size: 10px;" type="submit" value="submit">
				Valider
				</button>
				<button class="btn btn-outline-info  btn-sm btn-block"  style="font-size: 10px;" id="myButton">
						Quitter
				</button>


				

			</div>

		</div>

	</div>

	<script>

            const buttons = document.getElementsByTagName("button");
    		var clicked = false
            var b1 = document.querySelector(".b1")
            var b2 = document.querySelector(".b2")
            var b3 = document.querySelector(".b3")
            var b5 = document.querySelector(".b5")

    		function hideButtons( button1, button2, button3) {
            	clicked = false
                for (button of buttons) {
                	button.style.display = "inline";
                }
                button1.style.display = (clicked ? "inline" : "none")
                button2.style.display = (clicked ? "inline" : "none")
                button3.style.display = (clicked ? "inline" : "none")
                clicked = !clicked
                }
                b1.addEventListener("click", () => {hideButtons(b2, b3, b1)})

                function hideButtons1(button1, button2, button3) {

                	clicked = false
                    for (button of buttons) {
                    	button.style.display = "none";
                    }
                    button1.style.display = "inline";
                    button2.style.display = "inline";
                    button3.style.display = "inline";
                    clicked = !clicked
                    }

                    b5.addEventListener("click", () => {
                    hideButtons1(b1, b2, b3)})

			function goBack() {
  					window.history.back()
				}


  			document.getElementById("myButton").addEventListener("click", function() {
    			window.history.back();
  			});


    </script>

</form>


<br>

<div class="row">
	<div class="col-md">
		<div class="card card-body">
			<table class="table table-sm">
				<tr>
					<th>ID</th>
					<th>login</th>
					<th>Prenom et Nom</th>
					<th>Telephone</th>
					<th>EMAIL</th>
					<th>Util création</th>
					<th>Date création</th>
					<th>Util modification</th>
					<th>Date modification</th>
				</tr>

				

			</table>
		</div>
	</div>
</div>
<!--https://stackoverflow.com/questions/72089986/how-to-toggle-between-button-display -->

<hr>
<h1>Footer</h1>
</body>
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</html>

views:

def UserAjouter(request):
    pk = request.user.id # l'id du user qui est entrainde faire la création
    groupe = f_groupe_user.objects.get(IDF_GROUPE_USER=pk)  # le groupe utilisateur du créateur du user
    scuser = request.user.id
    aze = "Ajout utilisateur"
    sEtat = "crea" # en mode création
    utilisateur = groupe.f_utilisateur_set.all() #la liste des utilisateur du même groupe créateur
    groupes = f_groupe_user.objects.all() # la liste de tous les groupes

    print(f"La valeur du groupe  dans GroupeAjouter est : {utilisateur}")
    print(f"La valeur du scuser est : {scuser}")

    form=f_utilisateur_userForm()
    if request.method=="POST":
        #print(localize(datetime.now()))
        #print(localize(datetime()))
        form.created_at = datetime.now()
        form.updated_at = datetime.now()
        form.UTIL_CREATION = settings.WCURUSER
        form.UTIL_MODIF = settings.WCURUSER
        form.Soc_sigle = settings.WSOCGEN
        form=f_utilisateur_userForm(request.POST)
        print("Lheure locale est:")
        print(localize(datetime.now()))
        print(request.method)
        if form.has_changed():
            print("The following fields changed: %s" % ", ".join(form.changed_data))

        #print(form.cleaned_data)

        if form.is_valid():
            #print(form.changed_data)
            form.save()
            return redirect('/')
        else:
            print("")
    context = {'form':form, 'groupe': groupe, 'aze': aze, 'sEtat': sEtat, 'utilisateur': utilisateur, 'scuser': scuser,
               'groupes': groupes}
    return render(request, 'appMenuAdministrator/L_liste_GroupeUtilisateur/FicheCreaUser.html',context )

models:

class f_utilisateur(models.Model):   # Crée un lien entre le user et les services, le 'name' étant le nom du service
    IDF_UTILISATEUR=models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    LOGIN= models.CharField(max_length=120)
    name = models.CharField(max_length=120)
    MOtpasse= models.CharField(max_length=120)
    USERCONNECTE=models.BooleanField()
    COMPTEACTIF=models.IntegerField()
    prenom= models.CharField(max_length=120)
    IDF_GROUPE_USER=models.ForeignKey(f_groupe_user, on_delete=models.CASCADE, null=True)
    mOtpassWorkFlow=models.CharField(max_length=120, blank=True)
    CODeSecret=models.CharField(max_length=120, blank=True)
    EMAIL=models.CharField(max_length=120, blank=True)
    Telephone = models.CharField(max_length=120, blank=True)
    Activer=models.IntegerField()
    PROFILSIGN=models.CharField(max_length=120, blank=True)
    DATEEXPIRATION=models.DateTimeField(blank=True)
    PICTURE=models.FileField(upload_to=user_directory_pathPictureUser, blank=True)
    DROIT=models.IntegerField(blank=True)
    MAJ=models.IntegerField()
    NUMCLT=models.CharField(max_length=120)
    UTIL_CREATION=models.CharField(max_length=120)
    UTIL_MODIF=models.CharField(max_length=120)
    Soc_sigle=models.CharField(max_length=120, blank=True)
    Multisite=models.BooleanField()
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at= models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

forms:

class f_utilisateur_userForm(forms.ModelForm):
    class Meta:
        model = f_utilisateur
        fields = ['user', 'LOGIN', 'name', 'prenom', 'MOtpasse', 'USERCONNECTE', 'COMPTEACTIF', 'IDF_GROUPE_USER', 'mOtpassWorkFlow', 'CODeSecret', 'EMAIL', 'Telephone',
                  'Activer', 'PROFILSIGN', 'DATEEXPIRATION','PICTURE', 'DROIT', 'MAJ', 'NUMCLT','Multisite','UTIL_CREATION', 'UTIL_MODIF','Soc_sigle']

        labels = {'user': 'username', 'LOGIN':'LOGIN', 'name':'Nom', 'prenom':'Prenom', 'MOtpasse':'Password', 'USERCONNECTE': 'CONNECTE ?', 'COMPTEACTIF':'ACTIF ?',
                  'IDF_GROUPE_USER': 'GROUPE', 'mOtpassWorkFlow':'Pwd WFlow', 'CODeSecret':'Code Secret', 'EMAIL':'EMAIL', 'Telephone': 'Tel.',
                  'Activer':'Activer', 'PROFILSIGN':'PROFIL SIGN', 'DATEEXPIRATION': 'DATE EXPIRATION','PICTURE': 'Photo', 'DROIT': 'DROIT', 'MAJ': 'MAJ',
                  'NUMCLT' : 'NUMCLT','Multisite': 'Multisite?', 'created_at': 'Date de création',  'updated_at': 'Date de modification',
                  'UTIL_CREATION': 'UTIL CREATION', 'UTIL_MODIF': 'UTIL MODIF', 'Soc_sigle':',Societe'}

        widgets={
            'IDF_GROUPE_USER':forms.Select(attrs={'class':'form-control'}),
        }

urls:

from django.urls import path, re_path, reverse
from . import views

from .views import Registrations_Create, registrations_success

urlpatterns=[
 path("Groupe_Users/add/", views.GroupeAjouter, name='GroupeAjouter'),
]

Please help to check.

I dont see any form element in your template. You need a form element with a method attribute set to POST.

I suggest you read the documentation for form handling if you have not.

Also, you can access data related to the authenticated user in you template by simply using {{ request.user.pk }}. No need to query it in the view and pass it to the context dictionary.

I also suggest reading this documentation because your code looks very messy:

In addition to the response above (most significantly the issue that you’re not rendering your form, you’ve hard-coded your form fields), you’ve got a lot of unnecessary code in your view:

The last line in this quoted block, where you’re creating a new instance of the f_utilisateur_userForm and binding it to the POST data, overwrites all of the previous lines where you have set values on the form object.

The 5 assignment statements above this creation of the form object is all unnecessary and useless code.

Finally, if your form is not valid, you want to render the invalid form for it to display the errors that were identified.

In addition to the two links mentioned previously, you’ll probably also want to spend some time reviewing The Forms API | Django documentation | Django

@abbasj i don’t understand what you mean by ‘I dont see any form element in your template’ because at the beginning of the html body i put this

<form action="" method="POST">. 

Please, could clearing what you want to say for me. thank you for you help by document link. You can also see the button with type=‘submit’.

The original issue with the display of your post is that you had an extra line of ```, which messed up your formatting of your code. Your HTML wasn’t completely visible. (I took the liberty of fixing it.)

Likewise, in this most recent reply, the html you supplied isn’t visible. (Look at your post.) Within a single line, you want to surround the html with single backticks - `.

Thanks @KenWhitesell .

Hello!

Sorry, I was reading on my phone and missed the html form element. Now that I’m on my laptop, here are some concrete tips.

You’r view should be like this:

def UserAjouter(request):
    groupe = f_groupe_user.objects.get(IDF_GROUPE_USER=pk)  # le groupe utilisateur du créateur du user
    aze = "Ajout utilisateur"
    sEtat = "crea" # en mode création
    utilisateur = groupe.f_utilisateur_set.all() #la liste des utilisateur du même groupe créateur
    groupes = f_groupe_user.objects.all() # la liste de tous les groupes

    if request.method=="POST":
        
       form=f_utilisateur_userForm(request.POST)
        
       if form.has_changed():
          print("The following fields changed: %s" % ", ".join(form.changed_data))

       if form.is_valid():
          form.save()
          return redirect('The url that you want to re-direct to')
       else:
            print("")
   else:
      form = f_utilisateur_userForm()

    context = {'form':form, 'groupe': groupe, 'aze': aze, 'sEtat': sEtat, 'utilisateur': utilisateur, 'scuser': scuser,
             'groupes': groupes}
    return render(request, 'appMenuAdministrator/L_liste_GroupeUtilisateur/FicheCreaUser.html',context )

Key points:

  1. Only initialize the form class once and bind the POST data to it. You don’t need all the other assignments. It’s unnecessary and takes space in your computers memory.
  2. After validating the form and saving the form, you need to redirect to a URL. If you have multiple apps, the URL can be generated like this: return redirect(“app_names_space:View_name”). This will dynamically generate the URL. Don’t ever hard cod URLs anywhere in you’r code since it can change.
  3. Notice that I added an else statement to handle the case where you don’t have a POST request. This will handle the GET request where the form is just displayed without any actions.
  4. There is no point (at least that I can see) to pass string objects to the context dictionary. If you want to add a text in the template, just write it in the template. Or if you have a certain reason for doing that, please let me know.
  5. f_groupe_user in you view seem to be a model that you’re trying to query, but the model does not exist in you models file. The same with f_groupe_user, it seem to be a model that does not exist in you model (I assume you have shared all you’r models).

You’r template should be something likes this:

<form method = "POST">
{% csrf_token %}
{{ form.as_div }}
<button type="submit">Submit the form</button>
</form>

This is basically everything you need, if you’re using ModelForms. In you’r template, you have hard coded pretty much everything. Don’t! Instead, work on you form class and then you can render all you’r choices, form fields etc by the template code I provided.

The {% csrf_token %} is very important and should be added to all you’r forms.

I strongly recommend reading more about forms here:

And when you have a understanding of forms, you can continue and read about model forms:

Some general tips:

  1. Create a base template that you then are extending to other templates in the template you provided minus all the CSS, HTML code inside the body tags and the JavaScript codes.
  2. Separate your styling from the main template.
  3. Separate JavaScript form your base template.
  4. Use better naming of you’r model, model fields, views etc. I linked an article about this earlier.

@abbasj thank you. a lot

In my model i have f_groupe_user and f_utilisateur.

In the model f_utilisateur, i have the fields
created_at
updated_at
UTIL_CREATION
UTIL_MODIF
Soc_sigle

class f_utilisateur(models.Model):   # Crée un lien entre le user et les services, le 'name' étant le nom du service
    IDF_UTILISATEUR=models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    LOGIN= models.CharField(max_length=120)
    name = models.CharField(max_length=120)
    MOtpasse= models.CharField(max_length=120)
    USERCONNECTE=models.BooleanField()
    COMPTEACTIF=models.IntegerField()
    prenom= models.CharField(max_length=120)
    IDF_GROUPE_USER=models.ForeignKey(f_groupe_user, on_delete=models.CASCADE, null=True)
    mOtpassWorkFlow=models.CharField(max_length=120, blank=True)
    CODeSecret=models.CharField(max_length=120, blank=True)
    EMAIL=models.CharField(max_length=120, blank=True)
    Telephone = models.CharField(max_length=120, blank=True)
    Activer=models.IntegerField()
    PROFILSIGN=models.CharField(max_length=120, blank=True)
    DATEEXPIRATION=models.DateTimeField(blank=True)
    PICTURE=models.FileField(upload_to=user_directory_pathPictureUser, blank=True)
    DROIT=models.IntegerField(blank=True)
    MAJ=models.IntegerField()
    NUMCLT=models.CharField(max_length=120)
    UTIL_CREATION=models.CharField(max_length=120)
    UTIL_MODIF=models.CharField(max_length=120)
    Soc_sigle=models.CharField(max_length=120, blank=True)
    Multisite=models.BooleanField()
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at= models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

I need to add data for this 4 fields but the are not html displayed fields.

The data for the fields UTIL_CREATION, UTIL_MODIF, Soc_sigle are initialize into my setting file.

For the 2 other files:
created_at=models.DateTimeField(auto_now_add=True)
updated_at= models.DateTimeField(auto_now=True)
they are auto input data so i am trying to initialize them too.

It is what i am trying to do here:

form.created_at = datetime.now()
form.updated_at = datetime.now()
form.UTIL_CREATION = settings.WCURUSER
form.UTIL_MODIF = settings.WCURUSER
form.Soc_sigle = settings.WSOCGEN
form=f_utilisateur_userForm(request.POST)

@KenWhitesell explained that the f_utilisateur_userForm and binding it to the POST data, overwrites all of the previous lines.
but i need to input these datas to the database too with the data form.
Thank you to reverse.

Hello @abbasj and @KenWhitesell ,

Thank you for the docs you advise me. It helps me so much.

I change my form, view, html like following but the method “POST” into the html file change when running to the GET method. Then the form fields is not showing only the button “submit”. I test it in my terminal. Please help to fix.

Please, help to fix.

Form:

class f_utilisateurForm(forms.ModelForm):

    class Meta:
        model = f_utilisateur
        #fields = "__all__"
        exclude = ["UTIL_CREATION", "UTIL_MODIF", "Soc_sigle", "created_at", "updated_at"]
        widgets={
            'IDF_GROUPE_USER':           forms.Select(attrs={'class':'form-control', 'label':'Groupe'}),
            'user':                      forms.Select(attrs={'class': 'form-control', 'label':'Username'}),
            'MAJ':                       forms.CheckboxInput(attrs={'class': 'form-control', 'label':'MAJ'}),
            'Multisite':                 forms.CheckboxInput(attrs={'class': 'form-control', 'label':'Multi site'}),
            'DATEEXPIRATION':            forms.DateTimeInput(attrs={'label':'Date Expir.'}),
            'EMAIL':                     forms.EmailInput(attrs={'class': 'form-control', 'label':'Email', 'size':40,'placeholder': 'Entrer ton jmjabisoft Email','pattern':".+@jmjabisoft\.com" , 'required': 'False'}),
            'CODeSecret':                forms.PasswordInput(attrs={'class': 'form-control','label':'Code Secret', 'size':12,'placeholder': 'Code Secret', 'required': 'False'}),
            'mOtpassWorkFlow':           forms.PasswordInput(attrs={'class': 'form-control','label':'Pwd WF', 'size':12,'placeholder': 'Pw WF', 'required': 'False'}),
            'COMPTEACTIF':               forms.CheckboxInput(attrs={'class': 'form-control', 'label':'Compte Actif'}),
            'MOtpasse':                  forms.PasswordInput(attrs={'class': 'form-control', 'label':'Pwd User', 'size':12,'placeholder': 'Password', 'required': 'False'}),
            #'PICTURE':                   forms.ImageField(attrs={'class': 'form-control', 'label':'Pwd User'})
        }

Model:

class f_utilisateur(models.Model):   # Crée un lien entre le user et les services, le 'name' étant le nom du service
    IDF_UTILISATEUR=models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    LOGIN= models.CharField(max_length=120)
    name = models.CharField(max_length=120)
    MOtpasse= models.CharField(max_length=120)
    USERCONNECTE=models.BooleanField()
    COMPTEACTIF=models.BooleanField()
    prenom= models.CharField(max_length=120)
    IDF_GROUPE_USER=models.ForeignKey(f_groupe_user, on_delete=models.CASCADE, null=True)
    mOtpassWorkFlow=models.CharField(max_length=120, blank=True)
    CODeSecret=models.CharField(max_length=120, blank=True)
    EMAIL=models.CharField(max_length=120, blank=True)
    Telephone = models.CharField(max_length=120, blank=True)
    Activer=models.BooleanField()
    PROFILSIGN=models.CharField(max_length=120, blank=True)
    DATEEXPIRATION=models.DateTimeField(blank=True)
    PICTURE=models.FileField(upload_to=user_directory_pathPictureUser, blank=True)
    DROIT=models.IntegerField(blank=True)
    MAJ=models.BooleanField()
    NUMCLT=models.CharField(max_length=120)
    UTIL_CREATION=models.CharField(max_length=120)
    UTIL_MODIF=models.CharField(max_length=120)
    Soc_sigle=models.CharField(max_length=120, blank=True)
    Multisite=models.BooleanField()
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at= models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

view:

def UtilAjouter(request):
    pk = request.user.id # l'id du user qui est entrainde faire la création
    groupe = f_groupe_user.objects.get(IDF_GROUPE_USER=pk)  # le groupe utilisateur du créateur du user
    scuser = request.user.id
    aze = "Ajout utilisateur"
    sEtat = "crea" # en mode création
    utilisateur = groupe.f_utilisateur_set.all() #la liste des utilisateur du même groupe créateur
    groupes = f_groupe_user.objects.all() # la liste de tous les groupes
    users = User.objects.all()  # la liste de tous les groupes

    print(f"La valeur du groupe  dans GroupeAjouter est : {utilisateur}")
    print(f"La valeur du scuser est : {scuser}")

    form=f_utilisateurForm()
    print(f"La valeur du form est : {form}")
    if request.method=="POST":
        print("LA methode est post")
        form=f_utilisateurForm(request.POST)

        if form.has_changed():
            print("The following fields changed: %s" % ", ".join(form.changed_data))

        #print(form.cleaned_data)

        if form.is_valid():
            #print(form.changed_data)
            d_utilisateur=form.save(commit=False)
            d_utilisateur.UTIL_CREATION = settings.WCURUSER,
            d_utilisateur.UTIL_MODIF    = settings.WCURUSER,
            d_utilisateur.Soc_sigle     = settings.WSOCGEN,
            d_utilisateur.created_at    = datetime.now(),
            d_utilisateur.updated_at    = datetime.now(),
            d_utilisateur.save()
            form.save_m2m()

            return redirect('/')
        else:
            print("Les champs non valides : %s" % ", ".join(form.errors.as_data()))
    else:
        print("LA methode n'est pas post")
        form = f_utilisateurForm()


    context = {'groupe': groupe, 'aze': aze, 'sEtat': sEtat, 'utilisateur': utilisateur, 'scuser': scuser,
           'groupes': groupes, 'users':users}
    return render(request, 'appMenuAdministrator/L_liste_GroupeUtilisateur/FicheCreaUtil.html', context)

html:

{% extends 'appMenuAdministrator/mainadmin.html' %}
{% block content %}

<form method = "POST">
{% csrf_token %}
{{ form.as_div }}
<button type="submit">Submit the form</button>
</form>

{% endblock content%}

My Terminal:

[07/Dec/2024 20:46:50] "GET /AccessAdmin/EspaceAdministrator HTTP/1.1" 200 7045
[07/Dec/2024 20:46:50] "GET /static/css/all.min.css HTTP/1.1" 404 1985
La valeur du cuser est : 1
[07/Dec/2024 20:46:54] "GET /AccessAdmin/Groupe_Users/ HTTP/1.1" 200 12710
[07/Dec/2024 20:46:54] "GET /static/css/all.min.css HTTP/1.1" 404 1985
La valeur du groupe  dans GroupeAjouter est : <QuerySet []>
La valeur du scuser est : 1
La valeur du form est : <div>
    <label for="id_user">User :</label>



<select name="user" class="form-control" label="Username" required id="id_user">
  <option value="" selected>---------</option>

  <option value="1">admin</option>

  <option value="2">kof</option>

  <option value="4">ful</option>

  <option value="5">HOU</option>

  <option value="7">fulberto22@gmail.com</option>

</select>

</div>

  <div>
    <label for="id_LOGIN">LOGIN :</label>



<input type="text" name="LOGIN" maxlength="120" required id="id_LOGIN">

</div>

  <div>
    <label for="id_name">Name :</label>



<input type="text" name="name" maxlength="120" required id="id_name">

</div>

  <div>
    <label for="id_MOtpasse">MOtpasse :</label>



<input type="password" name="MOtpasse" class="form-control" label="Pwd User" size="12" placeholder="Password" required maxlength="120" id="id_MOtpasse">

</div>

  <div>
    <label for="id_USERCONNECTE">USERCONNECTE :</label>



<input type="checkbox" name="USERCONNECTE" id="id_USERCONNECTE">

</div>

  <div>
    <label for="id_COMPTEACTIF">COMPTEACTIF :</label>



<input type="checkbox" name="COMPTEACTIF" class="form-control" label="Compte Actif" id="id_COMPTEACTIF">

</div>

  <div>
    <label for="id_prenom">Prenom :</label>



<input type="text" name="prenom" maxlength="120" required id="id_prenom">

</div>

  <div>
    <label for="id_IDF_GROUPE_USER">IDF GROUPE USER :</label>



<select name="IDF_GROUPE_USER" class="form-control" label="Groupe" required id="id_IDF_GROUPE_USER">
  <option value="" selected>---------</option>

  <option value="1">prends ma main</option>

  <option value="2">take way</option>

  <option value="3">dffhgh</option>

  <option value="4">dieu</option>

  <option value="5">pour cause</option>

  <option value="6">fghj</option>

  <option value="7">hhkkk</option>

  <option value="8">ferier</option>

  <option value="9">dfgg</option>

  <option value="10">derier</option>

  <option value="11">fare</option>

  <option value="12">fghgh</option>

  <option value="13">fghgh</option>

  <option value="14">prenez</option>

  <option value="15">der</option>

</select>

</div>

  <div>
    <label for="id_mOtpassWorkFlow">MOtpassWorkFlow :</label>



<input type="password" name="mOtpassWorkFlow" class="form-control" label="Pwd WF" size="12" placeholder="Pw WF" required="False" maxlength="120" id="id_mOtpassWork
Flow">

</div>

  <div>
    <label for="id_CODeSecret">CODeSecret :</label>



<input type="password" name="CODeSecret" class="form-control" label="Code Secret" size="12" placeholder="Code Secret" required="False" maxlength="120" id="id_CODeS
ecret">

</div>

  <div>
    <label for="id_EMAIL">EMAIL :</label>



<input type="email" name="EMAIL" class="form-control" label="Email" size="40" placeholder="Entrer ton jmjabisoft Email" pattern=".+@jmjabisoft\.com" required="Fals
e" maxlength="120" id="id_EMAIL">

</div>

  <div>
    <label for="id_Telephone">Telephone :</label>



<input type="text" name="Telephone" maxlength="120" id="id_Telephone">

</div>

  <div>
    <label for="id_Activer">Activer :</label>



<input type="checkbox" name="Activer" id="id_Activer">

</div>

  <div>
    <label for="id_PROFILSIGN">PROFILSIGN :</label>



<input type="text" name="PROFILSIGN" maxlength="120" id="id_PROFILSIGN">

</div>

  <div>
    <label for="id_DATEEXPIRATION">DATEEXPIRATION :</label>



<input type="text" name="DATEEXPIRATION" label="Date Expir." id="id_DATEEXPIRATION">

</div>

  <div>
    <label for="id_PICTURE">PICTURE :</label>



<input type="file" name="PICTURE" id="id_PICTURE">

</div>

  <div>
    <label for="id_DROIT">DROIT :</label>



<input type="number" name="DROIT" id="id_DROIT">

</div>

  <div>
    <label for="id_MAJ">MAJ :</label>



<input type="checkbox" name="MAJ" class="form-control" label="MAJ" id="id_MAJ">

</div>

  <div>
    <label for="id_NUMCLT">NUMCLT :</label>



<input type="text" name="NUMCLT" maxlength="120" required id="id_NUMCLT">

</div>

  <div>
    <label for="id_Multisite">Multisite :</label>



<input type="checkbox" name="Multisite" class="form-control" label="Multi site" id="id_Multisite">



</div>
LA methode n'est pas post

Your template has:

But you’re not passing the form in to the render in the context: