質問

すべてのドキュメントに行き、IRCチャンネルにも行きました(BTWは素晴らしいコミュニティです)。彼らは、「現在のユーザー」がいるフィールドではモデルを作成して選択肢を制限することはできないと教えてくれました外部キー。 例でこれを説明しようと思います:

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 の送信。

役に立ちましたか?

解決

このモデルを編集する current ユーザーを取得する場合は、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

他のヒント

モデル自体は現在のユーザーについては何も知りませんが、モデルオブジェクトを操作するフォームのビューでこのユーザーを指定できます(および必要なフィールドの choices をリセットします)。

管理サイトでこれが必要な場合- django-granular-permissions とともに raw_id_admin を試すことができます( http://code.google.com/p/django-granular-permissions/ ですが、すぐには動作しませんでした私のジャンゴですが、1.0には十分新鮮なようです...)。

最後に、adminでselectboxが非常に必要な場合は、 django.contrib.admin 自体をハックする必要があります。

現在のユーザーに対する選択肢のこの制限は、静的なモデル定義ではなく、リクエストサイクルで動的に実行する必要がある一種の検証です。

つまり、このモデルのインスタンスを作成する時点でビューになり、その時点で現在のユーザーにアクセスできるようになり、選択を制限できます。

その後、request.userを渡すカスタムModelFormが必要になります。次の例を参照してください。 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})

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

templates / 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 %}

あなたが何をしたいのかを完全に理解しているかどうかはわかりませんが、カスタムマネージャー。特に、現在のユーザーに制限のあるモデルを定義しようとせず、現在のユーザーに一致するオブジェクトのみを返すマネージャーを作成します。

うーん、私はあなたの質問を完全には理解していません。しかし、モデルを宣言するときにそれができない場合は、「送信」するオブジェクトのクラスのメソッドをオーバーライドすることで同じことを達成できます。ユーザーオブジェクト、おそらくコンストラクターから始めます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top