Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want a logged in user to see only its saved information

I just started learning django. i created a model and i expect when a user logs in, the user should see only info it saved but when another user logs in, it sees saved information from other users

view.py

def user_locker(request):
    saved_info = Locker.objects.all()
    all_saved_info = {'saved_info': saved_info}
    return render(request, 'pwdbank/user_locker.html', all_saved_info)

model.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Locker(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    site_name = models.CharField(max_length=55)
    site_url = models.URLField(max_length=55)
    username = models.CharField(max_length=55)
    email = models.EmailField(max_length=100)
    password = models.CharField(max_length=55)
    created_date = models.DateField(auto_now_add=True)
    updated_date = models.DateField(auto_now=True)
    
    def __str__(self):
        return f'{self.site_name}'

Thank you. Please Help!

>Solution :

You should keep the request to be allowed only for logged in users.

from django.contrib.auth.decorators import login_required

@login_required
def user_locker(request):
    saved_info = Locker.objects.filter(user=request.user)
    all_saved_info = {'saved_info': saved_info}
    return render(request, 'pwdbank/user_locker.html', all_saved_info)

Reference : https://docs.djangoproject.com/en/4.1/topics/auth/default/#the-login-required-decorator

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading