Field 'id' expected a number but got 'product_id' django [closed] - django

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In my ecommerce app when I click on add to cart the product goes to the cart but when I click on the cart it gives me the error that 'Field 'id' expected a number but got 'product_id''. Basically I use context_processor to pass the cart.py information to the template.
Link to the cart from base.html is:
<div class="navbar-item">
Cart {% if cart %}({{cart|length}}){% endif %}
</div>
When I click on cart this error is generated:
Field 'id' expected a number but got 'product_id'
my project/urls.py is
path('cart/',include("cart.urls")),
my cart/urls.py is
urlpatterns = [
path('',views.cart_detail, name='cart')
]
my cart/cart.py is
from django.conf import settings
from product.models import Product
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def __iter__(self):
for p in self.cart.keys():
self.cart[(p)]['product'] = Product.objects.get(pk=p)
for item in self.cart.values():
item['total_price'] = item['product'].price * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def add(self, product_id, quantity=1, update_quantity=False):
product_id = str(product_id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 1, 'id': product_id}
if update_quantity:
self.cart[product_id]['quantity'] += int(quantity)
if self.cart[product_id]['quantity'] == 0:
self.remove(product_id)
self.save()
print(self.cart)
def remove(self, product_id):
if product_id in self.cart:
del self.cart[product_id]
self.save()
def save(self):
self.session[settings.CART_SESSION_ID] = self.cart
self.session.modified = True
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
def get_total_cost(self):
for p in self.cart.keys():
self.cart[str(p)]['product'] = Product.objects.get(pk=p)
return sum(item['quantity'] * item['product'].price for item in self.cart.values())
my context_processors.py is
def cart(request):
return {'cart': Cart(request)}
and my cart.html is:
{% extends 'core/base.html' %}
{% block title %}Cart | {% endblock %}
{% block content %}
<h1 class="title">Cart</h1>
{% if cart %}
<div class="box mb-6">
<div class="table">
<table class="table is-fullwidth is-striped">
<thead>
<th></th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th></th>
</thead>
<tbody>
{% for item in cart %}
<tr>
<td>
<figure class="image is-64x64">
<img src="{{ item.product.get_thumbnail }}">
</figure>
</td>
<td>
{{ item.product.title }}
</td>
<td>
{{ item.quantity }}
-
+
</td>
<td>${{ item.total_price }}</td>
<td>Remove</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td></td>
<td><strong>Total cost</strong></td>
<td><strong>{{ cart|length}}</strong></td>
<td colspan="2"><strong>${{ cart.get_total_cost }}</strong></td>
</tr>
</tfoot>
</table>
</div>
</div>
<h2 class="subtitle">Contact information</h2>
<form method="post" action="." id="payment-form">
{% csrf_token %}
{% if form.non_field_errors %}
<div class="notification is-danger">
{{ form.non_field_errors}}
</div>
{% endif %}
{% if form.errors %}
<div class="notification is-danger">
<ul>
{% for field in form %}
{% for error in field.errors %}
<li><strong>{{ field.label }}: </strong>{{ error }}</li>
{% endfor %}
{% endfor %}
</ul>
</div>
{% endif %}
<div class="columns">
<div class="column is-6">
<div class="field">
<label>First name</label>
<div class="control">
<input class="input" type="text" name="first_name">
</div>
</div>
<div class="field">
<label>Last name</label>
<div class="control">
<input class="input" type="text" name="last_name">
</div>
</div>
<div class="field">
<label>E-mail</label>
<div class="control">
<input class="input" type="email" name="email">
</div>
</div>
<div class="field">
<label>Phone</label>
<div class="control">
<input class="input" type="text" name="phone">
</div>
</div>
</div>
<div class="column is-6">
<div class="field">
<label>Address</label>
<div class="control">
<input class="input" type="text" name="address">
</div>
</div>
<div class="field">
<label>Zip code</label>
<div class="control">
<input class="input" type="text" name="zipcode">
</div>
</div>
<div class="field">
<label>Place</label>
<div class="control">
<input class="input" type="text" name="place">
</div>
</div>
</div>
</div>
</form>
<h2 class="subtitle">Payment information</h2>
<div id="card-element">
<!-- A Stripe Element will be inserted here -->
</div>
{% if messages %}
{% for message in messages %}
<div class="notification is-danger">{{ message }}</div>
{% endfor %}
{% endif %}
<div class="field">
<div class="control">
<button class="button is-dark mt-4 is-uppercase">Checkout</button>
</div>
</div>
</div>
{% else %}
<p>You don't have any products in your cart!</p>
{% endif %}
{% endblock %}

Aren't you casting the product_id to a string with str(product_id) ? And later you're passing it as an number but it's still an string. In cart.py and function add

The answer is I did not clear cookies. As I clear those o the code

change this:
{'quantity': 1, 'id': product_id}
with this
{'quantity': 1, 'id': int(product_id)}

Related

Django CreateView form in modal not show

I have a simple CRUD for a table named Clasificacion. The problem is I would like use a Modal for insert record, but actually I don't use the Django form, instead I declared a normal form with all the fields one by one, but I would like use the From, but is not posible for me show the form content, instead the modal shows empty with the ok button.This table has a model declared as:
class Clasificaciones(models.Model):
clasificacion=models.CharField(max_length=30)
detalles=models.CharField(max_length=1000)
This is How I declared the ListView and the CreateView
class ClasificacionesListView(ListView):
model = Clasificaciones
template_name = 'clasificacion/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Lista de clasificaciones"
return context
class ClasificacionesCreateView(SuccessMessageMixin, CreateView):
model = Clasificaciones
form_class = ClasificacionesForm
template_name = 'clasificacion/index.html'
success_url = reverse_lazy('clasificaciones')
success_message = "Insertado correctamente!!!!"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
and this is the index.html with the modal. The modal is in other directory but not works if I put in the same index.html file
{% extends "starter.html" %}
{% block content %}
<div class="content-wrapper">
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<div class="pull-right">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#modalAddClasificacion">Nueva clasificación</button>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</section>
<section class="content">
<div class="content-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Clasificaciones</h3>
</div>
<div class="card-body">
<table id="tablaClasificaciones" class="table table-bordered table-striped">
<thead>
<tr>
<th>Clasificación</th>
<th>Detalles</th>
<th></th>
</tr>
</thead>
<tbody>
{% for clasificacion in object_list %}
<tr>
<td>{{ clasificacion.clasificacion }}</td>
<td>{{ clasificacion.detalles }}</td>
<td>
<div>
<!-- Detalles -->
Editar
<a class="btn btn-link" data-toggle="modal" data-target="#deleteClasificacionModal{{clasificacion.id}}"><span class="fas fa-trash text-danger"></a>
{% include 'clasificacion/modals/delete_modal.html' %}
</div>
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th>Clasificación</th>
<th>Detalles</th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
{% include 'clasificacion/modals/add_modal.html' %}
{% endblock %}
and the modal code, commented the inputs, this way works, but I would like use form
<div class="modal fade" id="modalAddClasificacion">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Adicionar clasificación</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<form id="addclasificacion" method="POST">
{% csrf_token %}
<div class="row">
{% for field in form.visible_fields %}
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>{{ field.label }}</strong>
{{ field }}
</div>
</div>
{%endfor%}
<!-- <div class="col-12">
<div class="form-group">
<strong>Clasificación:</strong>
<input type="text" name="clasificacion" class="form-control" placeholder="Clasificación">
</div>
</div>
<div class="col-12">
<div class="form-group">
<strong>Detalles:</strong>
<textarea class="form-control" style="height:150px" name="detalles" placeholder="Detalles"></textarea>
</div>
</div> -->
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Insertar</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
It not works because I must add to context variable the form, in this case the Form to Categoria model. Also I must add to Create form, because I don't use a create template.
So this is the answer:
class ClasificacionesListView(ListView):
model = Clasificaciones
template_name = 'clasificacion/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Lista de clasificaciones"
context['form'] = ClasificacionesForm()#here the detail.
return context

Problems with a backend part of search line in Django

who can explain me why my SearchView doesn't work. I have some code like this.It doesn't show me any mistakes, but it doesn't work. The page is clear. Seems like it doesn't see the input.
search.html
<div class="justify-content-center mb-3">
<div class="row">
<div class="col-md-8 offset-2">
<form action="{% url 'search' %}" method="get">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search..." />
<div class="input-group-append">
<button class="btn btn-dark" type="submit" id="button-addon2">Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
search/urls.py
path('search/', SearchView.as_view(), name='search')
search/views.py
class SearchView(ListView):
model = Question
template_name = 'forum/question_list.html'
def get_queryset(self):
query = self.request.GET.get("q")
object_list = Question.objects.filter(
Q(title__icontains=query) | Q(detail__icontains=query)
)
return object_list
forum/question_list.html
{% extends 'main/base.html' %}
{% block content %}
{% for question in object_list %}
<div class="card mb-3">
<div class="card-body">
<h4 class="card-title">{{ question.title }}</h4>
<p class="card-text">{{ question.detail }}</p>
<p>
{{ question.user.username }}
5 answers
10 comments
</p>
</div>
</div>
{% endfor %}
{% endblock %}

how can ı submit more than one row in django view with table form

ı wanna submit more than one record but in that code only first student can be record how can ı add more than one record in django view ı am prety new in django can anyone help about that table image
thats the model.py
class GonulluOgrenciDevamsizlik(models.Model):
ogrenci_dersi = models.ForeignKey('Ogrenci', null=True, on_delete=models.SET_NULL)
gonulu = models.ForeignKey('Gonullu', null=True, on_delete=models.SET_NULL)
devamsizlik = models.BooleanField(verbose_name="Devamsızlık Bilgisi",blank=True, default=False)
sinif = models.ForeignKey('SinifListe', null=True, on_delete=models.SET_NULL)
olusturma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturma Tarihi')
guncelleme_tarihi = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-devamsizlik']
verbose_name = 'Devamsızlık'
verbose_name_plural = 'Devamsızlıklar'
def __str__(self):
return self.gonulu.ad + ' ' + self.gonulu.soyad
here is my view: in view ı had been add required foreign keys for my table and then try to save coming post data from table form.
def ogrencidevamsizlik(request, id):
details = "hesabim/ogrenci-devamsizlik.html"
siniflar = SinifListe.objects.filter(gonullu__gonullu__email=request.user.email)
ogrenci = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email)
gonulu = GonulluDersleri.objects.get(gonullu__email__iexact=request.user.email, id=id)
gonulluler = Gonullu.objects.get(email__iexact=request.user.email)
ders = GonulluDersleri.objects.filter(gonullu__email=request.user.email, id=id)
devamsizliklar = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email, sinif__gonullu__id=id)
if request.method == 'POST':
form = DevamsizlikDetayForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, 'Devamsızlıklar başarılı bir şekilde eklendi.')
return redirect('gonullu-siniflar')
else:
messages.error(request, 'Devamsızlık bilgilerinizdeki zorunlu alanları eksiksiz doldurmalısınız.')
else:
form = DevamsizlikDetayForm()
context = {'devamsizliklar': devamsizliklar,
'gonulu': gonulu,
'ders': ders,
'form': form,
'ogrenci': ogrenci,
'siniflar': siniflar,
'gonulluler': gonulluler}
return render(request, details, context)
and here is my table: in table ı try to add devamsizlik area for each student , gonulu , ogrenci and sinif ıd are already coming with views info but devamsizlik will submited by the gonullu so ı made a for loop for all student but when ı submit only first one can be submit thats the promlem
<form class="" novalidate method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.title }}
<div class="row justify-content-center">
<div class="col-12 col-md-9 mt-3 ">
<div class="font-weight-bold align-center">Gönüllü Dersi :
{% for x in ders %}
{{ x.gonullu }} {% if x.birinci_ders != null %} {{ x.birinci_ders }} {{ x.birinci_ders_seviye }} {% endif %}
{% endfor %}
</div>
</div>
</div>
<div class="row justify-content-center">
<table class="table table-hover">
<thead>
<tr data-toggle="collapse" data-target="#accordion" class="clickable">
<th scope="col">Id</th>
<th scope="col">Öğrenci</th>
<th scope="col">Sınıf</th>
<th scope="col">Aktif</th>
<th scope="col">Devamsızlık</th>
</tr>
</thead>
<tbody>
{% for y in devamsizliklar %}
<tr>
<td id="accordion" class="collapse">{{ y.id }}</td>
<td id="accordion" class="collapse">{{ y.ogrenci }}</td>
<td id="accordion" class="collapse">{{ y.sinif }}</td>
<td id="accordion" class="collapse">{{ y.aktif }}</td>
<td id="accordion" class="collapse">
<div class="form-group row">
<div class="col-sm-10 col-md-7">
<input data-handle-width="20" data-label-width="1" data-size="mini"
{{ form|validation_class:"devamsizlik" }} id="devamsizlik" name="devamsizlik"
{% if form.devamsizlik.value %}checked{% endif %} class="form-control swich-check"
type="checkbox">
{{ form.devamsizlik|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">
<label for="gonulu" class="col-sm-2 col-md-5 col-form-label">Gönüllü*</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"gonulu" }}" name="gonulu"
id="gonulu" required>
<option value="{{ gonulu.gonullu.pk }}" selected="selected">{{ gonulu.gonullu|safe }}</option>
</select>
{{ form.gonulu|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">>
<label for="ad" class="col-sm-2 col-md-5 col-form-label">Öğrenci*</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"ogrenci_dersi" }}" name="ogrenci_dersi"
id="ogrenci_dersi" required>
<option value="{{ y.ogrenci.ogrenci.pk }}" selected="selected">{{ y.ogrenci.ogrenci|safe }}</option>
</select>
{{ form.ogrenci_dersi|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">>
<label for="ad" class="col-sm-2 col-md-5 col-form-label">Sınıf</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"sinif" }}" name="sinif"
id="sinif" required>
{% for x in siniflar %}
<option value="{{ x.pk }}" selected="selected">{{ x|safe }}</option>
{% endfor %}
</select>
{{ form.sinif|f_errors }}
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!--submit-->
<div class="row justify-content-center">
<button type="submit" name="save" value="save"
class="btn btn-primary mb-2 float-left bg-c b-0 rounded-0">
Devamsızlık bilgilerimi güncelle
</button>
</div>
</form>
And thats is the form.py
class DevamsizlikDetayForm(forms.ModelForm):
class Meta:
model = GonulluOgrenciDevamsizlik
fields = '__all__'

I am using django for a project and i got this error

I am doing a project in Django and i got this error.How is this occurs?
NoReverseMatch at /
Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$']
urls.py
from django.urls import path
from accounts import views
urlpatterns = [
path('',views.home, name="home"),
path('product/',views.products, name="product"),
path('customer/<str:pkid>/',views.customer, name="customer"),
path('create_order/<str:pk>/',views.createOrder, name="create_order"),
path('update_order/<str:pk>/',views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/',views.deleteOrder, name="delete_order"),
]
views.py
def createOrder(request, pk):
customer = Customer.objects.get(id=pk)
form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid:
form.save()
return redirect('/')
context = {'form':form}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" name="Submit">
</form>
{% endblock %}
customer.html`
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row" style="margin: auto;">
<div class="col-md">
<div class="card card-body">
<h5>Customer:{{customer.name}}</h5>
<hr>
Update Customer
Place Order
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Orders</h5>
<hr>
<h1 style="text-align:center;padding:10px">{{total_orders}}</h1>
</div>
</div>
</div>
<br>
<div class="row" style="margin: auto;">
<div class="col">
<div class="card card-body">
<form method="get">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row" style="margin: auto;">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.product.name}}</td>
<td>{{order.product.category}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td><a class="btn btn-sm btn-warning" href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Remove</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
In your HTML write action=" {%url 'create_order' order.id%}"

Django and HTML template : Group by panels with common object attributes

One more time, I come back to you in order to get advices or your help.
I'm displaying in my django template a list of objects and I would like to sort them through a common attributes : category.
Each object displayed (a publication) gets some attributes : category, format, language ...
For example :
The white text with blue background indicates the category. I have 2 publications with category = BIOLOGICAL STANDARDISATION PROGRAMME and 1 publication with category = TEST
I would like to group both BIOLOGICAL STANDARDISATION PROGRAMME in one panel but I don't find a way to do that.
This is my HTML template file :
{% for element in test_research|dictsort:"publication.category.name" %}
<div class="col-sm-12">
<div class="panel panel-default request-panel">
<div class="panel-heading" role="tab">
<h4 class="panel-title">
{{ element.publication.category }}
</h4>
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-9">
<p class="request-publication">{{ element.publication }} </p>
</div>
<div class="col-sm-3 request-cover">
{% if element.publication.cover %}
<a href="{{ element.publication.cover.url }}" target="_blank">
{% thumbnail element.publication.cover "40x40" crop="center" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}</a>
{% endif %}
</div>
</div>
</div>
<div class="panel-footer">
<div class="row">
<table>
<tbody>
<tr>
<td class="col-md-1">
<div class="material-switch pull-right">
<input id="someSwitchOptionSuccess_{{ element.id }}" name="DocumentChoice" type="checkbox"
value="{{ element.id }}"/>
<label for="someSwitchOptionSuccess_{{ element.id }}" class="label-success"></label>
</div>
</td>
<td class="col-md-1 request-language"> {{ element.language }}</td>
<td class="col-md-1 request-format">
{% if element.format == 'pdf' %}
<span class="badge alert-danger">{{ element.format }}</span>
{% endif %}
{% if element.format == 'epub' %}
<span class="badge alert-info">{{ element.format }}</span>
{% endif %}
</td>
<td class="col-md-1 request-flag">
{% if element.publication.new_publication == True %}
<span class="glyphicon glyphicon-flag"></span>
{% else %}
<span></span>
{% endif %}
</td>
<td class="col-md-offset-5 col-md-3 text-right">{{ element.title }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endfor %}
And in my views.py file :
def get_context_data(self, **kwargs):
search_category = Document.objects.values_list('publication__category__name', flat=True).distinct()
kwargs['search_category'] = search_category
search_format = Document.objects.values_list('format', flat=True).distinct()
kwargs['search_format'] = search_format
search_language = Document.objects.values_list('language', flat=True).distinct()
kwargs['search_language'] = search_language
checkbox_category = self.request.GET.getlist('CategoryChoice')
checkbox_format = self.request.GET.getlist('FormatChoice')
checkbox_language = self.request.GET.getlist('LanguageChoice')
choice_title = self.request.GET.get('TitleChoice')
kwargs['checkbox_category'] = checkbox_category
kwargs['checkbox_format'] = checkbox_format
kwargs['checkbox_language'] = checkbox_language
kwargs['choice_title'] = choice_title
# default to all documents
test_research = Document.objects.all().order_by('publication__category__name')
kwargs['test_research'] = test_research
if "SubmitChoice" in self.request.GET:
test_research = Document.objects.all()
# if user entered any search criteria, add those filters
if checkbox_category:
test_research = test_research.filter(publication__category__name__in=checkbox_category)
if checkbox_format:
test_research = test_research.filter(format__in=checkbox_format)
if checkbox_language:
test_research = test_research.filter(language__in=checkbox_language)
if choice_title:
test_research = test_research.filter(
Q(title__icontains=choice_title) | Q(publication__title__icontains=choice_title))
kwargs['test_research'] = test_research
return super(HomeView, self).get_context_data(**kwargs)
I can add models.py file if necessary. How it's possible to group them under the same category panel ?
EDIT :
I maybe found something with that :
{% for category in checkbox_category %}
<div class="col-sm-12">
<div class="panel panel-default request-panel">
<div class="panel-heading" role="tab">
<h4 class="panel-title">
{{ category }}
</h4>
</div>
{% for element in test_research %}
{{ element.publication.category }} - {{ category }}
{% if element.publication.category == category %}
But the if condition doesn't seems to work even if {{element.publication.category}} == {{category}}
You should restructure your data in the view so that it's already prepared for the template. Django's template system is built in a way to avoid this type of logic.
You might be able to do it simply like this:
from collections import defaultdict
research_categories = defaultdict(list)
for element in test_research:
research_categories[element.publication.category].append(element)
Then use research_categories in your template.