Giter Site home page Giter Site logo

django-mptt-urls's Introduction

Overview

This reusable app helps to create arbitrary-depth Clean URLs which correspond to MPTT tree hierarchy of model instances, like these:

http://best-photographer.com/gallery/weddings/Dexter-and-Rita/

http://best-photographer.com/gallery/my-pets/dogs/husky/

As you can see, the links are quite different - they have different depth of hierarchy. When users see these URLs they can easily discover where they are located. They can either delete some part of the URL and thus move up in the hierarchy.

Django-mptt-urls is just a simple view that knows how to resolve hierarchical urls.

Example

The simpliest way to understand how django_mptt_urls works is to clone this GitHub project, create virtual environment and run test_project (no extra settings required, except sqlite3 database support):

git clone https://github.com/c0ntribut0r/django-mptt-urls.git
pyvenv django-mptt-urls
source django-mptt-urls/bin/activate
pip install django-mptt-urls/
python django-mptt-urls/test_project/manage.py runserver

And visit 127.0.0.1:8000 in your browser.

Requirements

django-mptt-urls uses django-mptt. It will be automatically installed as a requirement.

Installation

First of all, you should already be using django-mptt, something like this:

from mptt.models import MPTTModel, TreeForeignKey

class Category(MPTTModel):
    ...
    parent = TreeForeignKey('self', null=True, blank=True)
    slug = models.SlugField()
    class Meta:
        unique_together = ('slug', 'parent')

Install django-mptt-urls:

pip install django-mptt-urls

Then, in your urls.py, replace one or more views with special mptt_urls.view:

# urls.py
...
import mptt_urls

urlpatterns = patterns('',
    ...
    url(r'^gallery/(?P<path>.*)', mptt_urls.view(model='gallery.models.Category', view='gallery.views.category', slug_field='slug', trailing_slash=True), {'extra': 'You may also pass extra options as usual!'}, name='gallery'),
    ...
)

Here is what we've done:

  • We are capturing (?P<path>.*), which will be passed to mptt_urls.view when url resolution is fired. You can define path whatever you like (for example (?P<path>[\d/]+)), but don't forget to include '/' in the regex.
  • Replace your view with special mptt_urls.view.

mptt-urls.view works like a decorator to a view: it gets fired when url resolution is performed, calculates an instance the path is poining to, and passes it to original view.

So, if you write

url(r'^gallery/(?P<path>.*)', 'gallery.views.category', name='gallery'),

the gallery.views.category view will receive path variable and will have to make object resolution. With mptt_urls.view, you will get the resolved object automatically - gallery.views.category view will receive path and instance variables:

url(r'^gallery/(?P<path>.*)', mptt_urls.view(model='gallery.models.Category', view='gallery.views.category', slug_field='slug'), name='gallery'),

mptt_urls.view options are:

  • model - your model derived from MPTTModel.
  • view - a view which will process the request. Don't forget to capture path and instance (def category(request, path, instance):). If resolution fails, instance will be None.
  • slug_field - the field where model instance's slug is stored

get_absolute_url()

Well, url(...) defines direct url resolution. To define reverse url resolution, add to your model:

class Category(MPTTModel):
    ...
    def get_absolute_url(self):
        return reverse('gallery', kwargs={'path': self.get_path()})

Here, we use Category.get_path() which is available since using mptt_urls.view.

If you use namespaced url routing, don't forget to add namespace specifier like this:

return reverse('namespace:gallery', kwargs={'path': self.get_path()})

License

MIT. Do whatever you like. View license file for details.

django-mptt-urls's People

Contributors

batisteo avatar destos avatar maksim-burtsev avatar mrkesn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

django-mptt-urls's Issues

url_mptt import error

Hi,

I am trying to use your djang-mptt-urls module, but when I refresh the page, I get this error:

[Wed May 14 21:50:51 2014] [error] [client 127.0.0.1] File "/home/petr/projects/xyz/notespace/core/urls.py", line 3, in
[Wed May 14 21:50:51 2014] [error] [client 127.0.0.1] from mptt_urls import url_mptt
[Wed May 14 21:50:51 2014] [error] [client 127.0.0.1] ImportError: cannot import name url_mptt

I installed the module using pip as was suggested on the readme page. What could be wrong? Any ideas? Thank you!

Request to update Documentation for view routing

I think it may be a good idea to note in the docs that the model.get_absolute_url() function needs to be modified from the example if the user is using namespaced url routing.

For instance, I am building a cms using your django-mptt-urls. I have a page model with the following:

def get_absolute_url(self):
            return reverse(
                'page:page_view',
                kwargs={
                    'path': self.get_path()
                }
            )

I had to add the namespace for my app in order for the method to work properly. I feel kind of dumb, but it took me a bit to figure out that that was the problem. If you would like, I can make a pull request and modify the readme myself.

Let me know.

Specify parent field

As of now, your parent field can only be named "parent". Is it possible to specify the parent field in mptt_urls settings like you can do with the slugfield?

Add support for url namespaces when attaching url_mptt to namespaced pattern

I'm currently experimenting with using namespaces in django and noticed that there are errors when adding a namespace to a lower url pattern that the url_mptt gernerated url is attached to.

The failure occurs when the reverse is run inside the model bound get_absolute_url method, as the url is now namespaced it no longer works.
https://github.com/MrKesn/django-mptt-urls/blob/master/mptt_urls/__init__.py#L29

I'll be investigating if there is a way we can pass along namespacing information to get_absolute_url so the lookup can be done correctly.

how to filter on existing url

i am a beginner in django mptt urls....thanks in advance

class Category(MPTTModel):
title = models.CharField(max_length =120)
parent = TreeForeignKey('self' , null = True , blank = True , verbose_name='parent category', related_name='categories')
def get_absolute_url(self):
return reverse('categories', kwargs={'path': self.get_path()})
def get_clothes(self):
return Product.objects.filter(category__in=self.get_descendants(include_self=True))

class Product(models.Model):
brand = ForeignKey('Brand', verbose_name='brands', related_name='brand' , default='')
category = TreeForeignKey('Category', verbose_name='categories', related_name='products' , default='')

i have categories like this
men > men clothing > tshirts

my template
{% for product in instance.get_clothes %}
{{ product.title }}
{% endfor %}

how can i filter based on brand and still show the result on the same template ?

Not showing data for main categories

hello ...i followed django-mptt-urls....but i shows data only for the subcategory in which the photos are added but if we click on the category above it doesnt show any data...although it must show all the data present in together in all the below subcategories

for eg
men>menclothing>tshirts
men>menclothing>jeans

when clicking on menclothing it must show data for both tshirts and jeans combined

Optional trailing space

Hi,

On my routes if I omit the trailing space, the view does not return the instance.

I managed to create a fix with a decorator like this :

def check_trailing_slash(view):
    def wrap(request, *args, **kwargs):
        path = kwargs['path']
        if path.endswith('/'):
            return view(request, *args, **kwargs)
        else:
            uri = request.build_absolute_uri()
            return redirect(
                uri.replace(path, f"{path}/"),
                permanent=True,
            )

    return wrap

It works but i found the fix a bit ugly.

Is there something I missed with your library to manage this case ?

'NoneType' object has no attribute 'get_ancestors'

Hey, i've set up django-mptt-urls using your documentation, and everything works except if you remove the trailing slash at the end of url, f.e:
localhost.com/category1/category2

i get an error
AttributeError at /category1/category2
'NoneType' object has no attribute 'get_ancestors'

It is said that it raises ValueError, but it gives status 500 on the server.

Do you have any idea how to fix it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.