首页 > 解决方案 > 我想在一个模板中表示 DetailView 和 ListView。我能做些什么?

问题描述

我想将detailview表示为图片。我想对图片模板中的框部分进行编码。 在此处输入图像描述

现在如下。

视图.py

@login_required
def product_detail(request, id, product_slug=None):
    product = get_object_or_404(Product, id=id, slug=product_slug)
    return render(request, 'shop/detail.html', {'product': product})

我认为它应该修改为类。我想通过在detail_template中一起表示DetailView和ListView来解释它。我只修改了views.py,如下所示。

class ProductDetailView(DetailView, ListView):

    model = Product
    template_name = 'shop/detail.html'
    context_object_name = 'latest_question_list'
    @login_required
    def get_queryset(self, id, product_slug=None): 
        product = get_object_or_404(Product, id=id, slug=product_slug)
        return render(self, 'shop/detail.html', {'product': product})

发生此错误。AttributeError:“ProductDetailView”对象没有属性“用户”

网址.py

urlpatterns = [
    .........
    path('<int:id>/<product_slug>/', product_detail, name='product_detail'),
    .........
]

详细信息.html

{% extends 'base.html' %}
{% block title %}Product Detail{% endblock %}
{% block content %}

<div class="col">
    <div class="alert alert-info" role="alert">Detail</div>

    <div class="container">
        <div class="row">
            <div class="col-4">
                <img src="{{product.image.url}}" width="100%">
            </div>
            <div class="col">
                <h1 class="display-6">{{product.cname}}</h1>
                      <p class="card-text">{{product.pname}}</p>


                <h5><span class="badge badge-secondary">Description</span>{{product.description|linebreaks }}</h5>
                {% if product.author.username == user.username %}
                <a href="{% url 'shop:product_update' pk=product.id product_slug=product.slug %}" class="btn btn-outline-primary btn-xs mr-1 mt-1 float-left">Update</a>
                <a href="{% url 'shop:product_delete' pk=product.id product_slug=product.slug %}" class="btn btn-outline-danger btn-xs mr-1 mt-1 float-left">Delete</a>
                {% endif %}
                {% if product.author.username != user.username %}
                <a href="#" class="btn btn-secondary btn-xs mr-1 mt-1 float-left">Inquiry</a>
                {% endif %}
                <a href="/" class="btn btn-info btn-xs mt-1 float-left">Continue shopping</a>

            </div>
        </div>


    </div>
    <p></p>

<div class="col">
    <div class="alert alert-info" role="alert">Products added by registrants</div>


    <div class="container">
        {% for product in products %}
        <div class="row">

            {% if product.user.username == user.username %}
            <div class="col-4">
                <img src="{{product.image.url}}" width="auto" height="250">
            </div>
            <div class="col">
                <h1 class="display-6">{{product.pname}}</h1>
                <h5><span class="badge badge-secondary">Description</span>{{product.description|linebreaks}}</h5>
            </div>
            {% endif %}
        </div>
        {% endfor %}
    </div>

{% endblock %}

请帮助我如何解决它。如果您能推荐任何我可以参考的教科书,我也将不胜感激。

标签: python-3.xlistviewdjango-templatesdjango-viewsdetailview

解决方案


我也有类似的情况。我想在同一页面上显示创建表单、详细信息和列表:

网址:

example_urlpatterns = [
    path('', views.ExampleCreateView.as_view(), name='_list'),
    path('new/', views.ExampleCreateView.as_view(), name='_create'),
    path('<int:pk>/', views.ExampleCreateView.as_view(), name='_detail'),
    path('<int:pk>/del', views.ExampleDeleteView.as_view(), name='_del'),
]
urlpatterns = [
    # ...
    path('example/', include(example_urlpatterns)),
    # ...
]

如您所见,我有两个视图ExampleCreateView(也提供detaillist)和 ExampleDeleteView 用于删除。ExampleCreateView主要是一个创建视图:

class ExampleCreateView(CreateView):
    template_name = 'example.html'
    form_class = ExampleCreateForm
    model = Example

    def form_valid(self, form):
        pass  # Stuff to do with a valid form

    # add user info from request to the form
    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super().get_form_kwargs(*args, **kwargs)
        kwargs['user'] = self.request.user
        return kwargs

    # Create appropriate context    
    def get_context_data(self, **kwargs):
        kwargs['object_list'] = Example.objects.order_by('ip')  # list
        try:  # If we have pk, create object with that pk
            pk = self.kwargs['pk']
            instances = Example.objects.filter(pk=pk)
            if instances:
                kwargs['object'] = instances[0]
        except Exception as e:
            pass # No pk, so no detail
        return super().get_context_data(**kwargs)

因为我继承自CreateView,所以默认情况下会处理所有表单处理。

添加该kwargs['object_list'] =...行使其用作列表视图,try该行之后的块使其用作详细视图。

在模板中显示所有相关部分:

{% if object %}
    {% comment %}
        ...display the object...   (Detail section)
    {% endcomment %}
{% endif %}

{% if form %}
    {% comment %}
        ...display the form...   (Create section)
    {% endcomment %}
{% endif %}

{% if object_list %}
    {% comment %}
        ...display the list...   (List section)
    {% endcomment %}
{% endif %}

让我知道这是否有帮助


推荐阅读