Reputation: 146
I have relation between Customer
and Products
, and customer_id
is saving in Product
model table, but I want to display products on my view page according to customer
, suppose if a customer logged in using his details then he can see only his products, but currently he can see all products. Please let me know How I can do it.
Here is my models.py
file...
class Customer(models.Model):
name=models.CharField(default=None)
user=models.OneToOneField(User, related_name='userwithCustomer', on_delete=models.CASCADE)
class Product(models.Model):
name=models.CharField(default=None)
customer=models.Foreignkey(Customer, related_name='customer_product', on_delete=models.CASCADE)
here is my views.py
file...
def display_data(request):
test_display = Product.objects.all()
context = {
'test_display': test_display
}
return render(request, 'page.html', context)
here is my page.html
file...here i am trying to display products according to loggedin customer..
<p>{{test_display.count}}</p>
Upvotes: 0
Views: 802
Reputation: 31
The problem is that you are using the product instead of customer, which as a result will display all products instead of the ones solely owned by said user. Replace this line of code:
Product.objects.all()
with:
request.user.customer_product.all()
and it should only show the logged in user's items. For the display, you have to make a for loop to show the details of each item like so:
<ul>
{% for test in test_display %}
<li>{{test.name}}:${{test.price}}</li>
{% endfor %}
</ul>
Upvotes: 1
Reputation: 2110
If you're sure that your user is logged in (i.e. session authenticated) you can change your queryset from test_display = Product.objects.all()
to test_display = Product.objects.filter(customer=request.user)
. If you want to have login constraint on your view you can use login_required
decorator on your view:
from django.contrib.auth.decorators import login_required
@login_required
def display_data(request):
test_display = Product.objects.filter(customer=request.user)
context = {
'test_display': test_display
}
return render(request, 'page.html', context)
Upvotes: 1