Страницы

Поиск по вопросам

понедельник, 13 апреля 2020 г.

ЧПУ на django

#python #url #django

                    
Поправьте если я не прав:
models.py:
...
def get_absolute_url(self):
    return '/pages/%s' % self.slug

urls.py:
url(r'^pages/(?P.*)/$', 'APP.views.view_page'),

APP.views.py:
def view_page(request, slug):
    page = get_object_or_404(Page, slug=slug)
    return render_to_response('TEMPLATE', {'x': page})

Не могу понять, как работает get-object-or_404, первый параметр это модель, а второй
slug  это поле в модели, принимает переменную из url.py:  и сверяет, если они
равны (читай: часть введеного УРЛа по регулярке совпадает с model.slug) грузит страницу,
а в противном случае 404. Так? А то ужасное описание здесь: get_object_or_404.
get_object_or_404(klass, *args, **kwargs)

Calls get() on a given model manager, but it raises Http404 instead of the model's
DoesNotExist exception.
Required arguments
klass
A Model, Manager or QuerySet instance from which to get the object.
**kwargs
Lookup parameters, which should be in the format accepted by get() and filter().
Example

The following example gets the object with the primary key of 1 from MyModel:
from django.shortcuts import get_object_or_404

def my_view(request):
    my_object = get_object_or_404(MyModel, pk=1)

This example is equivalent to:
from django.http import Http404

def my_view(request):
    try:
        my_object = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        raise Http404

Note: As with get(), a MultipleObjectsReturned exception will be raised if more than
one object is found.
get_list_or_404
get_list_or_404(klass, *args, **kwargs)

Returns the result of filter() on a given model manager, raising Http404 if the resulting
list is empty.
Required arguments
klass
A Model, Manager or QuerySet instance from which to get the list.
**kwargs
Lookup parameters, which should be in the format accepted by get() and filter().
Example

The following example gets all published objects from MyModel:
from django.shortcuts import get_list_or_404

def my_view(request):
    my_objects = get_list_or_404(MyModel, published=True)

This example is equivalent to:
from django.http import Http404

def my_view(request):
    my_objects = list(MyModel.objects.filter(published=True))
    if not my_objects:
        raise Http404
Questions/Feedback

Having trouble? We'd like to help!
 Try the FAQ — it's got answers to many common questions. 
 Search for information in the archives of the django-users mailing list, or post
a question. 
 Ask a question in the #django IRC channel, or search the IRC logs to see if it has
been asked before. 
 If you notice errors with this documentation, please  open a ticket and let us know!
Please only use the ticket tracker for criticisms and improvements on the docs. For
tech support, use the resources above. 
Search

Version:

Contents
Django shortcut functions
render
Required arguments
Optional arguments
Example
render_to_response
Required arguments
Optional arguments
Example
redirect
Examples
get_object_or_404
Required arguments
Example
get_list_or_404
Required arguments
Example
Browse
Prev: File Uploads
Next: Generic views
Table of contents
General Index
Python Module Index
You are here:
Django dev documentation 
Using Django 
Handling HTTP requests 
Django shortcut functions
Download:

 Offline (development version): HTML | PDF | ePub 
Provided by Read the Docs.

© 2005-2012 Django Software Foundation unless otherwise noted. Django is a registered
trademark of the Django Software Foundation. Linux Web hosting graciously provided
by Media Temple. ](https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#get-object-or-404)

Если я все реализовал ЧПУ как правильно и ошибок у меня нет, то прошу совета как
элегантно добавлять .html без / в конце урла, не прописывая .html в шаблоне.    


Ответы

Ответ 1



def get_absolute_url(self): return '/pages/%s.html' % self.slug url(r'^pages/(?P.*)\.html$', 'APP.views.view_page'),

Комментариев нет:

Отправить комментарий