创建与DetailView相反的视图

时间:2014-11-12 05:09:22

标签: django django-class-based-views detailview create-view

我在上传图片后尝试从CreateView转换为DetailView。

我收到相同的消息

NoReverseMatch at / photo / image / add 反转'图像查看'参数'()'和关键字参数' {' 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" alt="" src="/media/%s" height="40" /></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

1 个答案:

答案 0 :(得分:2)

而不是将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。通过此更改,您应该在成功创建新图像时登陆上传图像的详细视图。