class UserSearchMixin(forms.ModelForm): """ Add a user_search field to the form, which resolves a string query to a User object, and set the property user_attr on the model to that user. """ user_search = UserField(label='User') user_attr = 'user' selected_user = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.HiddenInput(), required=False) def __init__(self, *args, **kwargs): super(UserSearchMixin, self).__init__(*args, **kwargs) self.fields['user_search'] = UserField() def clean_user_search(self): user = self.cleaned_data.get('user_search') return user def clean(self): cleaned_data = super(UserSearchMixin, self).clean() selected_user = cleaned_data.get('selected_user') if selected_user is not None: cleaned_data['user_search'] = selected_user if cleaned_data.get('user_search') is None: raise forms.ValidationError("No such user") return cleaned_data def save(self, commit=True, force_insert=False, force_update=False): m = super(UserSearchMixin, self).save(commit=False) setattr(m, self.user_attr, self.cleaned_data['user_search']) if commit: m.save() return m
class TranslationTaskForm(forms.ModelForm): # form related field word_count = forms.IntegerField(min_value=0, required=True) size_short = forms.BooleanField(required=False) size_medium = forms.BooleanField(required=False) size_long = forms.BooleanField(required=False) # modelr related field source_language = LanguageField(required=True) target_language = LanguageField(required=True) user = UserField(required=True) class Meta: model = TranslationTask fields = ( # Model oown field 'source_language', 'target_language', 'user', 'end_at') def save(self, commit=True): new_translation_task = super().save(commit=commit) word_count = self.cleaned_data.get('word_count') # word_count to no exceed for this task item size_short = self.cleaned_data.get('size_short') size_medium = self.cleaned_data.get('size_medium') size_long = self.cleaned_data.get('size_long') source_phrases = TranslationTask \ .phrases_ready_for_translation( source_language=new_translation_task.source_language, target_language=new_translation_task.target_language ).sizes( short=size_short, medium=size_medium, long=size_long ).order_by('-word_count') # create a translation task item for each phrases phrases_word_count = 0 for p in source_phrases: new_translation_task \ .translationtaskitem_set.create(_phrases_shared_id=p.shared_id) phrases_word_count += p.word_count if phrases_word_count >= word_count: break # set the translation task total word count new_translation_task.word_count += phrases_word_count new_translation_task.save() return new_translation_task
def __init__(self, *args, **kwargs): super(UserSearchMixin, self).__init__(*args, **kwargs) self.fields['user_search'] = UserField()