简体   繁体   中英

How to redirect to success after POST method in Django 2

I would like to know how a GET OR POST requests can be handled from a FormView class to render a unbound form for GET and POST the form to database for POST and subsequently redirect to success page (info message).

What template to use for GET and POST methods and how to include message after redirect to success URL?

views.py:

from django.shortcuts import render,redirect,render_to_response,get_object_or_404
from django.forms import ModelForm
from django.views import View

from django.views.generic.edit import CreateView
from .forms import MyPlaceForm
from .models import Place
from django.urls.base import reverse_lazy


from django.contrib import messages


#Ceate your class-based views here.
class MapView(View):
    def get(self, request):
        'Display map'
        return render(request,template_name='index.html')

# Handling forms with class-based view
class PlaceFormView(View):
    form_class = MyPlaceForm
    initial = {'key': 'value'}
    template_name = 'name.html'

    # Provide Blank Form if GET request
    def get(self, request, *args, **kwargs):
        form = self.form_class(initial=self.initial)
        return render(request, self.template_name, {'form': form})

# Provide a message if POST request
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        success_url=reverse_lazy('success')
        if form.is_valid():
            # <process form cleaned data>

            messages.add_message(request, messages.INFO, 'Hello world.')
            return reverse_lazy(success_url)

        return render(request, self.template_name, {'form': form})

urls.py:

from django.contrib import admin
from django.http import HttpResponse
from django.urls import path
from addismap.views import MapView,PlaceFormView


urlpatterns=[
    path('map/',MapView.as_view()),
    path('place/', PlaceFormView.as_view(), name='post-place'),
    path('place/success/',PlaceFormView.as_view(), name='success')

    ]

Following the documentation , you can do something like this:

# views.py    
if request.method == "POST":

    if form.is_valid():

        # <process form cleaned data>
        messages.success(request, 'Form updated with success.')
        return redirect('/success-page')

    else:       
        messages.error(request, 'Ops! Something went wrong')
        return redirect('/error-page')

In your template page you can get the message using a for loop code:

{% if messages %}
{% for message in messages %}
<div {% if message.tags %} class="alert alert-{{ message.tags }} alert-dismissible fade show" {% endif %}>
    <span>{{ message }}</span>
</div>
{% endfor %}
{% endif %}

Edit1 : Make sure you've imported the message tag and redirect in your views.py

from django.contrib import messages
from django.shortcuts import render, redirect

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