Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image created in views isnt being rendered in template django
Im trying to render a simple graph that i create with matplotlib in my template. I want to render the graph in the body of the page not just return an HttpResponse with that graph. But i cant get it to work. Here is what i tried. views.py code def showGraph(request): content_x = [10, 20, 30] content_y = ['one', 'two', 'three'] plt.bar(content_x, content_y) plt.title('Some chart') plt.show() buffer = io.BytesIO() canvas = plt.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") content_type = "Image/png" buffercontent = buffer.getvalue() graphic = (buffercontent, content_type) plt.close() return render(request, 'projectRelated/LAN/graphs.html', {'graphic': graphic}) html page code {% extends 'base.html' %} {% load static %} {% block container_content %} <img src="data:image/png;base64,{{ graphic }}"> {% endblock container_content %} The above code just displays a random icon.. -
JQuery-File-Upload using Signed_URL Google Storage, how to call super class function data.submit() within ajax callback?
I have a fileupload HTML element in my DOM and it currently gets multiple files and calls "add" function for each file. For each file, a signed url is received from an ajax call to the related api. After the succesful ajax call to api, I want to call the data.submit() method of the parent function which is the function in fileupload method as first argument. How may I be able to access that just after "xhr.setRequestHeader('Content-Type', file.type);" ? The primary inspiration is from this link :http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/ $("#fileupload").fileupload({ dataType: 'json', sequentialUploads: true, add: function(e, data) { $.each(data.files, function(index, file) { // pack our data to get signature url var formData = new FormData(); formData.append('filename', file.name); formData.append('type', file.type); formData.append('size', file.size); // Step 3: get our signature URL $.ajax({ url: '/api/getsignedurl/', type: 'POST', processData: false, contentType: false, dataType: 'json', headers: { 'X-CSRFToken': Cookies.get('csrftoken'), }, context: 'hello', data: formData, }).done(function (data) { // Step 5: got our url, push to GCS const xhr = new XMLHttpRequest(); if ('withCredentials' in xhr) { xhr.open("PUT", data.signed_url, true); } else if (typeof XDomainRequest !== 'undefined') { xhr = new XDomainRequest(); xhr.open("PUT", data.signed_url); } else { xhr = null; } xhr.onload = () => { const status = … -
How to stop Django PasswordInput prefilling form
I am trying to create a django form to allow users to login. forms.py class LoginForm(forms.ModelForm): username = forms.CharField(label='User name', max_length=30) password = forms.PasswordInput() class Meta: model = User fields = '__all__' widgets = {'password': forms.PasswordInput()} views.py def login_view(request): form_context = {'login_form': LoginForm,} url = "users/login.html" if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) ... else: context = form_context return render(request, url, context) login.html <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ login_form.username.label_tag }}</td> <td>{{ login_form.username }}</td> <td rowspan="2"><button type="submit" class="btn btn-success">Login</button></td> </tr> <tr> <td>{{ login_form.password.label_tag }}</td> <td>{{ login_form.password }}</td> </tr> </table> </form> The problem I have is that if the line widgets = {'password': forms.PasswordInput()} is used, then the form is pre-filled with username and password If the line is commented out, the the form is not prefilled, but the password is in plain text. What is wrong here? -
What do you think about my idea to build my personal finance tracker with Django - too ambitious? [closed]
I would love to have feedback on my idea. Thanks in advance :) First of all: Im relatively new to Python and Programming in general. I did a lot of tutorials, learned the standard syntax and tried out a lot of modules. I feel like I don't learn enough anymore and want to have my first real big project to really get out of the watch-tutorial-flow and really learn the modules by working with them. My idea: A personal finance tracker: I thought about using Django, because i want to learn a popular Web-Framework. I thought about dividing it into different apps: In one app you should be able to input data of the expenses(price, category, automatic timestamp, etc.) that is going to be saved to a database (sqlite) In another app you should have an (interactive) dashboard, that uses the data from the database and plots some graphes etc. optional: User-System to make the Webapp usable for other people Update sqlite to MySQL or other bigger databases Use some API or something to get data from your bank, so you don't need to manually type in the expenses My questions: Is the project too ambitious/to big? As I already … -
Is possible to update or create objects just using django bulk_create
In some cases I need to update existing objects in others I need to create them. It is possible to use a mixed list of updated/created objects to bulk_create() so I don't have to use save() for the updated objects? -
Synchronized Model instances in Django
I'm building a model for a Django project (my first Django project) and noticed that instances of a Django model are not synchronized. a_note = Notes.objects.create(message="Hello") # pk=1 same_note = Notes.objects.get(pk=1) same_note.message = "Good day" same_note.save() a_note.message # Still is "Hello" a_note is same_note # False Is there a built-in way to make model instances with the same primary key to be the same object? If yes, (how) does this maintain a globally consistent state of all model objects, even in the case of bulk updates or changing foreign keys and thus making items enter/exit related sets? I can imagine some sort of registry in the model class, which could at least handle simple cases (i.e. it would fail in cases of bulk updates or a change in foreign keys). However, the static registry makes testing more difficult. I intend to build the (domain) model with high-level functions to do complex operations which go beyond the simple CRUD actions of Django's Model class. (Some classes of my model have an instance of a Django Model subclass, as opposed to being an instance of subclass. This is by design to prevent direct access to the database which might break consistencies and … -
Django generic relations, unique together and abstract models
I have a Tag model and an intermediate model to relate it class Tag(models.Model): name = models.CharField(max_length=255) slug = models.CharField(max_length=255, blank=True) class TagIntermediate(models.Model): # Relation to custom content model content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() customcontent = GenericForeignKey('content_type', 'object_id') # Relation to tag tag = models.ForeignKey(Tag, on_delete=models.CASCADE) class Meta: unique_together = ["content_type", "object_id", "tag"] I add this to an abstract base class class BaseModel(models.Model): blog_tags = GenericRelation('TagIntermediate') class Meta: abstract = True And then I define two models derived from it class ModelOne(BaseModel): model_one_field = models.CharField() class ModelTwo(BaseModel): model_two_field = models.CharField() When I now create a Tag object and add it to a ModelOne object and a ModelTwo object, then I get the message triggered by my "unique together" definition: The combination of content_type, object_id and tag does already exist. Why? ModelOne and ModelTwo should be two different content_types, right? Or did I forget something? I`m using Django Version 3.0.4 -
Displaying data in Django by grouping
Basically, I have worked on this project and I am stuck in displaying the data according to my needs on the html page. Right now all that is shown is the 0-4 data but I'm unsure of how to show it correctly. For the children: I want it to show the user's children. For the timeline: Depending on which child is selected, the timeline table will show the data from the specific child.I want to group the data by age range (the column headers) and then when clicked, it will show the pdfs associated with the current timeline cell. My views file: def timeline(request): timeline = Timeline.objects.all() return render(request, 'timeline.html', { 'timeline': timeline }) My model file: HEADER_CHOICES = [ ('Financial Support', 'Financial Support'), ('Educational Support', 'Educational Support'), ('Governmental Support', 'Governmental Support '), ('Charity Support Groups', 'Charity Support Groups'), ('Therapy Support', 'Therapy Support '), ('Transport Support', 'Transport Support ') ] AGE_CHOICES = [ ('0-4', '0-4'), ('4-11', '4-11'), ('11-18', '11-18'), ('18-25', '18-25') ] class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) child = models.OneToOneField(Children, on_delete=models.CASCADE) class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE) My html page: {% extends 'pages/home_page.html' %} {% block content %} <style> .rightMenu { position:relative; … -
Django ModelForm ignores the data supplied via form and saves a an existing record
Here are the files, forms.py from django.forms import ModelForm from .models import * class NewCustomer(ModelForm): class Meta: model = Customer fields = ('name', 'mobile_number', 'email', 'address') Views.py from django.shortcuts import render, get_object_or_404, redirect from .models import * from .forms import * # Create your views here. def customers(request): customers = Customer.objects.all().order_by('id') return render(request, "customers.html", {'customers': customers, 'custactive': "active"}) def customer_details(request, pk): customer = get_object_or_404(Customer, pk=pk) return render(request, "customer_details.html", {'customer': customer}) def new_customer(request): if request.method == 'POST': form = NewCustomer(request.POST) if form.is_valid(): customer = form.save(commit=False) customer.name = request.user customer.mobile_number = request.user customer.email = request.user customer.address = request.user customer.save() return redirect ('customers') else: form = NewCustomer() return render(request, "new_customer.html", {'form': form}) Can someone tell me what's wrong with the code? Understandably I need to save new data that I supply with the form. -
Obtaining the fields using the ListView class from Django
I'm learning to manage the ListView class from django, obtain the data is really easy. from django.views.generic import ListView from .models import Fleet class fleet_bbdd_view(ListView): template_name = 'data_app/fleets-bbdd.html' paginate_by = 20 model = Fleet context_object_name = 'FleetsList' But what I can't find is how to obtain the fields of my model and pass they in my context object. Is possible to do this using the ListView class ? I know how to obtain it, in a normal function, but if it is possible I prefer to use ListView class. def getData(request): cols = [i.name for i in Fleet._meta.get_fields()] ctx = {'Cols':cols} return JsonResponse(ctx) Can somebody help me? Thank you very much. -
My Django is showing me importError am i doing it wrong
i tried running my django project on the Virtual Studio IDE , created a virtualEnv, but it does not import anything from the django framework, it always underline the "from" with red indicators.this is the error message am getting ..please i need your help because i still don't know why its happening -
Passing parent object into CreateView for a child object
I'm creating a dashboard to edit a tour app. Per tour I have a child record in which I define steps. The 2 models look like this: models.py class Tour(models.Model): tour_id = models.CharField(primary_key=True,unique=True, max_length=10) country = models.ForeignKey(Countries, models.DO_NOTHING, db_column='country') language = models.ForeignKey(Language, models.DO_NOTHING, db_column='language') lastupddtm = models.DateTimeField(default=timezone.now) productid = models.CharField(max_length=50) title = models.CharField(max_length=50) description = models.CharField(max_length=100) descrlong = models.CharField(max_length=1000) live = models.CharField(max_length=1) image = models.ImageField(upload_to=upload_tour_image, storage=OverwriteStorage(), blank=True, null=True) class Meta: db_table = 'tour' verbose_name_plural = "tour" def get_language_flag(self): return self.language.flag.url def __str__(self): return str(self.tour_id) + ' - ' + str(self.title) + ' - ' + str(self.description) class Toursteps(models.Model): # tour_id = models.OneToOneField(Tour, models.DO_NOTHING, db_column='tour_id') tour = models.ForeignKey(Tour, related_name='toursteps', on_delete=models.CASCADE) step = models.IntegerField(unique=True) title = models.CharField(max_length=50) description = models.CharField(max_length=100) descrlong = models.CharField(max_length=1000) audiotext = models.TextField() latitude = models.FloatField() longitude = models.FloatField() radius = models.FloatField() image = models.ImageField(upload_to=upload_tour_step_image, blank=True, null=True) class Meta: db_table = 'tourSteps' verbose_name_plural = "tourSteps" def __str__(self): return str(self.tour) + "|" + str(self.step) After I created a Tour, I go to a detail page. From there I can click a link to add a step for this tour. This is where the problem is. I pass the tour_id as a variable into the url, but I can't find a … -
Best way to create models for shopping lists in Django
I am thinking how to create models in Django when designing a shopping list. So basically I want to have Shopping Item and Shopping List. Shoping Item can be added to different shopping lists multiple times. Could you please advise on that? -
Django - 'tuple' object has no attribute 'status_code'
I'm trying to save some data to my database, but I keep getting the error. 'tuple' object has no attribute 'status_code'. I'm not entirely sure where i'm going wrong . Models.py class Task(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) admin = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() assigned_to = models.CharField(max_length=30) def save(self, *args, **kwargs): self.slug = slugify(self.text) super(Task, self).save(*args, **kwargs) def __str__(self): return self.text Form.py class CreateNewTask(ModelForm): text = forms.CharField(max_length=300, help_text="Please enter task: ") assigned_to = forms.CharField(max_length=30, help_text="Assigned to: ") complete = forms.BooleanField() slug = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = Task fields = ( 'text', 'assigned_to', 'complete') views.py def createTask(request): form = CreateNewTask() if request.method == "POST": form = CreateNewTask(request.POST) if form.is_valid(): temp = form.save(commit=False) temp.board = Board.objects.get(id=id) temp.save() return redirect("/dashboard") return(request, 'boards/create_task.html', {'form':form}) -
Issue with dropdown submitting selected value - Django/Python
I am trying to get the selected value in the dropdown to add to the cart. The way I have it prints out different dropdowns but submits the data into the cart. I just want one dropdown that submits the selected value. Thank you. {% for product in products %} <form class = 'pull-right' method ='GET' action='{% url "update_cart" product.slug 1 %}'> <select id="menulist"> <option>{{ product.name }}: ${{ product.price }}</option> {% endfor %} </select> <button type = 'submit' class ="btn btn-info btn-md" class ='pull-right'>Add To Order</button> </form> -
django.db.utils.ProgrammingError: relation "fdiary_fdiary" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fdiary_fdiary"
i did everything used python manage.py migrate, etc. But when i click on my model in django admin panel it shows this error. ProgrammingError at /admin/fdiary/fdiary/ relation "fdiary_fdiary" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fdiary_fdiary" ^ Request Method: GET Request URL: http://127.0.0.1:8000/admin/fdiary/fdiary/ Django Version: 3.0.4 Exception Type: ProgrammingError Exception Value: relation "fdiary_fdiary" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fdiary_fdiary" ^ Exception Location: J:\Program Files\Python3.8\lib\site-packages\django\db\backends\utils.py in _execute, line 86 Python Executable: J:\Program Files\Python3.8\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Dell\diary\diary', 'J:\Program Files\Python3.8\python38.zip', 'J:\Program Files\Python3.8\DLLs', 'J:\Program Files\Python3.8\lib', 'J:\Program Files\Python3.8', 'C:\Users\Dell\AppData\Roaming\Python\Python38\site-packages', 'J:\Program Files\Python3.8\lib\site-packages'] Server time: Fri, 3 Apr 2020 20:15:51 +0530 Meta:- ALLUSERSPROFILE 'C:\\ProgramData' APPDATA 'C:\\Users\\Dell\\AppData\\Roaming' COLORTERM 'truecolor' COMMONPROGRAMFILES 'C:\\Program Files\\Common Files' COMMONPROGRAMFILES(X86) 'C:\\Program Files (x86)\\Common Files' COMMONPROGRAMW6432 'C:\\Program Files\\Common Files' COMPUTERNAME 'DESKTOP-S6NQ606' COMSPEC 'C:\\Windows\\system32\\cmd.exe' CONTENT_LENGTH '' CONTENT_TYPE 'text/plain' CSRF_COOKIE 'mNHRnYHHB1kzOdnahlwlppBHiLEKYeO0ghFTgshaQGSXzzbS6aU5TI1rnpkWa9vT' DJANGO_SETTINGS_MODULE 'diary.settings' DRIVERDATA 'C:\\Windows\\System32\\Drivers\\DriverData' GATEWAY_INTERFACE 'CGI/1.1' HOMEDRIVE 'C:' HOMEPATH '\\Users\\Dell' HTTP_ACCEPT 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' HTTP_ACCEPT_ENCODING 'gzip, deflate' HTTP_ACCEPT_LANGUAGE 'en-US,en;q=0.5' HTTP_CONNECTION 'keep-alive' HTTP_COOKIE ('csrftoken=mNHRnYHHB1kzOdnahlwlppBHiLEKYeO0ghFTgshaQGSXzzbS6aU5TI1rnpkWa9vT; ' 'sessionid=amcqamjjcw9chtndh5nzib8nfdv8n1yy; ' 'PGADMIN_INT_KEY=fc56bb57-0d57-4b35-8b29-282be1e4197b; ' 'pga4_session=d8dcf70d-50e4-4474-9aef-6e057e2a6216!P0ZEZvLq08QDIa+4HpmE8XSwdWE=; ' 'PGADMIN_LANGUAGE=en') HTTP_DNT '1' HTTP_HOST '127.0.0.1:8000' HTTP_REFERER 'http://127.0.0.1:8000/admin/' HTTP_UPGRADE_INSECURE_REQUESTS '1' HTTP_USER_AGENT 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0' LANG 'en_GB.UTF-8' LOCALAPPDATA 'C:\\Users\\Dell\\AppData\\Local' LOGONSERVER '\\\\DESKTOP-S6NQ606' NUMBER_OF_PROCESSORS '4' ONEDRIVE 'C:\\Users\\Dell\\OneDrive' ONEDRIVECONSUMER 'C:\\Users\\Dell\\OneDrive' OS 'Windows_NT' PATH ('J:\\Program Files\\Python3.8\\Scripts\\;J:\\Program ' … -
Unable to find static files - Joined path located outside of base path components
Django noob here. My static files are working fine using my local development server, but as soon as I pushed changes to my production server on A2, it could no longer find my static files. For example, it can't find a js file at: https://mywebsite.com/static/js/jquery.waypoints.min.js The file actually exists at: https://mywebsite.com/project_root/static/js/jquery.waypoints.min.js This corresponds to: /home/user/public_html/project_root/static In my settings.py I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'public') When printed, Staticfile_dirs is /home/user/public_html/project_root/static, which seems right. but once I run python manage.py findstatic js/infinite.min.js It gives me the error django.core.exceptions.SuspiciousFileOperation: The joined path (/js/infinite.min.js) is located outside of the base path component (/home/user/public_html/project_root/static) Can someone help me understand what i'm missing? -
Django forms.ChoiceField to be dynamically created based
Im building a website with django where a user could create a shop > choose maximum one of each category > choose multiple products for each category; in that order I have a DetailView which allows them to see the details of the shop and create a category underneath it. I`m using FormMixin to allow them create a category, and a ChoiceField for the type of category. What I want: Let them choose only from the categories they didnt choose in the past, eg: I have 3 categories: Woodworks, Food, Tools; if they already have added a Tools category to their shop, they should be able to choose it again (i want the form not display it at all) My views: class OrganizationDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView, FormMixin): model = Organization queryset = Organization.objects.all().prefetch_related() template_name = 'org/org_view.html' form_class = CategoryForm def test_func(self): org = self.get_object() if self.request.user.profile == org.owned_by: return True return False def get(self, request, *args, **kwargs): # getting the post to display self.object = self.get_object() context = self.get_context_data() categories = Category.objects.filter(org=self.object).values_list('cat_name') context['categories'] = [] for category in categories: context['categories'].append(*category) return self.render_to_response(context) def post(self, request, *args, **kwargs): pk = self.get_object().serializable_value('pk') org_id = Organization.objects.get(org_id=pk) cat_name = self.request.POST.get('cat_name') new_category = Category.objects.create(org=org_id, cat_name=cat_name) return … -
how to use django template language inside script tag using django-jsRender
As I know, there is no way to use Django template language inside Javascript block so I searched for a way how to do it, I found a Django app on GitHub called Django-jsrender but unfortunately, there isn't enough documentation for this app and when I tried to use it I couldn't and this is my code: -
Django serializer "field is required"
I want a serializer to return all the distinct countries. It just query's the db and returns it. But it always return "field is required" on the "countries" field. This is my serializer: class AdminCountrySiteSerializer(serializers.ModelSerializer): countries = serializers.ListField() class Meta: model = Site fields = ["countries"] def get_countries(self): return list( Site.objects.values_list("country", flat=True) .order_by("country") .distinct() ) test class: def test_get_all_distinct_countries(self): self.client.force_login(self.admin_user) url = reverse("admin-site-countries") response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data["countries"]), 3) view: class AdminSiteCountryView(GenericAPIView): def get_permissions(self): return IsAuthenticated(), IsSoundTalksCS() def get_serializer_class(self): return AdminCountrySiteSerializer @swagger_auto_schema( responses={200: openapi.Response(_("Successfully fetched all the countries."),)} ) def get(self, request): """ GET all distinct countries """ serializer_class = self.get_serializer_class() # serializer = serializer_class(data=request.data) serializer = serializer_class(data={"request": request}) serializer.is_valid(raise_exception=True) return Response(data=serializer.data, status=status.HTTP_200_OK,) -
Django Ajax not updating data properly
I am trying to create a like button for my posts in my post list, however, i need to refresh the page every time for the number of likes and button to change. I do not know what's causing this behavior as I am sending all the posts to the post list html file in my view. My 'likes' is a ManyToMany field for the Post model. my post_like view: @login_required def post_like(request,id): data = dict() post = get_object_or_404(Post, id=id) user = request.user if request.method == 'POST': if post.likes.filter(id=user.id).exists(): post.likes.remove(user) else: post.likes.add(user) posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) return JsonResponse(data) my ajax javascript code: $(document).ready(function (e) { $(document).on("click", "#likeBtn", function (e) { e.preventDefault(); var pk = $(this).attr("value"); var tk = $(this).attr("data-token") $.ajax({ type: "POST", dataType: 'json', url: $(this).attr("data-url"), data: {'id':pk, 'csrfmiddlewaretoken': tk}, success: function (data){ $("#post-list div").html(data.posts); }, error: function(rs, e){ console.log(rs.responeText); }, }); }); }) Thanks for all the help in advance! -
Django Logging SystemLogHandler how to encrypt
I use logging.handlers.SysLogHandler in my Django app. I need encrypted data whenever log occurs and send it after encryption. So, do you have any suggestion or solution for this? -
How to save a serial number generated in alert message during form submission in database?
views.py from django.contrib import messages import datetime import random def personal_detail(request): now=datetime.datetime.now() messages.success(request,now.strftime("SKPMMVY%Y%m%d%H%M%S")+str(random.randint(0,99))+str(":\tYour form has been submitted successfully")) apply_online.save() return render(request,'users/applyonline.html') I want to save the serial number that is being generated i've saved others by creating their view like idcard=request.POST.get('idcard') and respectively created their model as idcard=models.CharField(max_length=100,blank=True, null=True) I'm just confused on how I can do the same for messages? -
How can I use a single enum for django model and graphql mutation arguments?
I've defined Django models with fields containing text choices corresponding to enums. The GraphQL API provides mutations (which are not derived from models directly) with arguments of type enum which shall accept the same values as the models only. How can I get rid of my dublication? models.py: class SomeModel(models.Model): class SomeEnum(models.TextChoices): A = "A", _("Option A") B = "B", _("Option B") enum_field = models.CharField( max_length=1, choices=SomeEnum.choices, default=SomeEnum.A, ) schema.py: class SomeEnumSchema(graphene.Enum): A = "A" B = "B" class SomeMutation(graphene.Mutation): class Arguments: some_enum = SomeEnumSchema(required=True) -
Django get all post of a parent category
I'm a begginner in django 3 and i decide to create a simple blog to pratice what i learned . I created a post model with a foreignkey category , and a model category with a self foreign key . Everething work well and i find a way to create my menu , the problem is when i click on the parent i want to have all post for the submenu . For example , I have this menu : *Informatic * Django * HTML - CSS *Graphic If i'm clicking on django , i have all my django post , same for html-css but now i want to have all informatic post , posts who have django + html-css together . I can modify my model Post and instead to have a field with category in foreign key , i could use a manytomanyfield . But i don't want it , because i can forgot to put in informatic or in other category . So what could I do, in a simple way ? Can you explain to me what and how todo , and where i need to put code I'm not sure what code do you need …