简体   繁体   中英

Struggling to pass request.user.id to SQL function in python/django

hoping someone can help as I'm new django (and coding) and I'm stuck with trying to pass the current user's ID number to an SQL function. I've spent days searching for a solution but nothing I've tried has worked. I know the SQL function works as I can pass through a number without any issue, but when trying to use request.user it just comes up blank.

views.py:

def my_custom_sql(request):
    current_user = User.objects.get(request.user)
    with connection.cursor() as cursor:
        cursor.execute("SELECT first_name FROM customuser WHERE id = %s",[current_user])
        row = cursor.fetchone()

    return row

def dashboard(request):
    return render(request, 'dashboard.html', {'my_custom_sql': my_custom_sql})

models.py:

class CustomUser(AbstractUser):
    pass
    # add additional fields in here
    employee_dob = models.DateField(blank=True, null=True)
    is_executive = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return self.username

dashboard.html:

<a href="{% url 'home' %}">Home</a> <br>

{% if user.is_authenticated %}

<p>Is this the your first name?: {{my_custom_sql}}</p>

{% else %}
    <p>You are not logged in, please do so.</p>

{% endif %}

I've read everything I can find around the issue but haven't found anything yet that has helped. I'm not sure if it has something to do with sessions or django hashing the info? But I'm not sure how to get around this safely. Anyone got any idea how to resolve this so that the logged in user's id number (pk) is passed to current_user for this to work? There's no error code for me to work around, it just returns a blank output where the user's first name should appear. Really trying to learn here so explanations of where I've gone wrong would be much appreciated.

# Just need to change the value of 'current_user' variable

def my_custom_sql(request):
    current_user = request.user.id
    with connection.cursor() as cursor:
        cursor.execute("SELECT first_name FROM customuser WHERE id = %s",[current_user])
        row = cursor.fetchone()

    return row

Just to let anyone know that has this issue that the reason it didn't like was only because the user.id is an integer and the SQL query was expecting a string. So by converting it to string using the str() command, it worked as below.

However, this would open the app to SQL injection attacks as it's raw SQL so the below is fine for proof of concept projects or testing but isn't suitable for production level (more info here: https://www.owasp.org/index.php/SQL_Injection?fbclid=IwAR3v5wwb52TfA4CyOTxDZWiuMAqVl4zdjr9hLEW2WwU7ZKhv85jQdKIe5Zs ). Instead use stored procedures and parameterisation (I think, again I'm new to this so could be wrong).

def my_custom_sql(request):
    current_user = str(request.user.id) #use str before passing argument to convert to string from db
    with connection.cursor() as cursor:
        cursor.execute("SELECT first_name FROM customuser WHERE id = %s",[current_user])
        row = cursor.fetchone()
    return row

Also request needed to be added into the context for the views:

def dashboard(request):
    return render(request, 'dashboard.html', {'my_custom_sql': my_custom_sql (request)})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM