Search code examples
python-3.xdjangohttp-redirectdjango-urlsdjango-url-reverse

How to pass object by id after saving from form using redirect?


I am sorry for asking this. I described a service that uploads an image through a form. The bottom line is that after a successful download (add_picture), I have to get to the image page (picture_detail). I don’t understand why I can’t transfer ID. I did the following:

models.py:

class Picture(models.Model):
    url = models.URLField(blank=True, verbose_name='Ссылка на изображение')
    image = models.ImageField(upload_to='pictures/%Y/%m/%d', width_field='image_width', height_field='image_height',
                              blank=True, verbose_name='Изображение')

def get_absolute_url(self):
    return reverse('home:picture_detail', args=[self.id])

views.py:

def add_picture(request, id=None):
    picture = Picture.objects.filter(is_active=True)
    # picture_form = None
    # picture = get_object_or_404(Picture, id=id)
    if request.method == 'POST':
        form = PictureCreateForm(data=request.POST, files=request.FILES)
                if form.is_valid():
        form.save()
        picture_id = form.save()
        request.session['id'] = picture_id.id
        id = request.session.get('id')
        return HttpResponseRedirect(reverse('home:picture_detail', kwargs={'id': id}))
        else:
            return render(request, 'add_picture.html', locals())
    else:
        form = PictureCreateForm()

    return render(request, 'add_picture.html', locals())

urls.py:

urlpatterns = [
    path('', views.home, name='home'),
    path('add_picture/', views.add_picture, name='add_picture'),
    path('picture_detail/<int:id>/', views.picture_detail, name='picture_detail'),
]

Bug report

As a result, I should get to a page of this kind: Such page should be based on the ID after saving the form


Solution

  • The id can be obtained out of the result of the form.save():

    from django.shortcuts import redirect
    
    # …
    
    if form.is_valid():
        item = form.save()
        return redirect('home:picture_detail', id=item.id)
    # …