Мне нужно связать комментарии с одним постом в django, я понятия не имею, что делать, я самоучка.

мне нужна критическая помощь, мне нужно привязать комментарии к одному посту в django, я понятия не имею что делать

мои модели я думаю, это единственная часть, в которой я знаю, что происходит

from tkinter import CASCADE, Widget
from django.db import models
from django.contrib.auth.models import User

class Post (models.Model):
    id = models.AutoField(primary_key=True)
    name = models.ForeignKey(User, on_delete=models.CASCADE, default='User')
    text = models.TextField (max_length=200)
    posted = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.text
    

class Comment(models.Model):#comment for the requests
    request = models.ForeignKey('sunu_app.Post', on_delete =models.CASCADE , related_name='comments', null=True , blank=True)
    # name = models.ForeignKey(User, on_delete=models.CASCADE , null=True , blank=True)
    text = models.TextField ()
    posted = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.text

Мои взгляды честно говоря, я понятия не имел, что там происходит

# from typing_extensions import Self
from urllib.request import Request
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.shortcuts import render,redirect
from .forms import *
from .models import *

def home(request):
    requests = Post.objects.all().order_by('-posted')
    count = Post.objects.all().count()
    #diplay the comments here and let it save in commentform.view
    comments = Post.comment_set.all()
    
    context = {'requests':requests , 'count':count , 'comments':comments}
    return render(request,'sunu_app/home.html', context)
    # context = {'cases':rooms} the second value is the data
    # you want to pass the first value is what it should be called in the template

def requestform (request):
    form = RequestForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('home')
    context = {'requestform':form}
    return render(request,'sunu_app/RequestForm.html',context)  

def deleteall(request):
    requests = Post.objects.all()
    requests.delete()
    return render(request,'sunu_app/home.html')

def commentform(request ,post_id):
    form = CommentForm(request.POST)
    requests = Post.objects.get(id = post_id)
    #save the comments here and let it display in home.view
    if request.method == 'POST':
        comment = Comment.objects.create{
            request = requests,
        }
        #pls i have no single idea what is goin on here
    
    context = {"commentform":form}
    return render(request,'sunu_app/CommentForm.html',context)

my home.html я также понятия не имею, что здесь происходит

 <!DOCTYPE html>

    {%extends 'main.html'%}
    {% block content%}   
    <!-- <style>
        .home-container{
            display: grid;
            grid-template-columns: 1fr 2fr 1fr;
        }
    </style> -->
    <!-- put everything in a freaking div -->
       
        <div class="addrequest">
            <a href="{% url 'requestform'  %}">
                <h3>Add request</h3>
            </a>
            <a href="{% url 'deleteall' %}">
                delete all Requests
            </a>
        </div>

        <div class="intronote">
            <p>
                Lorem ipsum dolor sit amet consectetur adipisicing elit. Commodi hic maiores
                quisquam sed ipsa incidunt iste, minima aperiam est sunt
                nobis, soluta adipisci laborum esse. Placeat praesentium quibusdam corrupti quis?
                Natus doloremque illum commodi unde nostrum expedita
                tempora sapiente magnam asperiores, placeat dolorum vitae repellendus possimus ut,
            </p>
            <div>
                <h4>{{count}} Requests in total</h4>
            </div>
            <hr>
        </div>

        <div class="allrequests">

            {% for post in requests %}
                <div>
                    <!-- request -->
                    <h4>{{post.name}}  the request id is : {{post.id}} posted <strong>{{post.posted}}</strong></h4>
                    <p>--{{post.text}}</p> 


                    
                    <!--comment -->
                    <h5>Comments</h5>
                    <p>{{post.comments.all}}</p>
                    

                    <!-- comment input -->
                    <a href="{% url 'commentform' post.id  %}">
                        <h3>Add Comment</h3>
                    </a> 
                   
                </div>
            
                <hr>    
            {% endfor %}

        </div> 
    
    {% endblock content %}

pls если вы также можете дать мне любые другие советы я буду очень признателен. спасибо

Здесь вы установили отношения между ними:

class Comment(models.Model):
    request = models.ForeignKey('sunu_app.Post', ...)
    ...

Поэтому при создании нового объекта Comment нужно передать Post id или весь объект в поле request (настоятельно рекомендую назвать его post вместо request):

post = Post.objects.get(id=1)
comment = Comment.objects.create(    # use round parenthesis
    request = post,
)
Вернуться на верх