创建与DetailView相反的视图
Posted
技术标签:
【中文标题】创建与DetailView相反的视图【英文标题】:Create View reverse to DetailView 【发布时间】:2015-01-08 21:00:52 【问题描述】:上传图片后,我正在尝试从 CreateView 反转到 DetailView。
我收到同样的信息
/photo/image/add 处的 NoReverseMatch 未找到带有参数“()”和关键字参数“'pk':50”的“图像视图”的反向。尝试了 0 个模式:[]
这是我的图像模型
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from django.conf import settings
from string import join
import os
class Image(models.Model):
title = models.CharField(max_length=60, blank=True, null=True)
image = models.FileField(upload_to="images/")
tags = models.ManyToManyField(Tag, blank=True)
albums = models.ManyToManyField(Album, blank=True)
created = models.DateTimeField(auto_now_add=True)
rating = models.IntegerField(default=50)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
user = models.ForeignKey(User, null=True, blank=True)
def __unicode__(self):
return self.image.name
def size(self):
return "%s x %s" % (self.width, self.height)
def tags_(self):
lst = [x[1] for x in self.tags.values_list()]
return str(join(lst, ', '))
def albums_(self):
lst = [x[1] for x in self.albums.values_list()]
return str(join(lst, ', '))
def thumbnail(self):
return """<a href="/media/%s"><img border="0" src="/media/%s" /></a>""" % (
(self.image.name, self.image.name))
thumbnail.allow_tags = True
def get_absolute_url(self,*args,**kwargs):
return reverse('image-view',kwargs='pk': self.pk)
我的 urls.py
from django.conf.urls import patterns, url
from django.conf import settings
from django.conf.urls.static import static
from photo import views
urlpatterns = patterns('',
url(r'^image/(?P<pk>\d+)/$', views.ImageView.as_view(),name='image-view',),
url(r'^$', views.ListImage.as_view(),name ='Photo-List',),
url(r'^image/add/$', views.ImageCreate.as_view(), name = 'create-image',),
url(r'update/(?P<pk>\d+)/$', views.ImageUpdate.as_view(),name='image-update',),
)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root = settings.MEDIA_ROOT)
我的观点
from django.views.generic import ListView, DetailView, UpdateView, CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy, reverse
from photo.models import Tag, Image, Album
from django.conf import settings
class ImageView(DetailView):
model = Image
allow_empty = True
template_name = 'image.html'
class ListImage(ListView):
#context_object_name = 'object_list'
template_name = 'image_list.html'
model = Image
#def get_queryset(self):
# return Image.objects.all()
class ImageCreate(CreateView):
model = Image
template_name='image_create.html'
fields = ['title','image']
有关我的错误的更多详细信息
Traceback Switch to copy-and-paste view
/Library/Python/2.7/site-packages/django/core/handlers/base.py in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/views/generic/base.py in view
return self.dispatch(request, *args, **kwargs) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/views/generic/base.py in dispatch
return handler(request, *args, **kwargs) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/views/generic/edit.py in post
return super(BaseCreateView, self).post(request, *args, **kwargs) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/views/generic/edit.py in post
return self.form_valid(form) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/views/generic/edit.py in form_valid
return super(ModelFormMixin, self).form_valid(form) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/views/generic/edit.py in form_valid
return HttpResponseRedirect(self.get_success_url()) ...
▶ Local vars
/Users/henriaugris/Documents/Django/mysite/photo/views.py in get_success_url
return reverse('image-view', kwargs='pk' : self.object.pk) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/core/urlresolvers.py in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix
(lookup_view_s, args, kwargs, len(patterns), patterns)) ...
▶ Local vars
Request information
GET
No GET data
【问题讨论】:
您是否尝试在 View 上设置成功变量? 您的模型中的from django.core.urlresolvers import reverse
在哪里?
Madzohan:在我看来
@frlan 如何设置成功?
@madzohan 有什么帮助吗?
【参考方案1】:
而不是将你的models.py文件中的get_absolute_url设置为:
def get_absolute_url(self,*args,**kwargs):
return reverse('image-view',kwargs='pk': self.pk)
你可以在你的views.py文件中设置它:
class ImageCreate(CreateView):
model = Image
template_name='image_create.html'
fields = ['title','image']
def get_success_url(self):
return reverse('image-view', kwargs='pk' : self.object.pk)
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(ImageCreate, self).get_form_kwargs(
*args, **kwargs)
return kwargs
进行此更改后,您应该从您的 models.py 文件中删除 get_absolute_url。通过此更改,您应该会在成功创建新图像后进入您上传的图像的详细视图。
【讨论】:
github.com/django/django/blob/master/django/views/generic/… 一样 你说的覆盖get_form_kwargs
是什么意思,但没有使用它?
今晚我会重新更新我的github项目,感谢您的耐心等待。我刚刚评论了 get_form_kwars 来调试第一部分。
@madzohan 所以你们知道出了什么问题吗?我尝试为我的 DeletView 使用 success_url 但它仅在我硬编码 url 时才有效,所以我猜 Django 无法识别我在 urls.py 中为不同视图赋予的名称以上是关于创建与DetailView相反的视图的主要内容,如果未能解决你的问题,请参考以下文章
Django 通用视图:何时使用 ListView 与 DetailView