型号limit_choices_to = {'用户':用户}

时间:2008-10-01 22:14:36

标签: python django model

我去了所有的文档,我也去了IRC频道(BTW一个很棒的社区),他们告诉我,在“当前用户”所在的字段中创建模型并限制选择是不可能的。 ForeignKey的。 我将尝试用一个例子解释这个:

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()

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

非常感谢你,如果你可以帮助我或给我任何建议,我不想你写所有的应用程序,只是一个提示如何处理。我有2天的时间在脑海中,我无法弄明白:(

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

7 个答案:

答案 0 :(得分:4)

模型本身对当前用户一无所知,但您可以在视图中为该用户提供操作模型对象的表单(并在表单中重置choices以获取必要的字段)。

如果您在管理网站上需要此功能 - 您可以尝试raw_id_admin以及django-granular-permissionshttp://code.google.com/p/django-granular-permissions/但我无法快速将其设置为我的django,但它似乎很新鲜足够的1.0所以...)。

最后,如果您在管理员中非常需要一个选择框 - 那么您将需要自己攻击django.contrib.admin

答案 1 :(得分:3)

这种对当前用户的选择限制是一种需要在请求周期中动态发生的验证,而不是在静态模型定义中。

换句话说:在您创建此模型的实例时,您将处于视图中,此时您将可以访问当前用户并限制选择。

然后你只需要一个自定义的ModelForm来传递request.user,请看这里的例子: http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/

from datetime import datetime, timedelta
from django import forms
from mysite.models import Project, TimeWorked

class TimeWorkedForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)
        self.fields['project'].queryset = Project.objects.filter(user=user)

    class Meta:
        model = TimeWorked

然后在你看来:

def time_worked(request):
    form = TimeWorkedForm(request.user, request.POST or None)
    if form.is_valid():
        obj = form.save()
        # redirect somewhere
    return render_to_response('time_worked.html', {'form': form})

答案 2 :(得分:1)

答案 3 :(得分:1)

在Django 1.8.x / Python 2.7.x中使用基于类的通用视图,这是我和我的同事提出的:

在models.py中:

# ...

class Proposal(models.Model):
    # ...

    # Soft foreign key reference to customer
    customer_id = models.PositiveIntegerField()

    # ...

在forms.py中:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.forms import ModelForm, ChoiceField, Select
from django import forms
from django.forms.utils import ErrorList
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .models import Proposal
from account.models import User
from customers.models import customer



def get_customers_by_user(curUser=None):
    customerSet = None

    # Users with userType '1' or '2' are superusers; they should be able to see
    # all the customers regardless. Users with userType '3' or '4' are limited
    # users; they should only be able to see the customers associated with them
    # in the customized user admin.
    # 
    # (I know, that's probably a terrible system, but it's one that I
    # inherited, and am keeping for now.)
    if curUser and (curUser.userType in ['1', '2']):
        customerSet = customer.objects.all().order_by('company_name')
    elif curUser:
        customerSet = curUser.customers.all().order_by('company_name')
    else:
        customerSet = customer.objects.all().order_by('company_name')

    return customerSet


def get_customer_choices(customerSet):
    retVal = []

    for customer in customerSet:
        retVal.append((customer.customer_number, '%d: %s' % (customer.customer_number, customer.company_name)))

    return tuple(retVal)


class CustomerFilterTestForm(ModelForm):

    class Meta:
        model = Proposal
        fields = ['customer_id']

    def __init__(self, user=None, *args, **kwargs):
        super(CustomerFilterTestForm, self).__init__(*args, **kwargs)
        self.fields['customer_id'].widget = Select(choices=get_customer_choices(get_customers_by_user(user)))

# ...

在views.py中:

# ...

class CustomerFilterTestView(generic.UpdateView):
    model = Proposal
    form_class = CustomerFilterTestForm
    template_name = 'proposals/customer_filter_test.html'
    context_object_name = 'my_context'
    success_url = "/proposals/"

    def get_form_kwargs(self):
        kwargs = super(CustomerFilterTestView, self).get_form_kwargs()
        kwargs.update({
            'user': self.request.user,
        })
        return kwargs

在template / proposals / customer_filter_test.html中:

{% extends "base/base.html" %}

{% block title_block %}
<title>Customer Filter Test</title>
{% endblock title_block %}

{% block header_add %}
<style>
    label {
        min-width: 300px;
    }
</style>
{% endblock header_add %}

{% block content_body %}
<form action="" method="POST">
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
    <input type="submit" value="Save" class="btn btn-default" />
</form>
{% endblock content_body %}

答案 4 :(得分:0)

我不确定我是否完全理解你想要做什么,但我认为你很有可能至少部分地使用custom Manager。特别是,不要尝试定义对当前用户有限制的模型,而是创建一个只返回与当前用户匹配的对象的管理器。

答案 5 :(得分:-1)

嗯,我不完全理解你的问题。但是,如果你在声明模型时不能这样做,你可以用“发送”用户对象的对象类的重写方法来实现同样的目的,也许从构造函数开始。

答案 6 :(得分:-1)

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

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)

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

user = threadlocals.get_current_user