使用重定向从表单保存后如何通过 id 传递对象?

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

很抱歉问这个问题。我描述了一种通过表单上传图像的服务。最重要的是,在成功下载 (add_picture) 后,我必须进入图像页面 (picture_detail).不明白为什么不能转ID。我做了以下事情:

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'),
]

因此,我应该进入这样的页面:

id可以从form.save()的结果中得到:

from django.shortcuts import redirect

# …

if form.is_valid():
    <b>item =</b> form.save()
    return redirect('home:picture_detail'<b>, id=item.id</b>)
# …

万岁!我管理。所需要的只是将 id 传递给会话。我已经更正了我的代码并且它有效。在 views.py.

中查找