14

我查看了所有文档,还访问了 IRC 频道(顺便说一句,一个很棒的社区),他们告诉我不可能在“当前用户”位于 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到模型。

4

6 回答 6

6

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

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

然后你只需要一个自定义的 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})
于 2011-01-11T09:52:59.617 回答
4

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

如果您在管理站点上需要这个 - 您可以尝试raw_id_admindjango-granular-permissionshttp://code.google.com/p/django-granular-permissions/我无法快速让它在我的 django 上运行,但它似乎是新鲜的足够 1.0 所以......)。

最后,如果您非常需要管理员中的选择框 - 那么您需要django.contrib.admin自行破解。

于 2008-10-02T00:47:35.650 回答
1

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

在模型.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

在模板/提案/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 %}
于 2019-03-28T01:50:37.230 回答
0

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

于 2008-10-02T00:58:35.873 回答
-1

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

于 2008-10-01T22:24:08.960 回答
-5

如果要获取编辑此模型的当前用户,请使用 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
于 2008-10-02T10:09:01.213 回答