How to put the username of the logged-in user in the databse each time a form is submitted

how to retrieve data from database of a particular user after login in php
php get username of logged in user
how to display username after login in html5
display username after login using session php
how to get user id after login in php
how to display user profile after login in php
php session for multiple users
php get user id from session

I have an application where a user can submit a form which goes into the database (POSTGRES).

I want to be able to automatically send the username of the user logged in to the same database, so i can keep track of who is submitting. (I do not want to put a form line with the username, i want this to be dealt with in the back-end).

what I managed to do is get the user-id, but it stays null, and I do not know how to get the username in the database and to complete it at each submission.

I hope I am clear,

thanls guys.

Here is my code

models.py

from django.db import models as db_models
from django.contrib.auth.models import User
from django.contrib.gis.db import models


class Fertidb(models.Model):
    user = db_models.ManytoManyField(User, on_delete=models.CASCADE)
    area = models.IntegerField()
    plot = models.FileField(upload_to='KML_FILES', blank=True)

    def __str__(self):
        return f' Parcelles de {self.user.username}'

forms.py

from django import forms
from django.contrib.auth.models import User
from .models import Fertidb


class FertidbForm(forms.ModelForm):
    class Meta:
        model = Fertidb
        labels = {
            "plot": "Importez votre fichier KML"
        }
        fields = ['culture', 'area', 'plot']

views.py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import FertidbForm
from django.contrib.auth.models import User

title = 'FERTISAT'


@login_required
def fertisatmap(request):

    mapbox_access_token = 'pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w'
    if request.method == "POST":
        o_form = FertidbForm(request.POST, request.FILES)
        if o_form.is_valid():
            o_form.save(commit=False)
            o_form.user = request.user.username()
            messages.success(request, f'Vos informations ont été envoyées')
            return redirect('fertisat-map')
    else:
        o_form = FertidbForm()
    context = {'title': title, 'o_form': o_form}
    return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token})

Try to update your view like so:

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import FertidbForm
from django.contrib.auth.models import User

title = 'FERTISAT'


@login_required
def fertisatmap(request):

    mapbox_access_token = 'pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w'
    if request.method == "POST":
        o_form = FertidbForm(request.POST, request.FILES)
        if o_form.is_valid():
            fertidb = o_form.save(commit=False)
            fertidb.user = request.user
            fertidb.save()
            messages.success(request, f'Vos informations ont été envoyées')
            return redirect('fertisat-map')
    else:
        o_form = FertidbForm()
    context = {'title': title, 'o_form': o_form}
    return render(request, 'fertisat/fertisatmap.html ', context, {'mapbox_access_token': mapbox_access_token})

(commit=False) use for creating the model instance without submit to database, then assign current user to your new model instance fertidb.user = request.user and then call .save() to commit your data to database


Btw, mapbox_access_token suppose to stay inside settings.py in case you want to load it from environment variable when deploy production. like so:

settings.py

MAPBOX_ACCESS_TOKEN="pk.eyJ1IjoiaGFtemFiIiwiYSI6ImNrMHdwYmQ2bzA2OGYzbHB1Z292eGxneDgifQ.rGPQjaoWuOdnq_UdxAfQ_w"

views.py

from django.conf import settings

...
def fertisatmap(request):
    mapbox_access_token = settings.MAPBOX_ACCESS_TOKEN

Hope that helps!

How to display logged in user information in PHP ?, The session variables are used to display logged in user information in PHP. of the user, and then sends the entered data into the database, once the submit button is clicked. The size can be adjusted as per the requirement however, 100 is sufficient. $query = "INSERT INTO users (username, email, password). Log usage of forms and reports. This utility lets you track who opens each form and report in your database, and when. Logging gives feedback on how people use your application, and may help diagnose crashes or corruptions. To use it, copy the logging table and code from the sample database, and set two properties for each form or report.


There are two issues here:

1. In your Model, you want a User, but in your form, you are assigning it the username, which I think is a string.

user = db_models.ManytoManyField(User, on_delete=models.CASCADE)

and

o_form.user = request.user.username()

Just change the second line to o_form.user = request.user.

2. You are not saving the user anyway.

You have to save your model again after you assign the user.

How to Implement Multiple User Types with Django, model and adding boolean flags such as is_student and is_staff work for most cases. Permissions can be managed at a higher level using view decorators. In this video, you will see how you can welcome your user when they login to the Microsoft Access Database. It's very easy to do by using a temporary variable.


Thanks fo the help guys.

@Toan Quoc Ho thank you I made the modifications but I still have a problem. The database displays the user_id, but I would like it to display the username.

I guess my problem is in the model file. How do I modify the following, so I get the username in the database.

user=deb_models.ForeignKey(User,on_delete)models.CASCADE) puts the user_id -> I would like to have the username. How do I call it ?

models.py

*from django.db import models as db_models
from django.contrib.auth.models import User
from django.contrib.gis.db import models


class Fertidb(models.Model):
    user = db_models.ForeignKey(User, on_delete=models.CASCADE)
    culture = models.CharField(max_length=50)
    area = models.IntegerField()
    plot = models.FileField(upload_to='KML_FILES', blank=True)

    def __str__(self):
        return f' Parcelles de {self.user.username}'*

How can I get the username of the logged-in user in Django?, of logged in user. if you are using the old way of writting views, in the way of Function-Based-Views in your view, you are creating a new variable called usuario to save the request. To do this, they can simply create a text file in NotePad in a CSV (comma separated) format. Within the text file, have each user type their username and password (separated with a comma) as shown below. You need all your users to save the file with the same file name and in the same location on their computers.


How to get the currently logged in user's user id in Django?, object from template, you should pass it to template or use RequestContext. Furthermore, we will show you how to build secure pages that are only accessed by logged in users. Without login, the user can not access the page. How to create a Registration and Login System with PHP and MySQL. Here are Seven pretty simple steps you have to follow to create a login system. Create a Database and Database Table; Connect to the


What does request.user refer to in Django?, user.role = Role.query.get(form.role.data) user.name = form.name.data user.​about_me = form.about_me.data db.session.add(user) flash('The profile has been set in the choices attribute uses the numeric identifiers to reference each option. When the form is submitted, the id is extracted from the field's data attribute and  If an application design calls for a database that stores user information, the database is the core of this application. The database is needed to store the usernames and passwords of all users allowed to access the website. Often, the database is used to store much more information about the customer.


Flask Web Development: Developing Web Applications with Python, This simple Web form should contain just two fields—a user name field and a form are compared with the user name and password columns in the database. pages aimed at a general audience of Web visitors, you could place this form on contain only a user name field, a password field, and a single Submit button. Whenever a user sucessfully logs in, you add a record to that log that indicates who logged in and when. When they shut down their front end, the log record gets update with their logout time. So you can see who is in the database but querying the log for whoever has a log record without a logout time.