Python Django视图,按用户向访问者显示对象
我创建了一个应用程序,允许注册用户使用表单创建产品。每个注册用户都有一个配置文件页面,显示只有他们在登录时才能看到的产品。我想创建一个视图,允许未注册用户通过单击用户名查看任何用户的产品。我该怎么做 以下是产品表单:Python Django视图,按用户向访问者显示对象,python,django,views,Python,Django,Views,我创建了一个应用程序,允许注册用户使用表单创建产品。每个注册用户都有一个配置文件页面,显示只有他们在登录时才能看到的产品。我想创建一个视图,允许未注册用户通过单击用户名查看任何用户的产品。我该怎么做 以下是产品表单: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'description', 'url', 'product_type', '
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url']
labels = {
'name': 'Product Name',
'url': 'Product URL',
'product_type': 'Product Type',
'description': 'Product Description',
'image': 'Product Image',
'image_url': 'Product Image URL',
'price': 'Product Price'
}
widgets = {
'description': Textarea(attrs={'rows': 5}),
}
产品视图很简单:
def products(request):
products = Product.objects.all()
form = ProductForm()
return render(request, 'products.html', {'products': products, 'form':form})
def post_product(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ProductForm(data = request.POST, files = request.FILES)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
product = form.save(commit = False)
product.user = request.user
product.likes = 0
product.save()
# redirect to a new URL:
return HttpResponseRedirect('/products')
如果我需要展示其他东西,请告诉我
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})
我不得不从django.views.generic.base导入ContextMixin从django.views.generic.list导入ListView添加-现在我得到一个错误-TypeError:无法为bases ContextMixin创建一致的方法解析顺序(MRO),ListView您可以使用我根据您的函数更新的方法。我确实这样做了,但我仍然得到了类型错误,我非常感谢您的帮助。我也在研究它。我猜我也需要一个url模式来解决这个问题。我在产品页面上已经有了这个模式:url(r'^products/$,views.products,name='products'),-不确定要添加什么-url模式可以修复类型错误吗?我发现错误,将
类产品列表视图(ContextMixin,列表视图):
更改为类产品列表视图(列表视图):