Django Practice to organize views that have same permission - python

The login_required, user_passes_test and permission_required decorator only apply to specific functions, similar for the mixin. But is it a good practice to put #permission_required('polls.add_choice') to each and every view that require such permission?
I think it is quite common that multiple views have the same permission. For example, you have an employer and job seeker, only the employer can add company name/ address, post a job and check job application. It is also common that the website requires login for most of its pages.
So my question is what is the idioms/practice assigning the same permission to multiple views? The only recipe I can find is Beginning Django - Listing 10-8. Permission checks in urls. Pay for include () definitions. Another approach is to swap the view function inside a class (as static method) and do some trick the add permission to all methods.
Is there any better sulotion? Or any reason not to do that?

I think that in this case it is most ideal to use Django's groups system.
It's totally ok to use same permission for several views because in some cases there is more views than the 4 CRUD views and 2 views can be intended to same user/rule/groups.

It also depends on number of online users of your site.
It there are thousands of users online - try to cache that wrappers.
or rewrite all to api

Related

Django create a custom form permission

I'm developing a management software. And I need create a module for manage the permissions and groups using the auth of django. I dont want use the admin django because this just allow log in for super users.
I want override the admin route and create a form with the same features from the admin site. If is possible, I want use the widget for the assignment of permission and group.
I need all this built into an app because I need this to work for this and other projects.
I have already written a custom form to add, edit and view users extending the class UserCreationForm, I need something similar to that.
I hope you can help me...
First things first: don't do this!
Creating your own Django admin site is a load of work, and likely to be insecure etc. Your'e opening a giant can of worms here.
If you need members of your app to edit permissions, they do not have to be superusers! Users with is_staff = True can all access the admin site. Once you've set this for the users you want, go ahead and configure the exact permissions for this type of user.
Start with the official docs on user permissions.

What are the differences between Generics, Views, Viewsets and Mixins in Django?

I am new to Django and Django-Rest. I am confused about when I should use these? what are their advantages and disadvantages? I have only seen this- http://www.cdrf.co
The only thing I know is there are a lot of ways to do 1 thing. But this is totally unclear to me.
In Django, these four terms we use frequently for different purposes in the projects. I have tried to collect and share the actual meaning with the links to details description of each term. Please check if you find these helpful.
Generic views:
“Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.”
— Django Documentation
Read more details
Views:
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as it’s on your Python path. There’s no other requirement–no “magic,” so to speak. For the sake of putting the code somewhere, the convention is to put views in a file called views.py, placed in your project or application directory.
Read more details
Viewsets:
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks, you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
Read more details
Mixins:
The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post(), directly. This allows for more flexible composition of behavior.
The mixin classes can be imported from rest_framework.mixins.
Read more details

Subclassing and overriding Django Class based views

I'm building a website using django-all auth for it's authentication and social authentication functions. The forms that come bundled with the app are hardly great to look at and hence I decided to create my own views.
The problem is: How do I create them while ensuring that the backend of Django all auth is still available to me? I've dug into the source code and found that it uses class based views for rendering and performing CRUD operations.
I want to know if I can subclass those views in my own app/views.py and just change their template_name field to my own templates. Any advice would be most helpful.
Thanks.
You can of course subclass the views, as long as you change your URLs to point to the overridden versions. However, there is no need to do this just to use your own templates; Django's template loader is specifically written with this use case in mind. Simply create your own directory inside your templates folder to match the one allauth is using, and create your own template files inside it; Django will find yours first and use them.

Check if user is authenticated in urls.py

Is it possible to do something like this in urls.py?
urls.py: http://pastebin.com/raw.php?i=QVQ8BEvJ
This is not right way to implement it.
The best solution is to wrap your views with #login_requered decorator.
Example:
#login_required
def home_page(request):
...
You can specify in your settings.py LOGIN_URL where user will be redirected if not authorized.
Please read more at django documentation
Authentication checks should be performed in the view, that's where checks and security are ment to exist.
Apart from that you can decorate Class Based Views in urls to check for login, but the most common / sensible / usual approach is to make that check in the view.
If you are using Class Based Views then you could create a Mixin which checks if the user is authenticated, this combined with the tools Django Offers, allow you to redirect the user to the appropriate view (login, or if check is passed allow him to view the requested url).
If you are using function based views, then Django offers decorators for those functions to provide common "needs" of a web framework.
PS If you are using CBV's then django-braces has already a few wonderful mixins available for common tasks (Ajax, Security etc).

Django, how to generate an admin panel without models?

I'm building a rather large project, that basically consists of this:
Server 1:
Ice based services.
Glacier2 for session handling.
Firewall allowing access to Glacier2.
Server 2:
Web interface (read, public) for Ice services via Glacier2.
Admin interface for Ice services via Glacier 2.
The point I'm concerned with is the web interface. I want to use Django, because it's both written in python and has that incredibly useful automatic admin panel generator.
The web interface doesn't access any database. It connects to an Ice service on Server #1 via the Glacier2 router and uses the API exposed by those services to manipulate data.
And as you probably know, the admin generation in Django depends on the use of Django's ORM; which I'm not using since I have no database to access.
So I need to generate the admin panel, but, instead of having an standard data access like the ORM normally does, I need to intercept any "db-access" calls and transform them into Ice service calls, and then take the service's output (if any), transform it into whatever the ORM normally returns and return control to Django.
Anyone knows how I could do this? what would I need to subclass? Any specific ideas?
Thanks for your time.
I think there might be a simpler way than writing custom ORMS to get the admin integration you want. I used it in an app that allows managing Webfaction email accounts via their Control Panel API.
Take a look at models.py, admin.py and urls.py here: django-webfaction
To create an entry on the admin index page use a dummy model that has managed=False
Register that model with the admin.
You can then intercept the admin urls and direct them to your own views.
This makes sense if the add/edit/delete actions the admin provides make sense for your app. Otherwise you are better off overriding the admin index or changelist templates to include your own custom actions
The real power of the contrib.admin is django Forms. In essence, the admin tool is basically auto-generating a Form to match a Model with a little bit of urls.py routing thrown in. In the end it would probably just be easier to use django Forms apart from the admin tool.
you can "mock" some class so it look like a model but it does proxy to your APIs
f.e.
class QuerysetMock(object):
def all():
return call_to_your_api()
[...]
class MetaMock(object):
def fields():
return fields_mock_objects..
verbose_name = ''
[...]
class ModelMock(object):
_meta = MetaMock()
objects = QuerysetMock()
admin.site.register(ModelMock)
This may work.. but you need to do a lot django.model compatible stuff
The django ORM has a pluggable backent, which means that you can write a backend for things that aren't RDBMSes. It's probably a rather large task, but a good place to get started is with Malcolm Tredinnick's talk from DjangoCon 2008, Inside the ORM.
Otherwise, you could bypass the ORM altogether, and write the forms manually for the access you need.

Categories