I'm a beginner in SQLite, and I need to know how do I select all the elements from an SQLite table and put them in a list. Here's what I tried:
<select name="users" id="users">
{% for user_reg in db.user_registration_models %}
{% if user.is_authenticated %}
<option value="/all_users/{{ user_reg.id }}">{{ user_reg.username }}</option>
{% endif %}
{% endfor %}
</select>
Thanks in advance for your answers!
CodePudding user response:
You can either return all the users in the db or return only the authenticated one, if you want to print the username of current user if he is authenticated user the following code:
{% if request.user.is_authenticated %}
<select name="users" id="users">
<option >{{ request.user.username }}</option>
</select>
{% endif %}
If you need to print the username of the current user, just use request.user.username but.. If you want to select anything from db (model) which is created by the current user e.g. posts that created by the current user so can do it by the following:
In model.py file.
from django.db import models
from django.contrib.auth.models import User
class PostModel(models.Model):
user= models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=250)
text = models.CharField(max_length=5000)
In veiws.py
from .modal import PostModel
from django.shortcuts import render
def home_view(request):
if request.user.is_authenticated:
posts = PostModel.objects.filter(user=request.user)
return render(request, 'index.html', {'posts': posts})
else:
#you can return anything instead of redirect the user to login page
# if the user not authenticated
return render(request, 'login.html', {})
In index.html
{% for item in posts %}
<div class='post-container' >
<div class='user'> {item.user.first_name }</div>
<div class='title'> {item.title}</div>
<div class='text'> {item.text}</div>
</div>
{% endfor %}
user filter method to get anything with specific parameters, e.g.
posts = PostModel.objects.filter(user__id=1)
posts = PostModel.objects.filter(title='my post')
users = User.objects.filter(first_name='first name')
and so on. Read about filter function in the documentation: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#filter