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.
 
 
 
 
 
 

312 lines
10 KiB

from django import forms
from django.db.models import Q
from django.forms.models import inlineformset_factory
from mptt.forms import TreeNodeChoiceField
from pprint import pprint, pformat
import itertools
from .models import Project, ProjectFile, Portfolio, Answer, AnswerMessage, Realty, PortfolioPhoto, Stage
from archilance import util
from common.models import Location
from specializations.models import Specialization
from users.models import User, Team
class ProjectFilterForm(forms.ModelForm):
PROJECT_ORDER_CHOICES = ( # "Упорядочить по"...
('name', 'названию'),
('budget', 'цене'),
('created', 'дате размещения'),
('views', 'просмотрам'),
)
order_by = forms.ChoiceField(required=False, choices=PROJECT_ORDER_CHOICES)
last_order_by = forms.ChoiceField(required=False, choices=PROJECT_ORDER_CHOICES)
reverse_order = forms.BooleanField(required=False)
keywords = forms.CharField(required=False, max_length=255)
class Meta:
model = Project
fields = (
'cro',
'specialization',
'work_type',
)
widgets = {
'work_type': forms.Select(attrs={'class': 'selectpicker'}),
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super().__init__(*args, **kwargs)
self.fields['work_type'].choices = tuple(itertools.chain((('',''),), self.fields['work_type'].choices))
self.fields['work_type'].required = False
self.fields['work_type'].initial = ''
self.fields['specialization'].required = False
self.fields['specialization'].queryset = Specialization.objects.root_nodes()[0].get_descendants()
# self.fields['specialization'].queryset = Specialization.objects # Migrate with this enabled
class ProjectFilterRealtyForm(forms.ModelForm):
class Meta:
model = Realty
fields = (
'building_classification',
'construction_type',
'location',
)
widgets = {
'building_classification': forms.Select(attrs={'class': 'selectpicker'}),
'construction_type': forms.Select(attrs={'class': 'selectpicker'}),
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super().__init__(*args, **kwargs)
self.fields['building_classification'].empty_label = ''
self.fields['building_classification'].required = False
self.fields['construction_type'].empty_label = ''
self.fields['construction_type'].required = False
self.fields['location'].queryset = Location.objects.root_nodes()[0].get_descendants()
# self.fields['location'].queryset = Location.objects # Migrate with this enabled
class CustomerProjectEditForm(forms.ModelForm):
files = forms.ModelMultipleChoiceField(
queryset=ProjectFile.objects.none(),
widget=forms.CheckboxSelectMultiple,
required=False,
)
class Meta:
model = Project
fields = (
'budget',
'budget_by_agreement',
'cro',
'currency',
'deal_type',
'files',
'name',
'price_and_term_required',
'realty',
'specialization',
'term_type',
'text',
'work_type',
)
widgets = {
'currency': forms.Select(attrs={'class': 'selectpicker2 valul'}),
'realty': forms.Select(attrs={'class': 'selectpicker'}),
'term_type': forms.Select(attrs={'class': 'selectpicker'}),
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super().__init__(*args, **kwargs)
self.fields['realty'].empty_label = 'Создать новый'
self.fields['realty'].queryset = self.request.user.realties.all()
self.fields['budget'].required = False
self.fields['currency'].required = False
self.fields['term_type'].required = False
self.fields['specialization'].queryset = Specialization.objects.root_nodes()[0].get_descendants()
# self.fields['specialization'].queryset = Specialization.objects # Migrate with this enabled
if self.instance.pk:
self.fields['files'].queryset = self.instance.files
def clean(self):
cleaned_data = super().clean()
if not cleaned_data.get('budget_by_agreement'):
if not cleaned_data.get('budget'): raise forms.ValidationError({'budget': 'Это поле обязательно'})
if not cleaned_data.get('currency'): raise forms.ValidationError({'currency': 'Это поле обязательно'})
if not cleaned_data.get('term_type'): raise forms.ValidationError({'term_type': 'Это поле обязательно'})
return cleaned_data
class RealtyForm(forms.ModelForm):
class Meta:
model = Realty
fields = (
'building_classification',
'construction_type',
'location',
'name',
)
widgets = {
'construction_type': forms.Select(attrs={'class': 'selectpicker'}),
'building_classification': forms.Select(attrs={'class': 'selectpicker'}),
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super().__init__(*args, **kwargs)
if not self.data.get('extra_fields'):
self.fields['name'].required = False
self.fields['location'].queryset = Location.objects.root_nodes()[0].get_descendants()
# self.fields['location'].queryset = Location.objects # Migrate with this enabled
class PortfolioForm(forms.ModelForm):
duplicate = forms.BooleanField(required=False, label='Some label here')
images_ids = forms.CharField(required=True)
class Meta:
model = Portfolio
fields = '__all__'
widgets = {
'construction_type': forms.Select(attrs={'class': 'selectpicker'}),
'building_classification': forms.Select(attrs={'class': 'selectpicker'}),
'currency': forms.Select(attrs={'class': 'selectpicker'}),
'term_type': forms.Select(attrs={'class': 'selectpicker'}),
}
class ProjectAnswerForm(forms.ModelForm):
text = forms.CharField(widget=forms.Textarea)
class Meta:
model = Answer
fields = (
'budget',
'currency',
'portfolios',
'secure_deal_only',
'term',
'term_type',
)
widgets = {
'currency': forms.Select(attrs={'class': 'selectpicker'}),
'term_type': forms.Select(attrs={'class': 'selectpicker'}),
}
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
self.project = kwargs.pop('project')
self.answer_as_team = kwargs.pop('answer_as_team', None)
super().__init__(*args, **kwargs)
if self.answer_as_team:
self.fields['secure_deal_only'].label = 'Работаем только по безопасной сделке'
try: members = self.request.user.team.contractors.all()
except Team.DoesNotExist: members = ()
portfolios = Portfolio.objects.filter(user__pk__in=tuple(m.pk for m in members))
self.fields['portfolios'].queryset = portfolios
else:
self.fields['secure_deal_only'].label = 'Работаю только по безопасной сделке'
self.fields['portfolios'].queryset = self.request.user.portfolios.all()
if self.project and self.project.price_and_term_required:
self.fields['budget'].required = True
self.fields['currency'].required = True
self.fields['term'].required = True
self.fields['term_type'].required = True
def clean(self):
if self.answer_as_team:
try:
self.request.user.team
except Team.DoesNotExist:
raise forms.ValidationError('У исполнителя отсутствует команда')
return super().clean()
class ProjectAnswerMessageForm(forms.ModelForm):
class Meta:
model = AnswerMessage
fields = (
'text',
)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super().__init__(*args, **kwargs)
class StageForm(forms.ModelForm):
class Meta:
model = Stage
fields = (
# 'cost',
# 'cost_type',
# 'name',
# 'result',
# 'term',
# 'term_type',
)
PortfolioPhotoFormSet = inlineformset_factory(Portfolio, PortfolioPhoto, fields=('img',))
class CustomerProjectTrashForm(forms.Form):
pk = forms.ModelChoiceField(queryset=Project.objects.none())
def __init__(self, *args, **kwargs):
self.req = kwargs.pop('req')
super().__init__(*args, **kwargs)
self.fields['pk'].queryset = self.req.user.customer_projects.filter(state='active')
class ContractorPortfolioTrashForm(forms.Form):
pk = forms.ModelChoiceField(queryset=Portfolio.objects.none())
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super().__init__(*args, **kwargs)
self.fields['pk'].queryset = self.request.user.portfolios.all()
class CustomerProjectRestoreForm(forms.Form):
pk = forms.ModelChoiceField(queryset=Project.objects.none())
def __init__(self, *args, **kwargs):
self.req = kwargs.pop('req')
super().__init__(*args, **kwargs)
self.fields['pk'].queryset = self.req.user.customer_projects.filter(state='trashed')
class CustomerProjectDeleteForm(forms.Form):
pk = forms.ModelChoiceField(queryset=Project.objects.none())
def __init__(self, *args, **kwargs):
self.req = kwargs.pop('req')
super().__init__(*args, **kwargs)
self.fields['pk'].queryset = self.req.user.customer_projects.filter(Q(state='active') | Q(state='trashed'))
# import code; code.interact(local=dict(globals(), **locals()))