简体   繁体   中英

Django: How to send user to ancor after POST

Supposed there is a long page with a form at the end. Now the user submits this form with invalid data and it gets rerendered.I don't want to have him scrolling all the way back down, so i want to send him to a

<a name="form"></a>

This is a related question: Django. How to redirect to url with fragment identifier The difference is, that i am rerendering instead of redirecting. Because i only redirect after success. So how do i send the user to the ancor with

@method_decorator(login_required())
def post(self, request, article_id, article):
    self.object = self.get_object() # needed to fill context
    form = CommentForm(request.POST, response_to_id=article_id, author=self.request.user)  # A form bound to the POST data
    if form.is_valid():  # All validation rules pass
        comment = form.save()
        redirect_url = reverse('article_detail', kwargs={'article_id': article_id}) + "#" + str(comment.id)
        return HttpResponseRedirect(redirect_url)  # Redirect after POST
return self.render_to_response(self.get_context_data(form=form))

the call at the end?

Just add the #whatever .

just add the window.location.href if form is submit,

<script>

{% if submit %}
window.location.href = "#whatever"
{% endif %}

</script>

Note: send the context variable of submit=True if request is POST.

and in your htm form,

<form id='whatever' action="some" method='post'></form>

Example: Django: How to send user to ancor after POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM