首页 > 解决方案 > 如何在python django中获取和保存页面中最近元素的数据

问题描述

我需要在 django python 的主页上添加评论模块 - 每个帖子下的简单文本区域。在将其保存在表单中之前,我需要获取最近的帖子 ID,以便我的评论知道与哪个帖子相关。

我的表格.py

class newPost(forms.ModelForm):
    class Meta:
        model = Post
        exclude = ['author', 'date_posted']
        fields = ('content', 'date_posted', 'author')

class newComment(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['author', 'date', 'post']
        fields = ('content', 'date', 'author', 'post')

我的观点.py

def home(request):
    newPostForm = newPost()
    newCommentForm = newComment()
    if request.is_ajax():
        newPostForm = newPost(request.POST)
        newCommentForm = newComment(request.POST)
        if newPostForm.is_valid():
            instance = newPostForm.save(commit=False)
            instance.author = request.user
            instance.date_posted = timezone.now()
            instance.save()
            data = {
                'message': 'post is added'
            }
            return JsonResponse(data)
        if newCommentForm.is_valid():
            instance = newCommentForm.save(commit=False)
            instance.author = request.user
            instance.date = timezone.now()
            instance.save()
            data = {
                'message': 'comment is added'
            }
            return JsonResponse(data)
    context = {
        'newPostForm': newPostForm,
        'newCommentForm': newCommentForm,
        'posts': Post.objects.all().order_by('-date_posted'),
        'comments': Comment.objects.all().order_by('-date_posted')
    }

和我的 home.html

 <div class="leftcolumn">
            <div class="new_post_form">
                <form METHOD="POST" class="new_post" id="new_post">
                    {% csrf_token %}
                    {{ newPostForm }}
                    <button type="submit">Publish</button>
                </form>
            </div>
            <div id="posts">
            {% for post in posts %}
                <div class="container">
                    <a class="user" href="#">{{ post.author }}</a>, {{ post.date_posted }}
                    <img src="{{ post.author.profile.image.url }}" alt="{{ post.author }}" style="width:100%;">
                    <p>{{ post.content }}</p>
                    {% for comment in post.comments.all %}
                    <div class="comment">
                        <p>{{ comment.content }}</p>
                        <form METHOD="POST" class="new_comment" id="new_commentt">
                        {% csrf_token %}
                        {{ newCommentForm }}
                        </form>
                    </div>
                    {% endfor %}
                </div>
            {% endfor %}
            </div>
            </div>

我什至不知道从什么开始......我正在考虑将这个帖子 ID 放入请求中的 javascript,但我不知道如何。你可以帮帮我吗?

标签: pythondjangoforms

解决方案


request.is_ajax():执行此指令:如果if request.method == 'POST':


推荐阅读