import itertools import pydash as _; from django import forms from django.db.models import Q from django.forms.models import inlineformset_factory from mptt.forms import TreeNodeChoiceField _.map = _.map_; _.filter = _.filter_ from .models import ( Project, ProjectFile, Portfolio, Answer, AnswerMessage, Realty, PortfolioPhoto, Stage, ProjectWorkTypeSuggestion, BuildingClassfication ) from archilance import util from common.models import Location, LiveImageUpload from specializations.models import Specialization from users.models import 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', 'work_type', 'realty', 'specialization', ) widgets = { 'work_type': forms.Select(attrs={'class': 'selectpicker6 -project-work-type-select-field'}), } 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['building_classification'].queryset = BuildingClassfication.objects.root_nodes()[ 0].get_descendants() # self.fields['location'].queryset = Location.objects # Migrate with this enabled class CustomerProjectEditForm(forms.ModelForm): # Define a form field manually for a reverse model vield: 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', '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 CustomerProjectEditFormNew(forms.ModelForm): # Define a form field manually for a reverse model vield: 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', # 'term_type', 'text', # 'work_type', ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super().__init__(*args, **kwargs) # self.fields['realty'].queryset = self.request.user.realties.all() self.fields['text'].required = True # self.fields['specialization'].queryset = Specialization.objects.root_nodes()[0].get_descendants() # self.fields['specialization'].queryset = Specialization.objects # Migrate with this enabled # print("files = ", self.instance.files) if self.instance.pk: self.fields['files'].queryset = self.instance.files class RealtyForm(forms.ModelForm): building_classification = TreeNodeChoiceField( BuildingClassfication.objects.exclude(name='_root'), label="ll", initial='', widget=forms.Select(attrs={ 'class': 'selectpicker', 'id': 'realtyBuildingClassificationId' }), level_indicator='  ', ) class Meta: model = Realty fields = ( 'building_classification', 'construction_type', 'location', 'name', ) widgets = { 'construction_type': forms.Select(attrs={'class': 'selectpicker'}), } def __init__(self, *args, **kwargs): try: self.request = kwargs.pop('request') except KeyError: pass 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['building_classification'].queryset = BuildingClassfication.objects.root_nodes()[ 0].get_descendants() # self.fields['location'].queryset = Location.objects # Migrate with this enabled class RealtyFormNew(forms.ModelForm): class Meta: model = Realty fields = ( 'building_classification', 'construction_type', 'location', 'name', ) 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['building_classification'].queryset = BuildingClassfication.objects.root_nodes()[ # 0].get_descendants() # self.fields['location'].queryset = Location.objects # Migrate with this enabled class PortfolioFormNew(forms.ModelForm): photos = forms.ModelMultipleChoiceField( queryset=PortfolioPhoto.objects.none(), # widget=forms.CheckboxSelectMultiple, required=False, ) class Meta: model = Portfolio fields = ( 'name', 'building_classification', # Классификация здания 'specializations', # Тип работы 'description', 'photos' ) def __init__(self, *args, **kwargs): try: self.request = kwargs.pop('request') except KeyError: pass super().__init__(*args, **kwargs) self.fields['specializations'].required = True if self.instance.pk: self.fields['photos'].queryset = self.instance.photos class PortfolioForm(forms.ModelForm): building_classification = TreeNodeChoiceField( BuildingClassfication.objects.exclude(name='_root'), widget=forms.Select(attrs={'class': 'selectpicker'}), level_indicator='  ', ) 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'}), 'currency': forms.Select(attrs={'class': 'selectpicker'}), 'term_type': forms.Select(attrs={'class': 'selectpicker'}), 'work_type': forms.Select(attrs={'class': 'selectpicker -project-work-type-select-field'}), } class PortfolioEditForm(forms.ModelForm): # Define a form field manually for a reverse model vield: photos = forms.ModelMultipleChoiceField( queryset=PortfolioPhoto.objects.none(), widget=forms.CheckboxSelectMultiple, required=False, ) live_images = forms.ModelMultipleChoiceField( queryset=LiveImageUpload.objects.all(), widget=forms.CheckboxSelectMultiple, required=False, ) building_classification = TreeNodeChoiceField( BuildingClassfication.objects.exclude(name='_root'), widget=forms.Select(attrs={'class': 'selectpicker'}), level_indicator='  ', ) class Meta: model = Portfolio fields = ( 'building_classification', 'construction_type', 'specialization', 'budget', 'currency', 'description', 'name', 'term', 'term_type', 'work_type', 'worksell', ) widgets = { 'construction_type': forms.Select(attrs={'class': 'selectpicker'}), 'currency': forms.Select(attrs={'class': 'selectpicker'}), 'term_type': forms.Select(attrs={'class': 'selectpicker'}), 'work_type': forms.Select(attrs={'class': 'selectpicker -project-work-type-select-field'}), } def __init__(self, *args, **kwargs): # self.request = kwargs.pop('request') super().__init__(*args, **kwargs) self.fields['photos'].queryset = self.instance.photos.all() 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 = 'Работаем только по безопасной сделке' contractor = self.request.user members = contractor.team.contractors.all() if util.has_related(contractor, 'team') else () # portfolios = [] # portfolios.extend(contractor.portfolios.all()) # # for c in members: # portfolios.extend(c.portfolios.all()) portfolios = Portfolio.objects.filter( user__pk__in=tuple(m.pk for m in itertools.chain((contractor,), 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')) class ProjectWorkTypeSuggestionForm(forms.ModelForm): class Meta: model = ProjectWorkTypeSuggestion fields = ( 'name', 'commentary', 'email', 'username', ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super().__init__(*args, **kwargs) # for bfield in self: # attrs = bfield.field.widget.attrs # attrs['class'] = _.join(_.compact((attrs.get('class'), '-error -error-%s' % bfield.html_name)), ' ') if self.request and self.request.user.is_authenticated(): self['username'].field.initial = self.request.user.username self['email'].field.initial = self.request.user.email # import code; code.interact(local=dict(globals(), **locals()))