I want to create the permissions in views dynamically instead of the defaults at models
I create a main class called CreatorView
from django.views.generic import View
from django.forms.models import modelform_factory
class CreatorView(View):
model = None
fields = None
exclude = None
form = None
page_title = ''
def create_form(self):
default =dict()
if self.fields == None:
if self.exclude == None:
default['fields'] = self.fields = self.model._meta.fileds
else:
default['exclude'] = self.exclude
else:
if self.exclude:
raise Exception('error')
default['fields'] = self.fields
return modelform_factory(self.model,**default)
def get(self,request,*args,**kwargs):
return render('','base.html')
def post(self,request,*args,**kwargs):
... and so on
the main urls is:
urlpatterns = [
path('%s/%s' % (cls.model._meta.app_label, cls.__name__.lower()), cls.as_view(),
name='%s/%s' % (cls.model._meta.app_label, cls.__name__.lower())) for cls
in CreatorView.__subclasses__()]
if I make inheritance from CreatorView then my class should create a page
for example:
class Login(CreatorView):
model = Users
""" my overwrite methods and actions """
class Configurations(CreatorView):
model = Configure
""" my overwrite methods and actions """
class Teachers(CreatorView):
model = Teachers
""" my overwrite methods and actions """
class Students(CreatorView):
model = Students
""" my overwrite methods and actions """
and so on
this code will create to me four pages
I want to create table semi to django content_type model to be like:
id
app_label
page
1
myapp
login
2
myapp
configurations
3
myapp
teachers
4
myapp
students
Can I modify auth_permission table in Django to make content_type foreign key from my content_type?
If I can how to prevent insert default permissions and make my insertion for default permission?
You can create Permissions manually according to docs here
from myapp.models import BlogPost
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(
codename='can_publish',
name='Can Publish Posts',
content_type=content_type,
)
OR
An enhanced permission library which enables a logic-based permission system to handle complex permissions in Django.
here
Related
I extend the default user model with a proxy model to add an extra method.
from django.contrib.auth.models import User
class Person(User):
class Meta:
proxy = True
def custom_method(self):
pass
The main purpose is to use the method in templates.
<div>{{ user.custom_method }}</div>
But since the user is pointing to the default user model, it has no access to the custom_method.
Is there any way to achieve this other than create a subclass of the User model?
=== UPDATE ==============
I ended up with custom backends:
(not sure if this solution has any drawbacks)
# user proxy
class ExtendedUser(get_user_model()):
class Meta:
proxy = True
def custom_method(self):
...
# backends
from django.contrib.auth.backends import ModelBackend
# since I'm using allauth
from allauth.account.auth_backends import AuthenticationBackend
from .models import ExtendedUser
class DjangoModelBackend(ModelBackend):
def get_user(self, user_id):
print("\n\n\ncustom user!!!")
try:
user = ExtendedUser.objects.get(pk=user_id)
except ExtendedUser.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None
class AuthModelBackend(DjangoModelBackend, AuthenticationBackend):
pass
And in settings.py, add these to AUTHENTICATION_BACKENDS.
It might be better to monkey patch the user model. Indeed, in one of the AppConfigs [Django-doc] we can implement this with:
# app_name/apps.py
from django.apps import AppConfig
from django.contrib.auth import get_user_model
def custom_method(self):
return 'Some value'
class MyAppConfig(AppConfig):
name = 'app_name'
def ready(self):
User = get_user_model()
User.custom_method = custom_method
Here we thus add a method to the user model that can then be called in views, templates, etc.
I'm trying to add custom functionality to django router methods.
This is my router that exposes the standard methods on an user.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [BasePermission]
I'm validating the user using serializer validation methods.
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
MOBILE_ERROR = 'Mobile number should be 10 digits long and only contain numbers.'
EMAIL_ERROR = 'Incorrect email format'
USERNAME_ERROR = 'Username must be at least 6 characters long and contain only letters and numbers.'
class Meta:
model = User
fields = '__all__'
def validate_mobile(self, value):
regexp = re.compile(r'^[0-9]{10}$')
if regexp.search(value):
return value
raise serializers.ValidationError(self.MOBILE_ERROR)
def validate_email(self, value):
if validate_email(value):
return value
raise serializers.ValidationError(self.EMAIL_ERROR)
def validate_username(self, value):
regexp = re.compile(r'^[a-zA-Z0-9]{6,}$')
if regexp.search(value):
return value
raise serializers.ValidationError(self.USERNAME_ERROR)
And this is my route.
router = DefaultRouter(trailing_slash=False)
router.register(r'user', UserViewSet),
urlpatterns = router.urls
I want to add a method send_activation_code if the user is created successfully. How do I do this?
For such purpose you can use signals. Every time when your app creates new User instance - some action should be performed. In your case you should connect build-in signal post_save and your existed send_activation_code function
Example for your case:
yourapp/signals.py:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def send_activation_code_signal(sender, instance, created, **kwargs):
if created:
send_activation_code(instance.phone_number)
Also, you need to import signals in your app config file
yourapp/app.py:
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class YourAppConfig(AppConfig):
name = 'yourproject.yourapp'
verbose_name = _('yourapp')
def ready(self):
import yourproject.yourapp.signals
yourapp/__init__.py:
default_app_config = 'yourproject.yourapp.apps.YourAppConfig'
If you dont need to send code every time User instance created - you can specify more statements, for example:
if created and instance.validated:
send_activation_code(instance.phone_number)
There are some more useful built-in signals in Django, check docs
Django signals docs: https://docs.djangoproject.com/en/3.0/ref/signals/
In "wagtail_hooks.py" I have the code below. As wagtail admin I can see the StudentModelAdmin, but as a user with restricted access to the admin interface I can't.
I would like to allow users with wagtail admin access and the specific permission below to access the student model admin. How do I go about creating the "CourseRegisterPermission" class?
from wagtail.contrib.modeladmin.options import (ModelAdmin, modeladmin_register)
from wagtail.wagtailcore import hooks
from .models import Participant
#hooks.register('register_permissions')
def view_course_registrations():
return Permission.objects.filter(codename="view_course_registrations")
class CourseRegisterPermission(PermissionHelper):
# how do I allow users with the permission to view course registrations
# to see the 'StudentModelAdmin" below?
class StudentModelAdmin(ModelAdmin):
model = Participant
menu_label = "Student Registrations"
menu_icon = "group"
search_fields = ('name', 'supervisor_name')
list_display = ('name', 'email')
list_filter = ('course',)
permission_helper_class = CourseRegisterPermission
I tried to find some examples of wagtail PermissionHelper but wasn't able to find any.
Any hint would be appreciated!
You can use the wagtail.contrib.modeladmin.helpers.PermissionHelper or wagtail.contrib.modeladmin.helpers.PagePermissionHelper permission helper classes from Wagtail's sources as an example. See methods like user_can_list, user_can_create, etc.
But... Are you sure that you need to define your own permission helper class? It seems to me that you can just create a new (or edit existing) group in the Wagtail admin and give required object permissions to your Participant model.
On my screenshot Programme is the model that I manage using ModelAdmin.
You can override some functions inside CourseRegisterPermission
class CourseRegisterPermission(PermissionHelper):
def user_can_list(self, user):
"""
Return a boolean to indicate whether `user` is permitted to access the
list view for self.model
"""
# this is just an example
return user.role == "driver"
def user_can_delete_obj(self, user, obj):
"""
Return a boolean to indicate whether `user` is permitted to 'delete'
a specific `self.model` instance.
"""
perm_codename = self.get_perm_codename('delete')
if obj.status > 0:
return False
if not self.user_has_specific_permission(user, perm_codename):
return False
if user.id == obj.id:
# users may not delete themselves
return False
You can also override the following functions:
def user_can_list(self, user):
def user_can_create(self, user):
def user_can_inspect_obj(self, user, obj):
def user_can_edit_obj(self, user, obj):
def user_can_delete_obj(self, user, obj):
def user_can_unpublish_obj(self, user, obj):
def user_can_copy_obj(self, user, obj):
I was trying to create a custom permission in a migration, however after running migrate, the permission was not created in the permission table. Could someone point out what the error was?
Also I am not sure what I should use as the related model for ContentType as the permission is used for restricting users that can view a page which shows summary of users on the site.
Any help will be greatly appreciated, thanks.
def add_view_aggregated_data_permissions(apps, schema_editor):
ContentType = apps.get_model('django', 'ContentType')
Permission = apps.get_model('auth', 'Permission')
content_type = ContentType.objects.get(app_label='auth', model='user')
permission = Permission.objects.create(codename='can_view_data',
name='Can view data',
content_type=content_type)
I would recommend you to use the standard way to use custom permissions as described in the Django documentation. You will avoid many issues altogether.
To create custom permissions for a given model object, use the permissions model Meta attribute.
This example model creates a custom permission:
class MyModel(models.Model):
...
class Meta:
permissions = (
('view_data', "Can see available data"),
)
The only thing this does is create those extra permissions when you run manage.py migrate. Your code is in charge of checking the value of these permissions when a user is trying to access the functionality provided by the application...
Then you can use the permission_required decorator with your view to check for the specific permission:
from django.contrib.auth.decorators import permission_required
#permission_required('myapp.view_data')
def my_view(request):
...
I wanted to created a custom permission (read) for all app models. I did this two steps:
Create an extended permission from DjangoModelPermissions:
class DjangoModelPermissionsExtended(DjangoModelPermissions):
"""
"""
perms_map = {
'GET': ['%(app_label)s.read_%(model_name)s'],
'OPTIONS': [],
'HEAD': [],
'POST': ['%(app_label)s.add_%(model_name)s'],
'PUT': ['%(app_label)s.change_%(model_name)s'],
'PATCH': ['%(app_label)s.change_%(model_name)s'],
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
}
Put it in each view I want to have read permission:
class ExampleViewSet(viewsets.ModelViewSet):
permission_classes = (
DjangoModelPermissionsExtended,
)
Create a django command customread.py:
from django.core.management.base import BaseCommand, CommandError
from project.app import models as app_models
from django.db import models
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
import inspect
class Command(BaseCommand):
help = 'Create the read permission to app models'
def handle(self, *args, **options):
for name, obj in inspect.getmembers(app_models):
if inspect.isclass(obj) and issubclass(obj, models.Model):
try:
self.add_canread(obj)
self.stdout.write(self.style.SUCCESS(
'created permission for %s' % obj
))
except Exception as e:
self.stdout.write(self.style.ERROR(
'Permission already exists for %s' % obj
))
def add_canread(self, object_class):
"""This a function that can be executed in order to create
new permissions (read view) to a class in DB.
"""
if inspect.isclass(object_class):
content_type = ContentType.objects.get_for_model(object_class)
permission = Permission.objects.create(
codename='read_{}'.format(object_class._meta.model_name),
name='Can view {}'.format(object_class.__name__),
content_type=content_type,
)
else:
msg = "The object is not a class"
print(msg)
Execute it after doing migrations:
python manage.py customread
As of django 1.8 and built-in migrations this is very painless.
All you need to do is add the permissions you want to the relevant
model
Run makemigration
./manage.py makemigrations
run the migration created in the step above
./manage.py migrate
My app has users who create pages. In the Page screen of the admin, I'd like to list the User who created the page, and in that list, I'd like the username to have a link that goes to the user page in admin (not the Page).
class PageAdmin(admin.ModelAdmin):
list_display = ('name', 'user', )
list_display_links = ('name','user',)
admin.site.register(Page, PageAdmin)
I was hoping that by making it a link in the list_display it would default to link to the actual user object, but it still goes to Page.
I'm sure I'm missing something simple here.
Modifying your model isn't necessary, and it's actually a bad practice (adding admin-specific view-logic into your models? Yuck!) It may not even be possible in some scenarios.
Luckily, it can all be achieved from the ModelAdmin class:
from django.urls import reverse
from django.utils.safestring import mark_safe
class PageAdmin(admin.ModelAdmin):
# Add it to the list view:
list_display = ('name', 'user_link', )
# Add it to the details view:
readonly_fields = ('user_link',)
def user_link(self, obj):
return mark_safe('{}'.format(
reverse("admin:auth_user_change", args=(obj.user.pk,)),
obj.user.email
))
user_link.short_description = 'user'
admin.site.register(Page, PageAdmin)
Edit 2016-01-17:
Updated answer to use make_safe, since allow_tags is now deprecated.
Edit 2019-06-14:
Updated answer to use django.urls, since as of Django 1.10 django.core.urls has been deprecated.
Add this to your model:
def user_link(self):
return '%s' % (reverse("admin:auth_user_change", args=(self.user.id,)) , escape(self.user))
user_link.allow_tags = True
user_link.short_description = "User"
You might also need to add the following to the top of models.py:
from django.template.defaultfilters import escape
from django.core.urls import reverse
In admin.py, in list_display, add user_link:
list_display = ('name', 'user_link', )
No need for list_display_links.
You need to use format_html for modern versions of django
#admin.register(models.Foo)
class FooAdmin(admin.ModelAdmin):
list_display = ('ts', 'bar_link',)
def bar_link(self, item):
from django.shortcuts import resolve_url
from django.contrib.admin.templatetags.admin_urls import admin_urlname
url = resolve_url(admin_urlname(models.Bar._meta, 'change'), item.bar.id)
return format_html(
'{name}'.format(url=url, name=str(item.bar))
)
I ended up with a simple helper:
from django.shortcuts import resolve_url
from django.utils.safestring import SafeText
from django.contrib.admin.templatetags.admin_urls import admin_urlname
from django.utils.html import format_html
def model_admin_url(obj: Model, name: str = None) -> str:
url = resolve_url(admin_urlname(obj._meta, SafeText("change")), obj.pk)
return format_html('{}', url, name or str(obj))
Then you can use the helper in your model-admin:
class MyAdmin(admin.ModelAdmin):
readonly_field = ["my_link"]
def my_link(self, obj):
return model_admin_url(obj.my_foreign_key)
I needed this for a lot of my admin pages, so I created a mixin for it that handles different use cases:
pip install django-admin-relation-links
Then:
from django.contrib import admin
from django_admin_relation_links import AdminChangeLinksMixin
#admin.register(Group)
class MyModelAdmin(AdminChangeLinksMixin, admin.ModelAdmin):
# ...
change_links = ['field_name']
See the GitHub page for more info. Try it out and let me know how it works out!
https://github.com/gitaarik/django-admin-relation-links
I decided to make a simple admin mixin that looks like this (see docstring for usage):
from django.contrib.contenttypes.models import ContentType
from django.utils.html import format_html
from rest_framework.reverse import reverse
class RelatedObjectLinkMixin(object):
"""
Generate links to related links. Add this mixin to a Django admin model. Add a 'link_fields' attribute to the admin
containing a list of related model fields and then add the attribute name with a '_link' suffix to the
list_display attribute. For Example a Student model with a 'teacher' attribute would have an Admin class like this:
class StudentAdmin(RelatedObjectLinkMixin, ...):
link_fields = ['teacher']
list_display = [
...
'teacher_link'
...
]
"""
link_fields = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.link_fields:
for field_name in self.link_fields:
func_name = field_name + '_link'
setattr(self, func_name, self._generate_link_func(field_name))
def _generate_link_func(self, field_name):
def _func(obj, *args, **kwargs):
related_obj = getattr(obj, field_name)
if related_obj:
content_type = ContentType.objects.get_for_model(related_obj.__class__)
url_name = 'admin:%s_%s_change' % (content_type.app_label, content_type.model)
url = reverse(url_name, args=[related_obj.pk])
return format_html('{}', url, str(related_obj))
else:
return None
return _func
If anyone is trying to do this with inline admin, consider a property called show_change_link since Django 1.8.
Your code could then look like this:
class QuestionInline(admin.TabularInline):
model = Question
extra = 1
show_change_link = True
class TestAdmin(admin.ModelAdmin):
inlines = (QuestionInline,)
admin.site.register(Test, TestAdmin)
This will add a change/update link for each foreign key relationship in the admin's inline section.