Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create View reverse to DetailView

I am trying to reverse from CreateView to DetailView after I have uploaded my Image.

I get the same message

NoReverseMatch at /photo/image/add Reverse for 'image-view' with arguments '()' and keyword arguments '{'pk': 50}' not found. 0 pattern(s) tried: []

This is my Model for Image

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})

My 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)

my views

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

More details on my error

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
like image 464
Han Ry Avatar asked Nov 12 '14 05:11

Han Ry


1 Answers

Instead of setting get_absolute_url in your models.py file as:

def get_absolute_url(self,*args,**kwargs):
        return reverse('image-view',kwargs={'pk': self.pk})

You could set it in your views.py file under:

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

After making this change, you should delete the get_absolute_url from your models.py file. With this change, you should land on the detail view of the image you uploaded upon successfully creating a new image.

like image 57
sv_rancher Avatar answered Oct 23 '22 03:10

sv_rancher