I'm looking to do something like this:
http://stackoverflow.com/questions/160009/django-model-limitchoicestouser-user
with some differences.
Some models may explain:
class Job(models.Model):
name = models.CharField(max_length=200)
operators = models.ManyToManyField(User)
class Activity(models.Model):
job = models.ForeignKey(Job)
job_operators = models.ManyToManyField(User, limit_choices_to={user: Job.operators} blank=True, null=True)
Note: the syntax is not intended to necessarily correct, but illustrative.
Now, I've had some success at getting the current user, using middleware, as some answers on SO depict, however, I was hoping that I might get the current Job, via request.POST, such that, if the Activity were saved, I would be able to discern the current Job, and therefore the subset of Users as operators, that it turn, would be the user set to choose from in the Activity model.
In other words, based on the selections of a ManyToManyField in the parent field, offer that sub-selection to the child field, or, if John, Jim, Jordan and Jesse worked on a Job, choose from only those names to describe work on an Activity, within and attributed to that Job.
BTW, here's my naive attempt in middleware:
# threadlocals middleware
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_locals = local()
def get_current_user():
return getattr(_thread_locals, 'user', None)
def get_current_job():
return getattr(_thread_locals, 'job', None)
class ThreadLocals(object):
"""Middleware that gets various objects from the
request object and saves them in thread local storage."""
def process_request(self, request):
_thread_locals.user = getattr(request, 'user', None)
_thread_locals.job = getattr(request.POST["job"], 'job', None)
and the Activity model:
operators = modes.ManyToManyField(User, limit_choices_to=dict(Q(User.objects.filter(job==threadlocals.get_current_job)))
Thank you.