Branching Workflows based on value of specified Page field - wagtail

I have a DailyReflectionPage Model with a reflection_date field that forms the basis for the Page's slug, which is in the form YYYY-MM-DD. Here's an extract of my Page model:
class DailyReflectionPage(Page):
"""
The Daily Reflection Model
"""
...
...
reflection_date = models.DateField("Reflection Date", max_length=254)
...
...
#cached_property
def date(self):
"""
Returns the Reflection's date as a string in %Y-%m-%d format
"""
fmt = "%Y-%m-%d"
date_as_string = (self.reflection_date).strftime(fmt)
return date_as_string
...
...
def full_clean(self, *args, **kwargs):
# first call the built-in cleanups (including default slug generation)
super(DailyReflectionPage, self).full_clean(*args, **kwargs)
# now make your additional modifications
if self.slug is not self.date:
self.slug = self.date
...
...
These daily reflections are written by different authors, as part of a booklet that is published towards the end of the year, for use in the coming year. I would like to have a workflow where, for instance, the daily reflections from January to June are reviewed by one group, and those from July to December are reviewed by another group, as illustrated in the diagram below:
How can this be achieved?

This should be able to be achieved by creating ONE new Workflow Task type that has a relationship to two sets of User Groups (e.g. a/b or before/after, it is probably best to keep this generic in the model definition).
This new Task can be created as part of a new Workflow within the Wagtail admin, and each of the groups linked to the Moderator Group 1 / 2.
Wagtail's methods on the Task allow you to return approval options based on the Page model for any created workflow, from here you can look for a method that would be on the class and assign the groups from there.
The benefits of having a bit more of a generic approach is that you could leverage this for any splitting of moderator assignments as part of future Workflow tasks.
Implementation Overview
1 - read the Wagatail Docs on how to add a new Task Type and the Task model reference to understand this process.
2 - Read through the full implementation in the code of the built in GroupApprovalTask.
3 - In the GroupApprovalTask you can see that the methods with overrides all rely on the checking of self.groups but they all get the page passed in as a arg to those methods.
4 - Create a new Task that extends the Wagtail Task class and on this model create two ManyToManyField that allow for two sets of user groups being linked (note: you do not have do to this as two fields, you could put a model in the middle but the example below is just the simplest way to get to the gaol).
5 - On the DailyReflectionPage model create a method get_approval_group_key which will return maybe a simple Boolean or a 'A' or 'B' based on the business requirements you described above (check the model's date etc)
6 - In your custom Task create a method that abstracts the checking of the Page for this method and returns the Tasks' user group. You may want to add some error handling and default values. E.g. get_approval_groups
7 - Add a custom method for each of the 'start', 'user_can_access_editor', page_locked_for_user, user_can_lock, user_can_unlock, get_task_states_user_can_moderate methods that calls get_approval_group with the page and returns the values (see the code GroupApprovalTask for what these should do.
Example Code Snippets
models.py
class DailyReflectionPage(Page):
"""
The Daily Reflection Model
"""
def get_approval_group_key(self):
# custom logic here that checks all the date stuff
if date_is_after_foo:
return 'A'
return 'B'
class SplitGroupApprovalTask(Task):
## note: this is the simplest approach, two fields of linked groups, you could further refine this approach as needed.
groups_a = models.ManyToManyField(
Group,
help_text="Pages at this step in a workflow will be moderated or approved by these groups of users",
related_name="split_task_group_a",
)
groups_b = models.ManyToManyField(
Group,
help_text="Pages at this step in a workflow will be moderated or approved by these groups of users",
related_name="split_task_group_b",
)
admin_form_fields = Task.admin_form_fields + ["groups_a", "groups_b"]
admin_form_widgets = {
"groups_a": forms.CheckboxSelectMultiple,
"groups_b": forms.CheckboxSelectMultiple,
}
def get_approval_groups(self, page):
"""This method gets used by all checks when determining what group to allow/assign this Task to"""
# recommend some checks here, what if `get_approval_group` is not on the Page?
approval_group = page.specific.get_approval_group_key()
if (approval_group == 'A'):
return self.group_a
return self.group_b
# each of the following methods will need to be implemented, all checking for the correct groups for the Page when called
# def start(self, ...etc)
# def user_can_access_editor(self, ...etc)
# def page_locked_for_user(self, ...etc)
# def user_can_lock(self, ...etc)
# def user_can_unlock(self, ...etc)
def get_task_states_user_can_moderate(self, user, **kwargs):
# Note: this has not been tested, however as this method does not get `page` we must find all the tasks allowed indirectly via their TaskState pages
tasks = TaskState.objects.filter(status=TaskState.STATUS_IN_PROGRESS, task=self.task_ptr)
filtered_tasks = []
for task in tasks:
page = task.select_related('page_revision', 'task', 'page_revision__page')
groups = self.get_approval_groups(page)
if groups.filter(id__in=user.groups.all()).exists() or user.is_superuser:
filtered_tasks.append(task)
return TaskState.objects.filter(pk__in=[task.pk for task in filtered_tasks])
def get_actions(self, page, user):
# essentially a copy of this method on `GroupApprovalTask` but with the ability to have a dynamic 'group' returned.
approval_groups = self.get_approval_groups(page)
if approval_groups.filter(id__in=user.groups.all()).exists() or user.is_superuser:
return [
('reject', "Request changes", True),
('approve', "Approve", False),
('approve', "Approve with comment", True),
]
return super().get_actions(page, user)

Related

Creating object with ManyToMany field via DRF ViewSet's perform_create

I have a simple model:
class Item(models.Model):
user = ForeignKey(User, related_name="user_items")
users = ManyToManyField(User, related_name="users_items")
I want it so that when a user creates an Item via ViewSet, that user is automatically assigned to the user and users fields.
I typically do this for ForeignKey's via the ViewSet's perform_create:
class ItemViewSet(viewsets.ModelViewSet):
...
def perform_create(self, serializer):
if self.request.user.is_authenticated:
serializer.save(user=self.request.user)
else:
serializer.save()
When I try to do it for the ManyToManyField too, I get this error:
{'users': [ErrorDetail(string='This list may not be empty.', code='empty')]}
I've tried the following in perform_create():
# 1
serializer.save(user=self.request.user, users=self.request.user)
# 2
serializer.save(user=self.request.user, users=[self.request.user])
# 2
serializer.save(user=self.request.user, users=[self.request.user.id])
How can I update a ManyToManyField via a ViewSet's perform_create?
Edit:
I guess the following works:
obj = serializer.save(user=self.request.user)
obj.users.add(self.request.user)
Is there no way to have the M2M field when the object is initially created though?
when you want set a list to m2m field one of the things you can do is this:
item_obj.users.set(user_list)
probably you need first get your item_obj.
for this you can get your object id from item_id = serializer.data.get('id') , and then item_obj = Item.objects.get(id = item_id)

How to retrieve Images of a User being part of a Group with Collection Permissions in Wagtail?

I have a wagtail installation using the Multisite pattern, where I have a group of user per site and each group as it's own collection.
When the User logged in the admin interface, they see in the Summary section the image count from all the collections.
But when they click the image menu, they only see the images within their group collection. I found it confusing that they could know the total count of all collections. I wanted to get the count from the collection the user had rights for.
I figured out I could override the ImagesSummaryItem and I ended up coding the following snippet of code:
class CorrectedImagesSummaryItem(SummaryItem):
order = 200
template = 'wagtailimages/homepage/site_summary_images.html'
def get_context(self):
site_name = get_site_for_user(self.request.user)['site_name']
permissions = Permission.objects.filter(
content_type=ContentType.objects.get_for_model(get_image_model()),
codename__in=['change_image', 'add_image'])
collections = Collection.objects.filter(
group_permissions__group__in=self.request.user.groups.all(),
group_permissions__permission__in=permissions
).distinct()
if collections:
image_count = get_image_model().objects.filter(collection__in=collections).count()
else:
image_count = 0
return {
'total_images': image_count,
'site_name': site_name,
}
def is_shown(self):
return permission_policy.user_has_any_permission(
self.request.user, ['change', 'add']
)
#hooks.register('construct_homepage_summary_items')
def add_corrected_images_summary_panel(request, items):
"""Replaces the Images summary panel to hide variants."""
for index, item in enumerate(items):
if item.__class__ is ImagesSummaryItem:
items[index] = CorrectedImagesSummaryItem(request)
This actually works fine, I am now showing the proper images count on the summary section but I am wondering is there a better way to query the collections of the user? Are these querysets right?
permissions = Permission.objects.filter(
content_type=ContentType.objects.get_for_model(get_image_model()),
codename__in=['change_image', 'add_image'])
collections = Collection.objects.filter(
group_permissions__group__in=self.request.user.groups.all(),
group_permissions__permission__in=permissions
).distinct()
Update
I ended up customizing the queryset for the images selection in order to only show the images within the collection the user was having access to.
In addition of the first function, I added the following code in my wagtail_hooks.py file.
#hooks.register('construct_image_chooser_queryset')
def show_collection_images_only(images, request):
# Show only the images from the collection the User has access.
collections = get_collections_from_group_permissions(request.user, ['change_image', 'add_image'])
images = images.filter(collection__in=collections)
return images
The get_collections_from_group_permissions is just a simplified function that returns exactly the Collection out of the Groups permissions the User has.
def get_collections_from_group_permissions(user, permissions):
"""
This function gets the Collections from the user groups permissions.
:param user: the user
:param permissions: the requested permissions on a Collection object
:returns: the Collections the selected User has access rights for.
"""
permissions = Permission.objects.filter(
content_type=ContentType.objects.get_for_model(get_image_model()),
codename__in=permissions)
collections = Collection.objects.filter(
group_permissions__group__in=user.groups.all(),
group_permissions__permission__in=permissions
).distinct()
return collections
With this in place, the Summary Item for the images is the number of images within the collections the User can access and when he clicks on a ImageChooserField and gets to the Image chooser, he only gets to see what is in the collections he has been granted access.
This logic is already implemented in Wagtail's permission_policy class, so this could be reduced to:
image_count = permission_policy.instances_user_has_any_permission_for(
self.request.user, ['change', 'add']
).count()
(Incidentally, the reason Wagtail itself doesn't take permissions into account when displaying this figure is that all users can see the complete set of images via the chooser popup - there's currently no 'choose' permission - so showing a reduced number would be misleading. See the discussion at https://github.com/wagtail/wagtail/issues/5129)

Django Models: How to setup these DB constraints on the fields?

Suppose I have the following Model:
class myClassObj(models.Model):
flag1 = models.NullBooleanField()
flag2 = models.BooleanField()
Now also suppose I want the Database to enforce the following constraint:
flag1 should be None if and only if flag2 is false
How can I write the constraints in this model so that this condition is checked any time a myClassObj is created or edited? I see some interesting information here. But I don't see how to specify an "iff" constraint as I described above.
The Django documentation recommends doing custom validation where access to multiple fields is required by overriding Model.clean().
This example from the documentation show how it's possible to validate that a news article still in the "draft" phase does not have a publication date.
def clean(self):
import datetime
from django.core.exceptions import ValidationError
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
raise ValidationError('Draft entries may not have a publication date.')
# Set the pub_date for published items if it hasn't been set already.
if self.status == 'published' and self.pub_date is None:
self.pub_date = datetime.date.today()
For more detailed information, see the full reference here: https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects
To have this called every time you save the object you'll also need to override the save method: https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods.
Another useful reference for other use cases if you only need to validate a single field is writing custom validators: https://docs.djangoproject.com/en/dev/ref/validators/

google cloud endpoint method with multiple response message

I have a google could enpoint method that I need to be able to return either a MaleResponseMessage or a FemaleResponseMessage. Is there a way to specify that such as with
#endpoints.method(message_types.VoidMessage, [MaleResponseMessage, FemaleResponseMessage])
There is of course the option of declaring a super message class, say, PersonResponseMessage to wrap either MaleResponseMessage or FemaleResponseMessage. But is there something similar to the snippet above?
EDIT:
Trying to implement my own proposal, I got stuck. The only thing the two message types have in common is the request: the exact same request fields (with an additional boolean female=true/false) for PersonRequest. The MaleResponseMessage and the FemaleResponseMessage have no field in common. So I am using one endpoint method, as #bossylobster shows, where I check
if request.female : # request.female == True
return get_female(etc, etc)
else: # request.female == False // implies male
return get_male(etc,etc)
For the response, I need something like
class PersonResponse(messages.Message):
if ??? :
item = messages.MessageField(MaleResponseMessage,1)
else:
item = messages.MessageField(FemaleResponseMessage,1)
I am not sure what to check ??? for. First, I thought about isinstance or type. But how would I do that? Would the below work?
class PersonResponse(messages.Message):
if type(Message()) == MaleResponseMessage :
item = messages.MessageField(MaleResponseMessage,1)
else:
item = messages.MessageField(FemaleResponseMessage,1)
Unfortunately no. You can have only one response and one request schema; this is because they are registered with Google's API infrastructure and having a strict schema is what provides the speed and efficiency of requests.
Your best bet would be to combine the fields needed for each male and female into a single model class and do your own validation.
A possible solution could look like
from protorpc import messages
class Gender(messages.Enum):
MALE = 0
FEMALE = 1
class GenderRequest(messages.Enum):
gender = messages.EnumField(Gender, 1, required=True)
class PersonResponse(messages.Message):
gender = messages.EnumField(Gender, 1)
# shared fields
# female specific fields
# male specific fields
and then in your actual method
#endpoints.method(GenderRequest, PersonMessage, ...)
def my_method(self, request):
if request.gender == Gender.MALE:
return male_response(request)
elif request.gender == Gender.FEMALE:
return female_response(request)
else:
# This should never occur since gender is required
raise endpoints.BadRequestException('Gender not set.')
where male_response and female_response are methods which create instances of PersonMessage corresponding to male and female.
You could use two different endpoint methods.

How can I mimic 'select_related' using google-appengine and django-nonrel?

django nonrel's documentation states: "you have to manually write code for merging the results of multiple queries (JOINs, select_related(), etc.)".
Can someone point me to any snippets that manually add the related data? #nickjohnson has an excellent post showing how to do this with the straight AppEngine models, but I'm using django-nonrel.
For my particular use I'm trying to get the UserProfiles with their related User models. This should be just two simple queries, then match the data.
However, using django-nonrel, a new query gets fired off for each result in the queryset. How can I get access to the related items in a 'select_related' sort of way?
I've tried this, but it doesn't seem to work as I'd expect. Looking at the rpc stats, it still seems to be firing a query for each item displayed.
all_profiles = UserProfile.objects.all()
user_pks = set()
for profile in all_profiles:
user_pks.add(profile.user_id) # a way to access the pk without triggering the query
users = User.objects.filter(pk__in=user_pks)
for profile in all_profiles:
profile.user = get_matching_model(profile.user_id, users)
def get_matching_model(key, queryset):
"""Generator expression to get the next match for a given key"""
try:
return (model for model in queryset if model.pk == key).next()
except StopIteration:
return None
UPDATE:
Ick... I figured out what my issue was.
I was trying to improve the efficiency of the changelist_view in the django admin. It seemed that the select_related logic above was still producing additional queries for each row in the results set when a foreign key was in my 'display_list'. However, I traced it down to something different. The above logic does not produce multiple queries (but if you more closely mimic Nick Johnson's way it will look a lot prettier).
The issue is that in django.contrib.admin.views.main on line 117 inside the ChangeList method there is the following code: result_list = self.query_set._clone(). So, even though I was properly overriding the queryset in the admin and selecting the related stuff, this method was triggering a clone of the queryset which does NOT keep the attributes on the model that I had added for my 'select related', resulting in an even more inefficient page load than when I started.
Not sure what to do about it yet, but the code that selects related stuff is just fine.
I don't like answering my own question, but the answer might help others.
Here is my solution that will get related items on a queryset based entirely on Nick Johnson's solution linked above.
from collections import defaultdict
def get_with_related(queryset, *attrs):
"""
Adds related attributes to a queryset in a more efficient way
than simply triggering the new query on access at runtime.
attrs must be valid either foreign keys or one to one fields on the queryset model
"""
# Makes a list of the entity and related attribute to grab for all possibilities
fields = [(model, attr) for model in queryset for attr in attrs]
# we'll need to make one query for each related attribute because
# I don't know how to get everything at once. So, we make a list
# of the attribute to fetch and pks to fetch.
ref_keys = defaultdict(list)
for model, attr in fields:
ref_keys[attr].append(get_value_for_datastore(model, attr))
# now make the actual queries for each attribute and store the results
# in a dict of {pk: model} for easy matching later
ref_models = {}
for attr, pk_vals in ref_keys.items():
related_queryset = queryset.model._meta.get_field(attr).rel.to.objects.filter(pk__in=set(pk_vals))
ref_models[attr] = dict((x.pk, x) for x in related_queryset)
# Finally put related items on their models
for model, attr in fields:
setattr(model, attr, ref_models[attr].get(get_value_for_datastore(model, attr)))
return queryset
def get_value_for_datastore(model, attr):
"""
Django's foreign key fields all have attributes 'field_id' where
you can access the pk of the related field without grabbing the
actual value.
"""
return getattr(model, attr + '_id')
To be able to modify the queryset on the admin to make use of the select related we have to jump through a couple hoops. Here is what I've done. The only thing changed on the 'get_results' method of the 'AppEngineRelatedChangeList' is that I removed the self.query_set._clone() and just used self.query_set instead.
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('username', 'user', 'paid')
select_related_fields = ['user']
def get_changelist(self, request, **kwargs):
return AppEngineRelatedChangeList
class AppEngineRelatedChangeList(ChangeList):
def get_query_set(self):
qs = super(AppEngineRelatedChangeList, self).get_query_set()
related_fields = getattr(self.model_admin, 'select_related_fields', [])
return get_with_related(qs, *related_fields)
def get_results(self, request):
paginator = self.model_admin.get_paginator(request, self.query_set, self.list_per_page)
# Get the number of objects, with admin filters applied.
result_count = paginator.count
# Get the total number of objects, with no admin filters applied.
# Perform a slight optimization: Check to see whether any filters were
# given. If not, use paginator.hits to calculate the number of objects,
# because we've already done paginator.hits and the value is cached.
if not self.query_set.query.where:
full_result_count = result_count
else:
full_result_count = self.root_query_set.count()
can_show_all = result_count self.list_per_page
# Get the list of objects to display on this page.
if (self.show_all and can_show_all) or not multi_page:
result_list = self.query_set
else:
try:
result_list = paginator.page(self.page_num+1).object_list
except InvalidPage:
raise IncorrectLookupParameters
self.result_count = result_count
self.full_result_count = full_result_count
self.result_list = result_list
self.can_show_all = can_show_all
self.multi_page = multi_page
self.paginator = paginator

Resources