0

My problem is rather simple, I need to pass a value from one view to another without the visitor being able to see the value in the URL. Here is my code :

views.py

def home(request, message=None):
    plats = Plat.objects.all() 
    return render(request, 'actualites/home.html', {'last_meals': plats, 'message': message}) 

@login_required
def proposer_plat(request):
    try:
        a = request.user.chef
        if request.method == "POST":
            form = PlatForm(request.POST, request.FILES)
            if form.is_valid():
                form.save()
                return redirect(home)
        else:
            form = PlatForm()
        return render(request, 'actualites/proposer_plat.html', {'form': form})

    except ObjectDoesNotExist:
            message = "Vous devez être enregistré comme chef pour effectuer cette action"
            return redirect(home, message=message)

urls.py

urlpatterns = [
    path('', views.home, name = 'home'),
    path('meal/<int:id>', views.display, name = 'display'),
    path('date', views.date_actuelle, name = 'date'),
    path('contact', views.contact, name = 'contact'),
    path('connexion', views.connexion, name = 'connexion'),
    path('deconnexion', views.deconnexion, name = 'deconnexion'),
    path('inscription', Inscription.as_view(), name = 'inscription'),
    path('proposer-plat', views.proposer_plat, name = 'proposer-plat')
]

So here I need to pass the value of the variable message from the "proposer_plat" view to the "home" view. Actually I'm getting a NoReverseMatch error. I know I coud do path('/<message>', views.home, name = 'home'), but with this, the message would be displayed in the URL and I would not be able to access the "home" view without providing a message in the URL. I guess I could use request (with POST or something) to pass the value but I'm really a beginner with Django and, despite all my researchs, I don't understand how to do that.

Can someone explain me how to do (if possible with an example)?

Julien Mertz
  • 465
  • 2
  • 8
  • 22
  • Django has functionality specifically for this: the [messages framework](https://docs.djangoproject.com/en/3.0/ref/contrib/messages/). For more general passing between views though, you'd use the session. – Daniel Roseman Dec 08 '19 at 12:29
  • Using messages, I was able to do what I wanted, thank you very much ! I just have another question, what do you mean by "more general passing" ? I'm asking because it will maybe be useful later in the project – Julien Mertz Dec 08 '19 at 13:48
  • I just meant for passing things that are not messages, for example elements from a form that you don't want to save to the database immediately. – Daniel Roseman Dec 08 '19 at 14:13
  • Ok I see, thank you ! – Julien Mertz Dec 08 '19 at 14:26

0 Answers0