You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
3.5 KiB
65 lines
3.5 KiB
# -*- coding: utf-8 -*-
|
|
from django.forms import ModelChoiceField
|
|
import autocomplete_light
|
|
|
|
from project.commons.forms import MyBaseModelForm
|
|
from project.customer.models import BankAccount, Client
|
|
|
|
|
|
class BaseModelForm(MyBaseModelForm):
|
|
"""Базовая форма редактирования модели бух. формы.
|
|
|
|
Добавляет к классу атрибут adjust_client_fields.
|
|
Добавляет к методу __init__ обязательный атрибут user.
|
|
"""
|
|
|
|
# Список полей, у которых нужно настроить выборку контрагентов так, чтобы попадали __только__ контрагенты данного
|
|
# пользователя. Если же пользователь никак не был задан - селекты будут пустыми! Если в форме есть поле client,
|
|
# то оно настраивается автоматически.
|
|
client = ModelChoiceField(Client.objects.all(), label=u'клиент', required=True,
|
|
widget=autocomplete_light.ChoiceWidget('ACClient'))
|
|
adjust_client_fields = []
|
|
|
|
def __init__(self, user, *args, **kwargs):
|
|
super(BaseModelForm, self).__init__(*args, **kwargs)
|
|
|
|
self._user = user
|
|
# Если передали user=None, то попробовать взять user из kwargs['instance'], а потом из self.data
|
|
if not self._user:
|
|
try:
|
|
self._user = getattr(kwargs.get('instance'), 'user')
|
|
except AttributeError:
|
|
self._user = self.data.get('user', user)
|
|
|
|
f = self.fields
|
|
|
|
# Настроить атрибуты виджетов
|
|
# TODO вынести в _MySuperForm (сделать там настройку полей с datepicker-ами из словаря)
|
|
f['doc_date'].widget.attrs['class'] = 'has-datepicker'
|
|
if f.get('plat_doc_date'):
|
|
f['plat_doc_date'].widget.attrs['class'] = 'has-datepicker'
|
|
if f.get('fix_doc_date'):
|
|
f['fix_doc_date'].widget.attrs['class'] = 'has-datepicker'
|
|
|
|
# Если в форме есть поле bank_account, настроить связь с BankAccount: чтобы можно было выбрать __только__
|
|
# расчетные счета данного пользователя. Также убрать пустой вариант из селекта.
|
|
if 'bank_account' in f:
|
|
user_accounts = BankAccount.objects.get_all(self._user)
|
|
f['bank_account'].queryset = user_accounts
|
|
f['bank_account'].empty_label = None
|
|
|
|
# Если в форме есть поле client, настроить связь с Client: чтобы можно было выбрать __только__
|
|
# контрагентов данного пользователя.
|
|
if 'client' in f:
|
|
user_clients = Client.objects.filter(user=self._user)
|
|
f['client'].queryset = user_clients
|
|
|
|
# Настроить связь других полей с контрагентами.
|
|
self._adjust_clients()
|
|
|
|
def _adjust_clients(self):
|
|
#"""Настраивает перечисленные в self.adjust_client_fields поля на модель Client."""
|
|
if self.adjust_client_fields:
|
|
user_clients = Client.objects.filter(user=self._user)
|
|
for key in self.adjust_client_fields:
|
|
self.fields[key].queryset = user_clients
|
|
|