模型 limit_choices_to={'user': user} [英] Model limit_choices_to={'user': user}

查看:34
本文介绍了模型 limit_choices_to={'user': user}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了所有文档,还访问了 IRC 频道(顺便说一句,一个很棒的社区),他们告诉我,在当前用户"所在的领域中,不可能创建模型并限制选择外键.我将尝试用一个例子来解释这一点:

I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:

class Project(models.Model):
  name = models.CharField(max_length=100)
  employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'})

class TimeWorked(models.Model):
  project = models.ForeignKey(Project, limit_choices_to={'user': user})
  hours = models.PositiveIntegerField()

当然该代码不起作用,因为没有用户"对象,但这是我的想法,我试图将对象用户"发送到模型以限制当前用户拥有项目的选择,我不想看到我不在的项目.

Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.

如果你能帮助我或给我任何建议,非常感谢你,我不想你写所有的应用程序,只是一个如何处理的提示.我脑子里有 2 天的时间,但我无法弄清楚:(

Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(

更新:解决方案在这里:http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/request.user 发送到模型.

UPDATE: The solution is here: http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/ sending request.user to a model.

推荐答案

如果您想获得编辑此模型的当前用户,请使用 threadlocals.Threadlocals 中间件将当前用户放入进程范围的变量中.拿这个中间件

Use threadlocals if you want to get current user that edits this model. Threadlocals middleware puts current user into process-wide variable. Take this middleware

from threading import local

_thread_locals = local()
def get_current_user():
    return getattr(getattr(_thread_locals, 'user', None),'id',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)

查看有关如何使用中间件类的文档.然后你可以在代码中的任何地方调用

Check the documentation on how to use middleware classes. Then anywhere in code you can call

user = threadlocals.get_current_user

这篇关于模型 limit_choices_to={'user': user}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆