1
votes

I have developed a simple django project in which photos will be stored and displayed. The problem is whenever I redirect to a page, the page gets loaded but the url does not change in the address bar. So when i refresh the page again, I am getting errors. For example,

I created an album. For that the url is: 127.0.0.1:8000/create_album/

Then it has to redirect to the albums page where all albums of user are stored. That url is 127.0.0.1:8000/10/

But i am not getting that url when i redirect to that page.

The views.py:

    **def create_album(request):
    if not request.user.is_authenticated():
        return render(request, 'photo/login.html')
    else:
        form = AlbumForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            album = form.save(commit=False)
            album.user = request.user
            album.album_logo = request.FILES['album_logo']
            album.save()
            return render(request, 'photo/detail.html', {'album': album})
        context = {
            "form": form,
        }
        return render(request, 'photo/create_album.html', context)

def detail(request, album_id):
    if not request.user.is_authenticated():
        return render(request, 'photo/login.html')
    else:
        user = request.user
        album = get_object_or_404(Album, pk=album_id)
        return render(request, 'photo/detail.html', {'album': album, 'user': user})**

The page has to be redirected to photo/detail.html. It redirects to the required page but the url doesn't change. Please help me with this.

1
But where do you think you are redirecting? There are no redirects anywhere in this code. - Daniel Roseman
The render method redirects to the specific page spicified in the parameters - Thedeadman619
No it doesn't. It renders a template. - Daniel Roseman
so how to modify that part? how to write the same thing using redirect method? Please help - Thedeadman619

1 Answers

0
votes

It is good practice to do a redirect upon submitting a form. Here's how you can change your code to perform the redirect:

from django.shortcuts import render, redirect
from django.urls import reverse

def create_album(request):
    if not request.user.is_authenticated():
        return render(request, 'photo/login.html')
    else:
        form = AlbumForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            album = form.save(commit=False)
            album.user = request.user
            album.album_logo = request.FILES['album_logo']
            album.save()
            return redirect(reverse('detail', kwargs={'album_id':album.id}))
        context = {
            "form": form,
        }
        return render(request, 'photo/create_album.html', context)

This assumes that the url/view is named detail in your url patterns.

You could try this first, and if it doesn't work could we see your HTML code for the form?