I'm creating an app that allows Users to create personal goals and then allow them to view those goals once created. When the goal is created it goes into my database and is put onto a list page that users are able to view. The problem is that all users are able to view these goals, not just their own. Below is my code showing how I am trying to make the lists for the users eyes only:
Models
class Goal(models.Model):
# values that I am storing in my SQLlite DB
title = models.CharField(max_length=1000)
body = models.TextField()
created_data = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_data = models.DateTimeField(auto_now_add=False, auto_now=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
# user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
# Where I am trying to authenticate the user
def get_queryset(self, *args, **kwargs):
return Goal.objects.all().filter(owner=self.request.user)
Views
def goal_list(request):
goals = Goal.objects.all().order_by('created_data')
return render(request, 'goals/goal_list.html', { 'goals': goals })
@login_required
def goal_create(request, *args):
if request.method == 'POST':
form = forms.CreateGoal(request.POST, request.FILES)
if form.is_valid():
# saving my form
goal_create = form.save(commit=False)
goal_create.user = request.user
goal_create.save()
return redirect('goals:goal_list')
else:
form = forms.CreateGoal()
return render(request, 'goals/goal_create.html', {'form': form})
html
{% block body%}
<div class="container">
<h1>Goals List</h1>
<div class="goals">
{% for goal in goals %}
<div class="goal">
{% these are the values Im displaying on the webpage. %}
<h2><a href="">{{ goal.title }}</a></h2>
<p>{{ goal.goal.title }}</p>
<p>{{ goal.body }}</p>
<p>{{ goal.created_data }}</p>
{# <p>{{ goal.user }}</p>#}
</div>
{% endfor %}
</div>
{% endblock %}