class ProductListView(ListView):
template_name = 'products.html'
context_object_name = 'product_list'
paginate_by = None
def get_queryset(self):
username = self.request.GET.get('username',None)
user = None
if username:
try:
user = User.objects.get(username=username)
except (User.DoesNotExist, User.MultipleObjectsReturned):
pass
if user:
return Product.objects.filter(user=user)
return Product.objects.none()
URL。py:
url(r'^product/$', ProductListView.as_view(), name='product_list'),
访问类似页面
www.example.com/product?username=testuser
根据您的编辑:
def products(request):
username = request.GET.get('username',None)
user = None
if username:
try:
user = User.objects.get(username=username)
except (User.DoesNotExist, User.MultipleObjectsReturned):
pass
if user:
return Product.objects.filter(user=user)
else:
products = Product.objects.all()
form = ProductForm()
return render(request, 'products.html', {'products': products, 'form':form})