A weird redirection problem

Hi everyone
I am designing a page for comparing products in my web store
i coded the view section as follow

class GoodCompareView(DetailView):
    model = Good
    template_name = 'good_compare.html'
   
   # bringing all related products that has same branch and subbranch similar to selected product for  compare
    def get_queryset(self):
        pk = self.kwargs.get(self.pk_url_kwarg)
        related_objects = Good.objects.filter(id=pk).values(
            'mainbranch', 'subbranch1', 'subbranch2')
        query = Good.objects.filter(mainbranch=related_objects[0]['mainbranch'],
                                    subbranch1=related_objects[0]['subbranch1'],
                                    subbranch2=related_objects[0]['subbranch2'])
        return query

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['compare_form'] = GoodCompareForm
        context['related_goods'] = self.get_queryset()
        return context

    # finding a certain product using designed search box
    @staticmethod
    def compare_search_modal(request):
        if request.POST.get('search_box'):
            compare_search_ph = request.POST.get('search_box')
            good_to_compare = Good.objects.filter(
                id=SubBranch3.objects.filter(sb3_desc=compare_search_ph)
            )
            if good_to_compare:
                return good_to_compare
            else:
                return messages.error(request, 'کالایی با این مشخصات یافت نشد')

    def get(self, request, *args, **kwargs):
        if self.compare_search_modal(request):
            context = {
                'next_good': self.compare_search_modal(request)
            }
            return render(request, self.template_name, context=context)
        else:
            return HttpResponseRedirect(reverse('good_compare', kwargs={'pk': self.kwargs['pk']}))

and here is my urls.py

urlpatterns = [
    path('about/', AboutPageView.as_view(), name='about'),
    path('?/', GoodsSearchView.as_view(), name='gsview'),
    path('?/<int:pk>/', GoodsListView.as_view(), name='goods_list'),
    path('?/<int:g_id>/wish_list/<int:c_id>/', add_to_wishlist, name='add_to_wishlist'),
    path('?/<int:g_id>/buy_basket/', add_to_buybasket, name='add_to_buybasket'),
    path('?/<str:from_link>&&<int:search_phrase>', GoodsSearchView.as_view(), name='branch_filter'),
    path('?/<int:pk>/edit_comment/<int:cpk>/', CommentUpdate.as_view(), name='edit_comment'),
    path('?/<int:pk>/delete_comment/<int:cpk>/', CommentDelete.as_view(), name='delete_comment'),
    path('?/<int:pk>/vote_comment/<int:cpk>', VoteComment.as_view(), name='comment_votes'),
    path('?/<int:pk>/good_compare', GoodCompareView.as_view(), name='good_compare'),
    path('?/<int:pk>/good_compare', GoodCompareView.compare_search_modal, name='compare_search'),
]

and good_compare.html template

{% extends '_base.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block title %}مقایسه کالا{% endblock title %}

{% block content %}
{% if messages %}
    {% for message in messages %}
        {% if message.tags == "success" %}
            <div class="alert alert-success d-flex align-items-center" role="alert">
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    {{ message }}
            </div>
        {% else %}
            {% if message.tags == "error" %}
                <div class="alert alert-danger d-flex align-items-center" role="alert">
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        {{ message }}
                    </div>
            {% endif %}
        {% endif %}
    {% endfor %}
{% endif %}
<h4 align="center"> مقایسه کالا </h4>
    <div class="container text-right">
        <div class="row">
            <div class="col-md-auto">
                <div class="sticky-top">
                    <div class="card" style="width: 18rem;">
                        <img src="{% static object.image %}" class="card-img-top"
                            alt="عکس محصول" height="250" width="200">
                        <div class="card-body">
                            <h5 class="card-title">{{object.subbranch3.sb3_desc}}</h5>
                            <p class="card-text">قیمت:{{object.price}}ریال</p>
                            <p class="card-text"></p>
                            <a href="{% url 'goods_list' pk=object.pk %}"
                                class="btn btn-primary stretched-link">مشاهده جزئیات</a>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="card" style="width: 18rem;">
                        {% for att in object.attributes.all %}
                            <div class="card card-body">
                                <div class="row row-col-2">
                                    <div class="col">
                                        <P>{{att.attribute.attribute_name}}</P>
                                    </div>
                                    <div class="col">
                                        <P>{{att.value}}</P>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div class="col-md-auto">
                    <!-- Button trigger modal -->
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal"
                            data-bs-target="#searchModal">
                        افزودن کالا
                    </button>
                    <!-- Modal -->
                    <div class="modal fade" id="searchModal" tabindex="-1" data-bs-backdrop="static"
                         aria-labelledby="searchModalLabel" aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h1 class="modal-title fs-5" id="searchModalLabel">جستجوی کالا</h1>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                                        aria-label="Close">
                                    </button>
                                </div>
                                    <div class="modal-body">
                                        <form method="post">{% csrf_token %}
                                            {{compare_form|crispy}}
                                            <a type="button" class="btn btn-primary"
                                               href="{% url 'compare_search' pk=object.pk %}">جستجو</a>
                                            <br>
                                            <br>
                                            <div class="row">
                                                {% for good in related_goods %}
                                                    <div class="col-md-auto">
                                                        <div class="card" style="width: 13rem; height: 13rem">
                                                        <img src="{% static good.image %}" class="card-img-top"
                                                            alt="عکس محصول" height="100" width="50">
                                                        <div class="card-body">
                                                            <p class="card-title">{{good.subbranch3.sb3_desc}}</p>
                                                            <p class="card-text">قیمت:{{good.price}}ریال</p>
                                                            <p class="card-text"></p>
                                                            <a href="{% url 'good_compare' pk=good.pk %}"
                                                                class="btn btn-primary stretched-link btn-sm">مشاهده جزئیات</a>
                                                        </div>
                                                        </div>
                                                        <br>
                                                    </div>
                                                {% endfor %}
                                            </div>
                                        </form>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">بستن</button>
                                    </div>
                            </div>
                        </div>
                    </div>
            {% if good_to_compare %}
                <div class="row">
                    <div class="col-md-auot">
                        <div class="card" style="width: 13rem; height: 13rem">
                            <img src="{% static good_to_compare.image %}" class="card-img-top"
                                 alt="عکس محصول" height="100" width="50">
                            <div class="card-body">
                                <p class="card-title">{{good_to_compare.subbranch3.sb3_desc}}</p>
                                <p class="card-text">قیمت:{{good_to_compare.price}}ریال</p>
                                <p class="card-text"></p>
                                <a href="{% url 'good_compare' pk=good_to_compare.pk %}"
                                   class="btn btn-primary stretched-link btn-sm">مشاهده جزئیات
                                   <div class="card" style="width: 13rem; height: 13rem">
                                        <img src="{% static good_to_compare.image %}" class="card-img-top"
                                            alt="عکس محصول" height="100" width="50">
                                        <div class="card-body">
                                            <p class="card-title">{{good_to_compare.subbranch3.sb3_desc}}</p>
                                            <p class="card-text">قیمت:{{good_to_compare.price}}ریال</p>
                                        </div>
                                   </div>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            {% endif %}
            </div>
        </div>
    </div>
{% endblock content %}

the problem is when i want to go to compare page browser says
The page isn’t redirecting properly
and i can not find out where the problem is

any help would be appreciated

It seems to me that you’re looking for POST data in a get request. From what I can tell here, compare_search_modal is always going to be None because you’re looking in request.POST for search_box, which is never going to be present.

As a result, your if self.compare_search_modal... test is always going to be false, resulting in the get always returning the HttpResponseRedirect.

(I also don’t see the value - or the appropriateness - of marking this method as a staticmethod.)

1 Like

Hi ken
thanks for you answer
i corrected my view as follow

class GoodCompareView(DetailView):
    model = Good
    template_name = 'good_compare.html'

    def get_queryset(self):
        pk = self.kwargs.get(self.pk_url_kwarg)
        related_objects = Good.objects.filter(id=pk).values(
            'mainbranch', 'subbranch1', 'subbranch2')
        query = Good.objects.filter(mainbranch=related_objects[0]['mainbranch'],
                                    subbranch1=related_objects[0]['subbranch1'],
                                    subbranch2=related_objects[0]['subbranch2'])
        return query

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['compare_form'] = GoodCompareForm
        context['related_goods'] = self.get_queryset()
        return context

    def compare_search_modal(request):
        print(request)

        if request.method == 'POST':
            name_query = SubBranch3.objects.filter(sb3_desc__icontains=
                                                   request.POST.get('search_box')).values('id')
            print(name_query)
            good_to_compare = Good.objects.filter(subbranch3_id__in=name_query)
            print(good_to_compare)
            if good_to_compare:
                context = {
                    'next_good': good_to_compare
                }
                return render(request, 'good_compare', context=context)
            else:
                messages.error(request, 'کالایی با این مشخصات یافت نشد')
                return HttpResponseRedirect(reverse('good_search'))
        else:
            return HttpResponseRedirect(reverse('good_compare',
                                                kwargs={'pk':??? })

i marked a place with ??? here i want to redirect to good_compare page with pk of first product that has chosen for comparing with others but i do not know how to access this parameter

What parameter? (I’m not sure I understand what you’re referring to by your reference to “this parameter”.) If you’re talking about the pk parameter in the url, you’re already referencing it in your get_queryset method.

1 Like

i solved pk problem
but now my problem is when i input a text into search_box, its value does not pass to view and it is None
here is my template
good_compare.html

{% extends '_base.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block title %}مقایسه کالا{% endblock title %}

{% block content %}
{% if messages %}
    {% for message in messages %}
        {% if message.tags == "success" %}
            <div class="alert alert-success d-flex align-items-center" role="alert">
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    {{ message }}
            </div>
        {% else %}
            {% if message.tags == "error" %}
                <div class="alert alert-danger d-flex align-items-center" role="alert">
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        {{ message }}
                    </div>
            {% endif %}
        {% endif %}
    {% endfor %}
{% endif %}
<h4 align="center"> مقایسه کالا </h4>
    <div class="container text-right">
        <div class="row">
            <div class="col-md-auto">
                <div class="sticky-top">
                    <div class="card" style="width: 18rem;">
                        <img src="{% static object.image %}" class="card-img-top"
                            alt="عکس محصول" height="250" width="200">
                        <div class="card-body">
                            <h5 class="card-title">{{object.subbranch3.sb3_desc}}</h5>
                            <p class="card-text">قیمت:{{object.price}}ریال</p>
                            <p class="card-text"></p>
                            <a href="{% url 'goods_list' pk=object.pk %}"
                                class="btn btn-primary stretched-link">مشاهده جزئیات</a>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="card" style="width: 18rem;">
                        {% for att in object.attributes.all %}
                            <div class="card card-body">
                                <div class="row row-col-2">
                                    <div class="col">
                                        <P>{{att.attribute.attribute_name}}</P>
                                    </div>
                                    <div class="col">
                                        <P>{{att.value}}</P>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div class="col-md-auto">
                    <!-- Button trigger modal -->
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal"
                            data-bs-target="#searchModal">
                        افزودن کالا
                    </button>
                    <!-- Modal -->
                    <div class="modal fade" id="searchModal" tabindex="-1" data-bs-backdrop="static"
                         aria-labelledby="searchModalLabel" aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h1 class="modal-title fs-5" id="searchModalLabel">جستجوی کالا</h1>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                                        aria-label="Close">
                                    </button>
                                </div>
                                    <div class="modal-body">
                                        <form method="post">{% csrf_token %}
                                            {{compare_form|crispy}}
                                            <a type="button" class="btn btn-primary"
                                               href="{% url 'compare_search' pk=object.pk %}">جستجو</a>
                                            <br>
                                            <br>
                                            <div class="row">
                                                {% for good in related_goods %}
                                                    <div class="col-md-auto">
                                                        <div class="card" style="width: 13rem; height: 13rem">
                                                        <img src="{% static good.image %}" class="card-img-top"
                                                            alt="عکس محصول" height="100" width="50">
                                                        <div class="card-body">
                                                            <p class="card-title">{{good.subbranch3.sb3_desc}}</p>
                                                            <p class="card-text">قیمت:{{good.price}}ریال</p>
                                                            <p class="card-text"></p>
                                                            <a href="{% url 'good_compare' pk=good.pk %}"
                                                                class="btn btn-primary stretched-link btn-sm">مشاهده جزئیات</a>
                                                        </div>
                                                        </div>
                                                        <br>
                                                    </div>
                                                {% endfor %}
                                            </div>
                                        </form>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">بستن</button>
                                    </div>
                            </div>
                        </div>
                    </div>
            {% if good_to_compare %}
                {% for item in good_to_compare %}
                <div class="row">
                    <div class="col-md-auot">
                        <div class="card" style="width: 13rem; height: 13rem">
                            <img src="{% static item.image %}" class="card-img-top"
                                 alt="عکس محصول" height="100" width="50">
                            <div class="card-body">
                                <p class="card-title">{{item.subbranch3.sb3_desc}}</p>
                                <p class="card-text">قیمت:{{item.price}}ریال</p>
                                <p class="card-text"></p>
                                <a href="{% url 'good_compare' pk=good_to_compare.pk %}"
                                   class="btn btn-primary stretched-link btn-sm">مشاهده جزئیات
                                   <div class="card" style="width: 13rem; height: 13rem">
                                        <img src="{% static good_to_compare.image %}" class="card-img-top"
                                            alt="عکس محصول" height="100" width="50">
                                        <div class="card-body">
                                            <p class="card-title">{{item.subbranch3.sb3_desc}}</p>
                                            <p class="card-text">قیمت:{{item.price}}ریال</p>
                                        </div>
                                   </div>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            {% endif %}
            </div>
        </div>
    </div>
{% endblock content %}

and here is my compare form
forms.py

class GoodCompareForm(forms.Form):
    search_box = forms.CharField(max_length=50,
                        help_text='جستجوی کالا از لیست کالاهای مرتبط جهت افزودن به مقایسه', label='')

and my GoodCompare class

class GoodCompareView(DetailView):
    model = Good
    template_name = 'good_compare.html'

    def get_queryset(self):
        pk = self.kwargs.get(self.pk_url_kwarg)
        related_objects = Good.objects.filter(id=pk).values(
            'mainbranch', 'subbranch1', 'subbranch2')
        query = Good.objects.filter(mainbranch=related_objects[0]['mainbranch'],
                                    subbranch1=related_objects[0]['subbranch1'],
                                    subbranch2=related_objects[0]['subbranch2'])
        return query

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['compare_form'] = GoodCompareForm
        context['related_goods'] = self.get_queryset()
        return context

    def compare_search_modal(request, pk):
        print(f"search box valuse is {request.POST.get('search_box')}")
        if request.method == 'POST':
            name_query = SubBranch3.objects.filter(sb3_desc__icontains=
                                                   request.POST.get('search_box')).values('id')
            print(name_query)
            good_to_compare = Good.objects.filter(subbranch3_id__in=name_query)
            print(f"search returns {good_to_compare}")
            if good_to_compare:
                context = {
                    'next_good': good_to_compare
                }
                return render(request, 'good_compare', context=context)
            else:
                messages.error(request, 'کالایی با این مشخصات یافت نشد')
                return HttpResponseRedirect(reverse('good_search'))
        else:
            return HttpResponseRedirect(reverse('good_compare', kwargs={'pk': pk}))

could it be using bootstrap modal problem that search_box value won’t pass to view?

No, that cannot be the cause of the issue.

I can’t seem to find this “search_box” that you’re referring to in the good_compare.html template you’re showing. But keep in mind, the _only_input fields that are submitted in a form are those elements that are inside the <form></form> tags. Fields not inside the form don’t get submitted with the form.

search_box is a field of class GoodCompareForm
and i pass this form to template in get_context_data

A couple different things here.

  • In your get_context_data you’re not creating an instance of the form, you’re setting the context element to the form class itself.

  • In your template where you have the button in the form, your url tag is split across lines. Django tags should not be split, the complete tag should be on the same line.

  • Also, that button is not a submit button. It’s an anchor tag with an href, which means it’s going to be a GET and not a POST. Since it’s not a submit button, it’s not going to submit any data.

  • Your def compare_search_modal is indented such that it’s in the GoodCompareView class. That’s not right, is it?

1 Like

Thanks for your answer
now i understand the problem
have a nice time