首页 > 解决方案 > 页面在与国内链接如“编辑”交互后,如何保持原样而不是刷新并进入顶部?

问题描述

于是自己搭建了一个Django论坛,只是在评论功能中添加了。这里有一件烦人的小事需要整理...

问题:编辑评论时,按下edit按钮/链接后,页面自然刷新,转到页面顶部,而不是我希望的,停留在原来的位置......这不是很好或不友好全部...

这是代码:

网址.py

app_name = 'forum'
urlpatterns = [
    path('topic_<int:topic_pk>/<int:post_pk>/edit_<int:comment_pk>/', views.post, name='edit_comment'),
]

视图.py

def post(request, topic_pk, post_pk, comment_pk=None):
    '''displaying one post under a topic and all the comments under this post'''
    # get existing topic and post
    topic = get_object_or_404(Topic, pk=topic_pk)
    try:
        post = topic.post_set.get(pk=post_pk)
    except:
        raise Http404

    # get all the comments under this post
    comments = post.comment_set.order_by('-pk')

    # deal with comment editing
    if comment_pk != None:
        comment_to_be_edited = get_object_or_404(Comment, pk=comment_pk)

        if 'delete' in request.POST:
            comment_to_be_edited.delete()
            return redirect('forum:post', topic_pk, post_pk)

        # get form with existing data ready to be rendered or edited/updated
        edit_comment_form = CommentForm(instance=comment_to_be_edited)

        if 'update' in request.POST:
            edit_comment_form = CommentForm(instance=comment_to_be_edited, data=request.POST)
            if edit_comment_form.is_valid():
                edit_comment_form.save()
                return redirect('forum:post', topic_pk, post_pk)

        # if not to delete or to update, simply render the existing form with comment data ready to be edited
        return render(request, 'forum/post.html', {
                'topic': topic,
                'post': post,
                'comments': comments,
                'comment_to_be_edited': comment_to_be_edited,
                'edit_comment_form': edit_comment_form})

    # if not posting a new comment, simply render the form
    if request.method != 'POST':
        form = CommentForm()
    else:
        # deal with posting a new comment
        form = CommentForm(data=request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.post = post
            new_comment.author = request.user
            new_comment.save()
            return redirect('forum:post', topic_pk, post_pk)

    # render the post and all the comments and the empty/error form
    return render(request, 'forum/post.html', {
        'topic': topic,
        'post': post,
        'comments': comments,
        'form': form})

post.html

{% for comment in comments %}
<div class="comment mt-3 border p-3 rounded-lg shadow-sm" id="{{ comment.pk }}">

    {% if comment == comment_to_be_edited %}
    <div class="d-flex justify-content-between align-items-start border-bottom">
        <p class="font-weight-bold">{{ comment.author }}</p>
        <p class="font-weight-light">{{ comment.date_added }}</p>
    </div>
    <form action="{% url 'forum:edit_comment' topic.pk post.pk comment.pk %}" method="POST">
        {% csrf_token %}
        {% bootstrap_form edit_comment_form %}
        <button name="update" class="btn btn-sm btn-info">update</button>
        <a href="{% url 'forum:post' topic.pk post.pk %}" 
            class="btn btn-sm btn-outline-danger">cancel</a>
        <button name="delete" class="btn btn-sm btn-danger float-right">delete</button>
    </form>

    {% else %}

    <div class="d-flex justify-content-between align-items-start border-bottom">
        <p class="font-weight-bold">{{ comment.author }}</p>
        <p class="font-weight-light">{{ comment.date_added }}</p>
        {% if comment.author == user %}
        <a href="{% url 'forum:edit_comment' topic.pk post.pk comment.pk %}"
            class="shadow-sm btn btn-sm btn-outline-secondary float-right px-3">edit</a>
        {% endif %}
    </div>
    <p class="mt-4">{{ comment.content | linebreaks }}</p>

    {% endif %}
</div>
{% empty %}
<p class="text-muted">No comment for this post yet. Anything you'd like to share?</p>
{% endfor %}

您可能从代码中可以看出我是编程新手。

现在,我根据主键id="{{ comment.pk }}''为每个评论添加了一个。div我可能接近解决方案,但我不确定如何在视图函数中引用div id ...

我试过的解决方案:

如果我可以在#<int:comment_pk>最后添加每个触发时的 url edit,就像这样:

path('topic_<int:topic_pk>/<int:post_pk>/edit_<int:comment_pk>/#<int:comment_pk>', views.post, name='edit_comment'),

或者干脆

path('topic_<int:topic_pk>/<int:post_pk>/edit/#<int:comment_pk>', views.post, name='edit_comment'),

但是,Django 似乎无法识别 中的哈希标记urlpatterns,而是在按下/触发%20后在页面的渲染 url 中显示一些内容。edit

我也拼命尝试过,希望它能起作用:

# view function
# --snip--
   return render(request, 'forum/post.html#comment.pk', context)

请帮忙。谢谢!!

标签: djangohyperlinkreferencecommentsforum

解决方案


表单提交刷新页面是浏览器的自然行为。

你想要的是 Ajax 阅读这篇文章来学习如何 Ajaxify 你的表单https://realpython.com/django-and-ajax-form-submissions/

但是,我建议将https://intercoolerjs.org/用于基本的 ajax 视图。


推荐阅读