我想在一个模板中表示 DetailView 和 ListView。我能做什么?

I want to represent DetailView and ListView in one Template. What can I do?

我想把细节视图表达成图片。我想在图片的模板中对盒子部分进行编码。 enter image description here

现在情况如下

views.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})

我觉得应该修改为class。我想通过在 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' 对象没有属性 'user'

urls.py

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

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 %}

请帮我解决一下。如果您能推荐一些我可以参考的教材,我将不胜感激。

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

网址:

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'] =... 使其作为 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 %}

如果有帮助请告诉我

目前我是这样申请的

views.py : 已修改

@method_decorator(login_required, name="dispatch")
class ProductDetailView(DetailView):

    model = Product
    template_name = 'shop/detail.html'


    def get_context_data(self, **kwargs):
        context = super(ProductDetailView, self).get_context_data(**kwargs)
        context['product_list'] = Product.objects.all()
    return context

index = ProductDetailView.as_view()

detail.html : 已修改

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


    <div class="container">
        {% for prdt in product_list %}
            {% if product.author.username == prdt.author.username %}
                {% if product.pname != prdt.pname %}
                    <a href="{{prdt.get_absolute_url}}" class="btn btn-outline-warning mt-1 text-success ">{{ prdt }}</a><br>
                {% endif %}
            {% endif %}

        {% endfor %}
    </div>

enter image description here