Group models in django admin - django

Is there any way to group the models in django admin interface?
I currently have an app called requests with the following models showing in the admin site:
**Requests**
Divisions
Hardware Requests
Hardware Types
Requests
Software Requests
Software Types
I would like the divisions, Software Requests and Hardware Requests to be grouped separately in a "Types" group.
I know I could override and hard code the admin/index.html and base_site.html but this seems rather convoluted just to specify grouping.
Is there anything i can add to the Meta class to specify a group name?
The only way I have found so far to achieve what i want is to move the models to a new app within requests ("requests.Types") but again, doesn't feel like its the 'correct way'.

You can do it using django-modeladmin-reorder.
You'd configure it somehow along these lines then (settings.py):
ADMIN_REORDER = (
{'app': 'requests', 'label': 'Types',
'models': (
'requests.Divisions',
'requests.HardwareRequests',
'requests.HardwareTypes'
)
},
{'app': 'requests', 'label': 'Other models',
'models': (
'requests.Requests',
'requests.SoftwareRequests',
'requests.SoftwareTypes'
)
},
)

There isn't anything you can put in the model definition to do this, because models -- by design -- don't know about the existence of the admin, or how they'll be presented in the admin.
This really is a case where you just write a template that does what you want, and use it; all you're asking for is a presentational change, and templates are where you do presentation in Django.

Related

Django REST framework - different views for same url depending on http method

I have a REST framework API and I have to dispatch an url to 2 different views, depending on a method.
the architecture is like this:
bookshop/authors/ - lists all authors, with POST - adds an author
bookshop/authors/<author>/ - with GET - gets details for an author, including books
bookshop/authors/<author>/ - with POST - creates a posting of a book for the same author.
bookshop/authors/<author>/<book>/ - gets a book, no posting
In general, for all my API I'm using Viewsets with Routers.
I tried doing this:
urlpatterns = patterns(
'',
url(r'^author/(?P<author>[0-9]+)',
AuthorViewSet.as_view({'get': 'retrieve'}),
name='author-detail'),
url(r'^author/(?P<author>[0-9]+)',
BookViewSet.as_view({'post': 'create'})),
)
but then it goes to the first url and the viewset checks for methods and throws an exception MethodNotAllowed.
I tried to catch it like this:
try:
urlpatterns = patterns(
'',
url(r'^author/(?P<author>[0-9]+)',
AuthorViewSet.as_view({'get': 'retrieve'}),
name='author-detail')
)
except MethodNotAllowed:
urlpatterns = patterns(
'',
url(r'^author/(?P<author>[0-9]+)',
BookViewSet.as_view({'post': 'create'})),
)
But it doesn't work too.
Is there any way to do it using viewsets?
The problem is that organizing your API in such a manner breaks RESTful convention. Breaking RESTful convention is not always bad, but usually represents a poor design and certainly means it is harder to user 3rd party software designed around the restframework to support your schema. So my suggestion is to update your API schema to:
GET bookshop/authors/ - lists all authors
POST bookshop/authors/ - creates an author
GET bookshop/authors/<author>/ - gets details for an author
POST bookshop/authors/<author>/books/ - creates a book for an author
GET bookshop/authors/<author>/books/<book> - gets a book
If you need to add postings you can also have (I'm not sure of the relationships between the objects so, not sure if the below accurately represents that relationship).
POST bookshop/authors/<author>/books/<book>/postings - creates a posting
GET bookshop/authors/<author>/books/<book>/postings/<posting> - gets a posting
When using Viewsets, typically you'll want to register your views with a router instead of binding views directly as you have done. The router will take care of "routing" the request to the correct handler.
Checkout:
http://www.django-rest-framework.org/api-guide/viewsets/#example
http://www.django-rest-framework.org/api-guide/routers/

Stale content type prompt deleting all model instances after renaming django model with permissions

I had two models called CombinedProduct and CombinedProductPrice which I renamed to Set and SetPrice respectively. I did this by changing their model name in the models.py file and replaced all occurrences of it. This also included renaming a foreignkey field in another model from combined_product to set (pointing to a CombinedProduct).
When running makemigrations django properly detected the renaming and asked if I had renamed all three of those things and I pressed 'yes' for all. However when running 'migrate', after applying some stuff, I get asked:
The following content types are stale and need to be deleted:
product | combinedproduct
product | combinedproductprice
Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.
I backed up my data and entered 'yes' which deleted all instances of Set (previously CombinedProduct) and SetPrice (previously CombinedProductPrice). If I roll back and tick no, then this question comes up every time I migrate.
This is weird since I don't use any of the django ContentType framework anywhere. When inspecting which fields point to ContentType however I see that auth.permission points to it, and I use permissions for those models. So maybe the deletion cascades from old permissions pointing to the old model names which in turn would delete my instances? If that is the case, how can I prevent this situation?
This is the migration that was generated:
operations = [
migrations.RenameModel(
old_name='CombinedProduct',
new_name='Set',
),
migrations.RenameModel(
old_name='CombinedProductPrice',
new_name='SetPrice',
),
migrations.AlterModelOptions(
name='setprice',
options={'ordering': ('set', 'vendor', 'price'), 'verbose_name': 'Set price', 'verbose_name_plural': 'Set prices'},
),
migrations.RenameField(
model_name='setprice',
old_name='combined_product',
new_name='set',
),
]
If you want to rename your table, please take a look to RenameModel. Yes, Django do not detect the renamed model. So, you need to add it manually.

How to find user group and use of caching in django?

I am new to django/python and working my way through my webapp. I need assistance in solving one of my problems.
In my app, I am planning to assign each user (from auth_user) to one of the group ( from auth_group). Each group can have multiple users. I have entry in auth_group, auth_user and auth_user_groups. Here is my question:
At time of login I want to check that logging user belongs to which group?
I want to keep that group info in session/cache so all pages I can show information about that group only.
If you have any sample code will be great.
Giving support to the very well #trinchet's answer with an example of context_processor code.
Puts inside your webapp a new file called context_processors.py and writes this lines on it:
def user_groups(request):
"""
Add `groups` var to the context with all the
groups the logged in user has, so you can access
in your templates to this var as: {{ groups }}
"""
groups = None
if request.user.is_authenticated():
groups = user.groups
return {'groups': groups}
Finally on your settings.py add 'webbapp.context_processors.user_groups'to TEMPLATE_CONTEXT_PROCESSOR:
TEMPLATE_CONTEXT_PROCESSORS = (
'webbapp.context_processors.user_groups',
)
1) Be user an instance of auth.models.User, you can get all groups the user belong to, through user.groups. If you want to ask at time of login then you should do this in your login view.
2) You can use session or cache approaches to deal with, this is irrelevant, but once you have the group you need to render the pages having this value, i mean, you need to provide the group to the template rendering, to do this I suggest to you using a custom context processor.

Backbone-relational with Django

I'm building a Backbonejs app that is running Django in the backend. In my Django, i have models like Author, books, shelf and user and they are related to one another. In Backbone, I have a model Author and when I do a fetch() I get its related models in an array. Should I proceed like this or it's better to create the same models in Backbone and do the same relations between them? (with backbone-relational)
Also, let's say I go with the second option, when i do fetch() and get related models, shall backbone-relational recognize it directly?
Thanks
I would recommend leveraging Backbone relational--especially if you expect the app to get somewhat complex later.
Probably you won't have to change your server side code, you can get Backbone relational to instantiate any related models that are included in the JSON of the model you have fetched. So if for an author query your backend returns:
[{
name: "Hemingway, Ernest",
books: [
{name: "For whom the bell tolls", ISBN: 1234},
{name: "The sun also rises", ISBN: 2345}
]
}]
... and you have defined a has-many relationship between Authors and books Backbone relational will instantiate the books as well.

Django Blog App urls functionality

I am trying to integrate the following blog APP https://github.com/nathanborror/django-basic-apps ,so in my main urls.py i have included the blog urls as (r'^blog/',include('basic.blog.urls')), Now my question is that now when i point my browser to the blog APP http://127.0.0.1/blog/ i get a message as "Post archive",How to proceed from here i.e, how to post blog and retrieve the same.What is the url to be used..The following is the blog urls
from django.conf.urls.defaults import *
urlpatterns = patterns('basic.blog.views',
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
view='post_detail',
name='blog_detail'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/$',
view='post_archive_day',
name='blog_archive_day'
),
url(r'^(?P<year>\d{4})/(?P<month>\w{3})/$',
view='post_archive_month',
name='blog_archive_month'
),
url(r'^(?P<year>\d{4})/$',
view='post_archive_year',
name='blog_archive_year'
),
url(r'^categories/(?P<slug>[-\w]+)/$',
view='category_detail',
name='blog_category_detail'
),
url (r'^categories/$',
view='category_list',
name='blog_category_list'
),
url(r'^tags/(?P<slug>[-\w]+)/$',
view='tag_detail',
name='blog_tag_detail'
),
url (r'^search/$',
view='search',
name='blog_search'
),
url(r'^page/(?P<page>\d+)/$',
view='post_list',
name='blog_index_paginated'
),
url(r'^$',
view='post_list',
name='blog_index'
),
)
I have never used this blogging app, but im guessing because it suggests its "basic" it will just provide the bare bones. So my starting point would be to add a post and see what happens.
If going to /blog/ doesnt provide a way to add a post, then register the models with your admin site and add through that way. Im guessing that you may have to build your own adding sections...
If you dont want to do this, djang-blog-zinnia is a blogging app i have used, and really like it
There are no URLs specific to post creation, so you need to do it via the Admin interface. I looked at the code and there is a specific template for creating/modifying post objects.
I've used and customized the basic blog application
The creation can be done through the Admin interface, the models are already registered with the admin interface
You just need to provide a good layout and some cool stylesheets for your front end to get started