django prepopulated fields break with hyphens

2019-07-29 07:23发布

问题:

I started putting prepopulated_fields options in my admins and funny stuff started happening I have this model

class Pelicula(models.Model):
    nombre = models.CharField(max_length=50)
    slug = models.SlugField(max_length= 15, unique= True, help_text = "Nombre corto para la URL", primary_key= True)

and this in admin.py

class PeliculaAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug' : ['nombre']}

nothing fancy, it's described all over the place But as soon as I use this slug in an object_detail generic view, the slug only works if it was only one word to begin with. so if i have this view

def detalle_pelicula(request, pelicula):
    return list_detail.object_detail(
        request,
        queryset = Pelicula.objects.all(),
        slug = pelicula,
        template_name='sections/detalle_pelicula.html',
        template_object_name = 'pelicula',
        extra_context = extra_context,
        )

if the original name had any spaces in it, i get a "No Page matches the given query." error. So detail/test will work but detail/test-page won't I'm a bit stumped

回答1:

i'm guessing you have your urlconf setup parsing your slug using \w+ try using [-A-Za-z0-9_]+

# e.g. in urls.py

url(r'del/(?P<slug>[-A-Za-z0-9_]+)/$',   'person_delete',  name='person_delete'),