Note that there are some explanatory texts on larger screens.

plurals
  1. POlimit choices to foreignkey using middleware
    primarykey
    data
    text
    <p>I'm looking to do something like this:</p> <p><a href="https://stackoverflow.com/questions/160009/django-model-limitchoicestouser-user">Model limit_choices_to={&#39;user&#39;: user}</a></p> <p>with some differences.</p> <p>Some models may explain:</p> <pre><code>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) </code></pre> <p>Note: the syntax is not intended to necessarily correct, but illustrative.</p> <p>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.</p> <p>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.</p> <p>BTW, here's my naive attempt in middleware:</p> <pre><code># 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) </code></pre> <p>and the Activity model:</p> <pre><code>operators = modes.ManyToManyField(User, limit_choices_to=dict(Q(User.objects.filter(job==threadlocals.get_current_job))) </code></pre> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload