Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error with authentication (Django Rest Framework + JWT Auth)
I've been working on my first Django Rest Framework project and I'm having some trouble getting my JWT authentication to work properly. Upon logging into my (React) app, everything works as intended, but when coming back to the app after several hours and doing something in the site that requires authentication, I get the following error instead of the token being refreshed or redirected to my login screen. I'm totally new to authentication, and my code for my JWT Auth is taken from this tutorial, so I'm not completely sure if I've goofed something up or if the tutorial code isn't working properly. I suspect the issue is on the front-end, so here is my axios file where I handle the token refreshes (again, taken from the tutorial code) https://github.com/aesakof/gas-app-v2/blob/main/react-frontend/src/axios.js One issue that is probably notable and that I changed from the tutorial's code is that on line 9 of that file, I changed it to "Bearer " from "JWT " as with JWT I was getting not authorized errors when making requests. As I said I'm very new to JWT and working with authentication in general, so any help would be greatly appreciated! -
How do I go about putting my image classifier in a django server, so various appliances can access it?
I recently created an image classifier for an application, but it turned out to be a way larger of a file than I anticipated, so I looked up on various ways to find a way of compressing it, but that was in vain. So I thought of creating a django server where I could store this classifier, which I could then access with any device. I looked up tutorials, on exactly what I want, but they were all just full django tutorials. So im kinda stuck at this point, so can someone help me with what im exactly supposed to learn/do? Thanks! -
Django Rest Framework - An invalid form control with name='' is not focusable
I've been working with DRF HTML & Forms. I've encountered an issue while playing with it, and I was wondering if that has already happened before. The issue is related to this topic in Stack Overflow. Basically, I'm capable of rendering the form with the prepopulated data, but when it comes to sending the PATCH request to update. I get this: An invalid form control with name='name' is not focusable. An invalid form control with name='jobTitle' is not focusable. An invalid form control with name='salary' is not focusable. Here my requirements.txt: djangorestframework==3.12.4 # https://github.com/encode/django-rest-framework django-cors-headers==3.10.0 # https://github.com/adamchainz/django-cors-headers django==3.2.9 Here is my view.py: class UserRetrieveUpdateView(RetrieveUpdateAPIView): renderer_classes = [TemplateHTMLRenderer] permission_classes = [IsAuthenticated] template_name = "users/modals/user_modal_update.html" queryset = UserPie.objects.all() serializer_class = UserPieSerializer lookup_url_kwarg = "user_pk" def get(self, request, user_pk): user = get_object_or_404(UserPie, pk=user_pk) serializer = self.get_serializer(user) return Response({"serializer": serializer, "user": user}) Here is my template: {% load static %} {% load rest_framework %} <div class="modal fade" id="userFormModalUpdate" tabindex="-1" aria-labelledby="userFormModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="userFormModalLabel">Update existing user</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form id="formUser" action="{% url 'users:form' user_pk=user.pk %}" method="patch"> {% csrf_token %} {% render_form serializer %} </form> </div> <div class="modal-footer d-flex justify-content-center "> <button type="button" … -
I want to simulate/mimic an "external API" which will send certain responses to my Django project?
I am creating a web application for data visualizations and analytics. I am using Django for that purpose. Now the problem is that, in normal circumstances, this project will take its data (for visualizations purposes) from an external API owned by someone else. And for me to access that API I need to prove my identity and go through many formalities. To avoid this time-gap, I want an app to mimic those external APIs. Basically I want to tell the mimic to throw certain Responses on certain API endpoints. I heard that "Postman" is good for the purpose but don't have any idea even if it will help me. I'm also open to any alternatives, if any. P.S. I'm new to all this web-app stuff so I have no idea If my question is valid. Im working on Windows 10 platform Also this is an educational project by the way. It is not meant for any profit. -
Django: filter ManyToManyfield of all objects in QuerySet
I basically want to do something like this: I want a distinct list of all products from all completed orders, but I want to save/annotate? the order reference('refCode') to the Product object. Order.objects.filter(is_completed=True).order_by('-date_created').products.all().filter(dlLocation__isnull=True).distinct() Notice the ".products.all()". Unfortunately this is no valid code. So my solution was to make 2 seperate querysets like so: completedOrders = Order.objects.filter(is_completed=True).order_by('-date_created').values_list('refCode', 'products', named=True) #<QuerySet [Row(refCode='7822788', products=307691), Row(refCode='7822788', products=307905) Row(refCode='4083860', products=307874)]> downloads = Product.objects.filter(topicID__in=completedOrders.values('products')).filter(dlLocation__isnull=True).distinct() #<QuerySet [<Product: product12>, <Product: product43>, <Product: product35>> How can I insert a Product object on its matching topicID in completedOrders Row dict? The result could be something like this: #<QuerySet [Row(refCode='7822788', products=<Product: product12>), Row(refCode='7822788', products=<Product: product43>) Row(refCode='4083860', products=<Product: product35>)]> Order models.py: class Order(models.Model): refCode = models.CharField(max_length=15, unique=True, primary_key=True, default=generateOrderRefCode) products = models.ManyToManyField(Product) is_completed = models.BooleanField(null=False, default=False) Product models.py: class Product(models.Model): topicID = models.IntegerField(null=False, unique=True, primary_key=True) dlLocation = models.CharField(max_length=200, null=True, blank=True) Excuse me for my bad explanation and grammar faults, this is the first time I have to ask a question to StackOverflow and my head is basically broken from working on this project too long, or I am going crazy lol. Thank you in advance and I wish u a life filled with love and joy <3 -
Form is invalid but no errors
Whenever I submit the form, it is invalid and there is no error message attached to it when I try to read it with form.errors; it's empty. Here is what I have: models.py class Project(models.Model): project = models.CharField(unique=True, max_length=50) is_active = models.BooleanField(default=False) forms.py from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Row, Column, Submit, Field class SelectProjectForm(forms.Form): def __init__(self, active_choices, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['is_active'] = forms.ChoiceField(choices=active_choices, widget=forms.Select) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout( Row( Column(Field('is_active')) ), Row( Column(FormActions(Submit('activate', 'Activate Project'))) ), ) views.py class ProjectSettings(LoginRequiredMixin, TemplateView): template_name = 'Home/project_settings.html' def get(self, request, *args, **kwargs): active_choices = [] for project in Project.objects.all(): active_choices.append((project.id, project.project),) return render(request, self.template_name, {'create_project_form': ProjectSettingsForm(), 'form': SelectProjectForm(active_choices)}) def post(self, request, *args, **kwargs): if 'activate' in request.POST: form = SelectProjectForm(request.POST) if form.is_valid(): .... messages.error(request, 'Something went wrong') return redirect('project_settings') I think the problem might be in the POST method in views where I initialize the form, but I don't know how to pass the active_choices parameter in post. If that is not the problem then I am lost. -
Django how to split data by unique key using dynamic URL?
I am making Django API. I collected place and review data using crwaling program. I want to split review data by place name, but it seems all reviews are saved together and is spread to all URL. models.py from django.db import models import uuid # Create your models here. from django.utils.text import slugify def generate_unique_slug(klass, field): origin_slug = slugify(field, allow_unicode=True) unique_slug = origin_slug numb = 1 while klass.objects.filter(slug=unique_slug).exists(): unique_slug = '%s-%d' % (origin_slug, numb) numb += 1 return unique_slug class BuildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, allow_unicode=True, default=uuid.uuid1) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) #building_time = models.CharField(max_length=50) def save(self, *args, **kwargs): if self.slug: # edit if slugify(self.building_name, allow_unicode=True) != self.slug: self.slug = generate_unique_slug(BuildingData, self.building_name) else: # create self.slug = generate_unique_slug(BuildingData, self.building_name) super(BuildingData, self).save(*args, **kwargs) class ReviewData(models.Model): building_name = models.CharField(max_length=50) review_content = models.TextField() star_num = models.FloatField() urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<str:slug>/', ReviewListAPI.as_view()) ] A part of crwaling program if __name__=='__main__': for item in building_dict: BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call']).save() #BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call'], building_time = item['time']).save() for item in … -
How to disable cookies for all-auth cookie in safari
I implemented social login in django. In settings.py i added "allauth.socialaccount.providers.google", On the site i added a button google signin. When i use chrome as a browser everything works fine, the user is signed in over and over again. However with safari i have a problem. The first time when ik log in with the google sign in the user is logged in fine. But when i log out the user and try to login again in django its giving me a this error " Social Network Login Failure An error occurred while attempting to login via your social network account." The solution seems to be to delete the cookie in safari of my site. If i then login again its working fine. Is it possible to disable the cookie for allauth ? -
How to escape '/' in django urls
I am working on a project that generates dynamic urls for eg if you type mysite.com/<yourtexthere> The site should generate a url with mysite.com/yourtexthere (where yourtext here is a slug of a model)and I am able to do that but the problem arises when I put something like this mysite.com/yourtexthere/moretext, Django doesn't match it with any of my existing URL patterns and gives me 404. I wanted to ask is there a way by which I can treat '/' as just another character and generate unique url mymysite.com/yourtexthere/moretext where yourtexthere/moretext is now the slug. views.py def textview(request, slug): obj, created= Text.objects.get_or_create(slug=slug, defaults={'text':'', 'password':'123'}) return render(request, 'text/textpage.html', {'obj' : obj, 'created' : created}) urls.py # Only patterns urlpatterns = [ path('', home, name='home'), path('<slug:slug>/', textview, name='textview'), ] -
Django allauth - how to send users that just signed up with Google to an intermediate screen where they fill out additional informations
I integrated django-allauth with my Django app but I would like to make a small tweak on the current sign-up flow. Problem Currently if a user uses google sign-up to sign-up on my app, django-allauth creates an account for them extracting a certain amount of informations from google and then send the user to the home-page. Desired behavior I would like users who just finished the authentication process through google/allauth,to be sent to an intermediate screen (that they can skip if they really want) where they are asked additional informations (like phone number) so that I can complete their profile. Setup I have a custom user model where email is the main unique id of a user. from django.contrib.auth.base_user import BaseUserManager from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and … -
How to get Photos of each Product using foreign key and show in a list view django?
I'm working on a ecommerce website and i wrote a model for a Image album for each Product. But when i want to show products in a list view all of images will be show for each product. What should i do to show photos that related to each product? Here is my models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) image = models.ImageField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%y/%m/%d') def __str__(self): return self.product.name Using ProductImage class i can add multiple photos for each product. and other problem is that if i have product with 5 photos i want to show only first two photos in list view and not all of them.what should i do for this problem? Here is my admin.py: class ProductImageAdmin(admin.StackedInline): model = ProductImage @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ProductImageAdmin] list_display = ['name', 'slug', 'price', 'available', 'created', 'updated'] list_filter = ['available', 'created', 'updated'] list_editable = ['price', 'available'] prepopulated_fields = … -
django get lazy reference by Model
To get model from lazy reference, we can do from django.apps import apps Article = apps.get_model('articles.Article') # app.Model But what about the reverse for it? I mean to get the lazy reference app.Model by Model class. from articles.models import Article # something like print(Article.lazy_reference) # <str> articles.Article you probably wonder why I do this, I need to tract user initiative and passive actions, there's no modelfield in django, hence I store the model reference and pk as indication. -
Unable to hit api with other pc on the same network for a multi tenancy application in django
I have successfully applied multi tenancy architecture with same database and separate schema for each tenant using Django and postgresql. But while trying to access the api's with a computer on the same network using the ip address I am getting 404 Not found. While on the main computer I am able to hit the api using localhost when the tenant domain is tenant1.localhost and to allow other computers on the same network I tried changing tenant domain to <my_ip>.tenant1 but it is not working. Any help would be appreciated. -
Get data from django database
So,how get data from django database?I have django models and created 2 objects there.I want to get 2 objects and write in html file. admin panel: https://i.stack.imgur.com/7WUZr.png view.py def vds(request): HTML_STRING = render_to_string("vds.html", context=context1) return HttpResponse(HTML_STRING) VDSTARIFS_obj = VDSTARIFS.objects.get(id=1) context1 = { "prise": VDSTARIFS_obj.prise, } file with models class VDSTARIFS( models.Model): prise = models.CharField(max_length= 10,) def __str__(self): return str(self.prise)``` -
Django html templates issue
I am a beginner in python. I scraped a website title and dates but dates are in different formats like Dec 4, 2021 and Dec 04, 2021. I used the condition to compare these dates from today's date so that my data will be present if the date matches the requirnment but when I used the below function in the HTML template by using Django it didn't work. The reason is that it only includes one space gap either I need 2 spaces between ", and 2021". nows = datetime.datetime.today() today_date=nows.strftime( "%b %d, %Y").replace(' 0', ' ') when i call today_date in html template it shows me only one gap like this 'Dec 4, 2021' and i need this 'Dec 4, 2021 result1=result.loc[data['LastUpdated']== today_date] json_records1=result1.reset_index().to_json(orient='records') arr1=json.loads(json_records1) ab={'abc':arr1} return render(request, "index.html",ab) This is my HTML template where I call today date {{abc}} If someone knows then kindly solve my problem. -
"This field is required." in DRF serializers
I am facing an issue in DRF serializers. I have a model named Issue which has a foreign Key of User Model to save the user who has created the particular Issue. Now the Get request is working fine when I request to get the issues I get it perfectly fine with username who has created the issue, but when I do the post request I get the error on "created_by" field that "This field is requied" even though I am providing this field. Following is my code: Model class Issues(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='issue_created_by') title = models.CharField(max_length=225, default='', null=False) details = models.CharField(max_length=1000, default='') created_on = models.DateField(default=timezone.now) tags = models.CharField(max_length=225, blank=True, null=True, default='') Issue Serializer class IssueSerializer(serializers.ModelSerializer): created_by = UserSerializer() class Meta: model = Issues fields = ['created_by', 'title', 'details', 'created_on', 'tags'] UserSerializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = super().create(validated_data) user.set_password(validated_data['password']) user.save() return True views.py class IssueView(viewsets.ViewSet): def create(self, request): serialized_issues = IssueSerializer(data=request.data) if serialized_issues.is_valid(): serialized_issues.save() return Response({'message': 'Issue Created', 'status': status.HTTP_200_OK}) else: return Response({'error': serialized_issues.errors, 'status': status.HTTP_400_BAD_REQUEST}) def list(self, request): all_issues = Issues.objects.all() serialized_issues = IssueSerializer(all_issues, many=True) return Response(serialized_issues.data) -
How to use dynamic global variables in Django view functions?
I now need to use RPY2 to get some value in one view and use that value in another view. In the development environment:it works view.py: PACds='abc' #Defining global variables def upload(request): global PACds robjects.r.source(path+"Upload.R") PACds=robjects.r.readPAC(.....) #Storing data globally def use(request): # Using the global variable But when deployed to the server, ajax requests using the Use view had a strange problem: PACds=' abc' was the global variable accessed the first time and changed the value the second time. Is there a better way to solve this problem? or Is it possible to save R type values obtained using RPY2 in one view and used in another view? Software version: Django 3.1 Python 3.8 rpy2 3.4.5 -
I am new to Django and just follow the Django official document, but here is a problem
I need to upload to another html template whose name depends on the variable that the server gives. How to make it work? I'm trying to do this: {% include 'ui_interface/tables/{{ item.product.title }}.html' %} But it gives an error: TemplateDoesNotExist at / in which the link to the template looks like this: Exception Type: TemplateDoesNotExist Exception Value: ui_interface/tables/{{ item.product.title }}.html that is, it does not translate the variable in the template engine -
how do I style and align errorlist from django forms?
This form errorfield comes with ul and li elements and I can't find a way to change it. So is it possible to have "email is taken" as error instead of having the whole ul element "email" before that, if that's not possible then can we at least align it inline together the ul and li. Thx in advance. css .errorlist li { list-style-type: none; display: inline-block; } .account-errors { font-family: "Circular Std Book"; color: black; } html {% if form.errors %} <div class="account-errors"> <div class="container-error"> {{ form.errors }} </div> </div> {% endif %} -
Changing column names of a database table created using django
Actually, I've created a model class in which I have a few attributes(column names). Is it possible for me to change the names of the column using class Meta? I'm just curious. I do know that we could just directly change the attributes themselves. I'm just exploring Meta Class. I'm new to Django and the whole framework thing. So a basic detailed answer would be of real help. You can correct me if I misunderstood the purpose of Meta Class. Thanks in advance :) -
Django_custom_filter for orders and servicess
i want to make a filter on orders model which filters orders based on services provided by a launderette in the order Here are my models: class Launderette(models.Model): launderer = models.ForeignKey(Launderer, null=True, on_delete= models.SET_NULL) name = models.CharField(max_length=200, null=True) available_time = models.CharField(max_length=500, null=True, blank=True) cover_photo = models.ImageField( default="0_GettyImages-1068728612.jpg") location = models.CharField(max_length=200, null=True) isBlocked = models.BooleanField(default=False) date_joined =models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.name) class Services(models.Model): launderette = models.ForeignKey(Launderette, null=True, on_delete= models.SET_NULL) title = models.CharField(max_length=200, null=True) price = models.FloatField(default=0) def __str__(self): return str(self.title) class StatusChoice1(models.TextChoices): PENDING = 'pending', 'Pending' FINISHED = 'finished', 'Finished' ONGOING = 'ongoing', 'Ongoing' DECLINED = 'declined', 'Declined' Canceled = 'canceled', 'Canceled' class Order(models.Model): client = models.ForeignKey(Client, null=True, on_delete= models.SET_NULL) launderette = models.ForeignKey(Launderette, null=True, on_delete= models.SET_NULL) description = models.TextField(blank=True, null=True) price = models.FloatField(default=0) amount = models.FloatField(default=0) services = models.ManyToManyField(Services) status =models.CharField(max_length=50, blank=True, null=True, choices=StatusChoice1.choices,default=StatusChoice1.PENDING) date_started = models.DateTimeField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) date_end = models.DateTimeField(null=True, blank=True) def __str__(self): return str(self.client.user.username) Here is my current filter: class OrderFilter2(django_filters.FilterSet): start_date = DateFilter(field_name="date_started", lookup_expr='gte') end_date = DateFilter(field_name="date_end", lookup_expr='lte') start_price = NumberFilter(field_name="price", lookup_expr='gte') end_price = NumberFilter(field_name="price", lookup_expr='lte') start_amount = NumberFilter(field_name="amount", lookup_expr='gte') end_amount = NumberFilter(field_name="amount", lookup_expr='lte') client_name = CharFilter(field_name='client__name', lookup_expr='icontains') status = ChoiceFilter(choices=FILTER_CHOICES, ) class Meta: model = Order exclude = '__all__' fields = ['start_date', 'end_date', … -
Nested serializers and data representation
Working on a django project I am a bit stuck on data representation through APIs. In fact when designing models the data model is quite stratighforward : I have a one to many relationship A--> B therefore I have added a FK to object B. Object B has a boolean attribute "active". I would like to make an API call to list all A objects having at least one assoicated object B with active = true. The api could be like this : /api/objectA/?investment.active=True Thanks for your help. -
django write signal handler as class (write class based django signal handlers)
From django docs it is clear that we can write signals handlers as function. from django.db.models.signals import pre_save from django.dispatch import receiver from myapp.models import MyModel @receiver(pre_save, sender=MyModel) def my_handler(sender, **kwargs): ... Is it possible to write the signal handlers as classes? If yes HOW? -
Cannot render data from REST API's GET (managed in Django) response in React
I am having the issue of data not being rendered from API response in React even though I do receive it. I have the following "Admin-Notification" component: import React from "react"; import './Admin-notifications.css'; import axios from 'axios'; class AdminNotifications extends React.Component { constructor(){ super(); this.state = { events:[ { "id": 1, "name": "Fotosinteza plantelor", "start_date": 1637496120, "end_date": 4098071460, "location": "Cluj-Napoca", "description": "Aduceti planta", "status": "pending", "id_organizer": 2, "id_type": 1 }, { "id": 2, "name": "Cantecul greierilor de peste imas", "start_date": 1637669280, "end_date": 4098071460, "location": "Imas", "description": "In padurea cu alune aveau casa 2 pitici", "status": "pending", "id_organizer": 2, "id_type": 1 }, { "id": 4, "name": "test", "start_date": 1637518260, "end_date": 4098071460, "location": "test", "description": "test", "status": "pending", "id_organizer": 2, "id_type": 1 } ] } this.state2={ events:[], } } getEvents(){ axios .get("http://127.0.0.1:8000/api/getevents") .then(response =>{ this.state2.events = response.data; }) .catch(err => console.log(err)); }; render(){ this.getEvents(); console.log(this.state); console.log(this.state2); const {events} = this.state2; return( <main className="mw6 center main"> { events.map((event)=>{ return( <article key={event.id} className="dt w-100 hight padd bb pb2 component" href="#0"> <div className="col-md-3"> <div className="dtc w2 w3-ns v-mid"> {/* <img src={event.img} alt="event image from organizator" className="ba b--black-10 db br-100 w2 w3-ns h2 h3-ns"/> */} </div> <div className="dtc v-mid pl3"> <h1 className="f6 f5-ns fw6 lh-title black … -
Display only one value of column value in django templates
I'm using post_list for my website. I added a column "type in my model" But i can only load it in a loop "for" and it finaly display multiple "type" in my template. But I want to display it just one time in the top of my web page: Here is example with 2 posts with same "type" : bad If i have only one post in this "type" it's good : good model.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) postpic = models.TextField(max_length=140, default='SOME STRING') type = models.TextField(max_length=140, default='blog') class Meta: ordering = ['-created_on'] def __str__(self): return self.title I used "queryset" with filter to created different view depending of the type of post: views.py: class ProgList(generic.ListView): queryset = Post.objects.filter(status=1, type="programmation").order_by('-created_on') class WebList(generic.ListView): queryset = Post.objects.filter(status=1, type="web").order_by('-created_on') class OsintList(generic.ListView): queryset = Post.objects.filter(status=1, type="osint").order_by('-created_on') class ForensicList(generic.ListView): queryset = Post.objects.filter(status=1, type="forensic").order_by('-created_on') class PostList(generic.ListView): queryset = Post.objects.filter(status=1, type="blog").order_by('-created_on') I think there is a better way to do this but i'm noob in django. And finaly I load the posts in one template called post_list.html : template Thanks for your help ! …