2

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

模型.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])

视图.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())

网址.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为基础

4

2 回答 2

2

可以从以下结果中获取 id form.save()

from django.shortcuts import redirect

# …

if form.is_valid():
    item = form.save()
    return redirect('home:picture_detail', id=item.id)
# …
于 2020-12-29T12:43:08.107 回答
0

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

于 2020-12-29T19:34:48.037 回答