djangohyperlinkreferencecommentsforum

How can a page stay where it is instead of refreshing and going to the top after interact with a domestic link such as 'edit'?


So I've built a Django forum, just added in the comment function. Here's a minor annoying thing needs to be sorted...

Problem: When editing a comment, after pressing edit button/link, the page naturally refreshes itself, going to the top of the page instead of, what I hope for, staying right where it was... This isn't nice or friendly at all...

Here's the code:

url.py

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

views.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 %}

You can probably tell from the code that I'm quite new in programming.

Now I've added an id="{{ comment.pk }}'' for each comment div based on their primary key. I'm probably v close to the solution, yet I'm not sure how to reference a div id in the view function...

Solution I've tried:

If only I could just add in #<int:comment_pk> at the end the each url when edit is triggered, like so:

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

or simply

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

However, Django doesn't seem to recognise the hash tag in urlpatterns, instead it's showing %20 something in rendered url of the page after edit is pressed/triggered.

I've also desperately tried this, hoping it'd work:

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

Please help. Thanks!!


Solution

  • Refreshing page on form submission is browser's natural behavior.

    What you want is Ajax read this article to learn how to Ajaxify your forms https://realpython.com/django-and-ajax-form-submissions/

    However, I would advise using https://intercoolerjs.org/ for basic ajax views.