class BookmarkForm(forms.Form): a = forms.CharField(widget=forms.HiddenInput) content_type = forms.CharField(required=False, widget=forms.HiddenInput) object_pk = forms.CharField(required=False, widget=forms.HiddenInput) user = forms.IntegerField(widget=forms.HiddenInput) url = StripURLField() name = forms.CharField(max_length=1024, required=False) description = forms.CharField(required=False, widget=forms.Textarea) def clean(self): from django.conf import settings from django.db import models from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.contrib.sites.models import Site from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType cleaned_data = self.cleaned_data.copy() if cleaned_data.get('content_type'): try: m = models.get_model( *cleaned_data['content_type'].split(".", 1)) target = m._default_manager.get(pk=cleaned_data['object_pk']) app_label, model = cleaned_data['content_type'].split(".", 1) ct = ContentType.objects.get(app_label=app_label, model=model) cleaned_data['content_type'] = ct cleaned_data['object_pk'] = target.pk except ObjectDoesNotExist, error: raise ValidationError(error) cleaned_data['user'] = User.objects.get(pk=cleaned_data['user']) cleaned_data['site'] = Site.objects.get(pk=settings.SITE_ID) return cleaned_data
class BaseCaseForm(forms.Form): summary = forms.CharField(label="Summary", ) default_tester = UserField(label="Default tester", required=False) requirement = forms.CharField(label="Requirement", required=False) is_automated = forms.MultipleChoiceField( choices=AUTOMATED_CHOICES, widget=forms.CheckboxSelectMultiple(), ) is_automated_proposed = forms.BooleanField(label='Autoproposed', required=False) script = forms.CharField(label="Script", required=False) arguments = forms.CharField(label="Arguments", required=False) alias = forms.CharField(label="Alias", required=False) extra_link = StripURLField(label='Extra link', max_length=1024, required=False) # sortkey = forms.IntegerField(label = 'Sortkey', required = False) case_status = forms.ModelChoiceField(label="Case status", queryset=TestCaseStatus.objects.all(), empty_label=None, required=False) priority = forms.ModelChoiceField( label="Priority", queryset=Priority.objects.all(), empty_label=None, ) product = forms.ModelChoiceField( label="Product", queryset=Product.objects.all(), empty_label=None, ) category = forms.ModelChoiceField( label="Category", queryset=TestCaseCategory.objects.none(), empty_label=None, ) component = forms.ModelMultipleChoiceField( label="Components", queryset=Component.objects.none(), required=False, ) notes = forms.CharField(label='Notes', widget=forms.Textarea, required=False) estimated_time = DurationField(label='Estimated Time', initial='0m', required=False) setup = forms.CharField(label="Setup", widget=TinyMCE(), required=False) action = forms.CharField(label="Actions", widget=TinyMCE(), required=False) effect = forms.CharField(label="Expect results", widget=TinyMCE(), required=False) breakdown = forms.CharField(label="Breakdown", widget=TinyMCE(), required=False) tag = forms.CharField(label="Tag", required=False) def __init__(self, *args, **kwargs): if args: self.notes_val = args[0].get('notes', None) self.script_val = args[0].get('script', None) elif kwargs: self.notes_val = kwargs.get('notes', None) self.script_val = kwargs.get('script', None) else: self.notes_val = '' self.script_val = '' super(BaseCaseForm, self).__init__(*args, **kwargs) def clean_is_automated(self): data = self.cleaned_data['is_automated'] if len(data) == 2: return 2 if len(data): # FIXME: Should data always be a list? try: return int(data[0]) except ValueError: return data[0] return data def clean_script(self): if self.script_val == '': return u'' elif self.script_val: return self.cleaned_data['script'] else: return None def clean_notes(self): if self.notes_val == '': return u'' elif self.notes_val: return self.cleaned_data['notes'] else: return None # def clean_alias(self): # data = self.cleaned_data['alias'] # tc_count = TestCase.objects.filter(alias = data).count() # # if tc_count == 0: # return data # # raise forms.ValidationError('Duplicated alias exist in database.') def clean_tag(self): tags = [] if self.cleaned_data['tag']: tag_names = TestTag.string_to_list(self.cleaned_data['tag']) tags = TestTag.get_or_create_many_by_name(tag_names) return tags def populate(self, product_id=None): if product_id: self.fields['category'].queryset = TestCaseCategory.objects.filter( product__id=product_id) self.fields['component'].queryset = Component.objects.filter( product__id=product_id) else: self.fields['category'].queryset = TestCaseCategory.objects.all() self.fields['component'].queryset = Component.objects.all()
class UserProfileForm(forms.ModelForm): user = forms.CharField(widget=forms.HiddenInput) username = forms.RegexField( label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$', help_text=_( "Required. 30 characters or fewer. " "Letters, digits and @/./+/-/_ only."), error_messages={'invalid': _( "This value may contain only letters, " "numbers and @/./+/-/_ characters.")}, ) first_name = forms.CharField(max_length=128, required=False) last_name = forms.CharField(max_length=128, required=False) email = forms.EmailField(label=_("E-mail"), max_length=75) im_type_id = forms.ChoiceField(choices=IM_CHOICES) url = StripURLField(required=False) class Meta: model = UserProfile fields = '__all__' def __init__(self, *args, **kwargs): if 'url' in kwargs: kwargs['url'] = kwargs['url'].strip() super().__init__(*args, **kwargs) if 'instance' in kwargs: instance = kwargs['instance'] self.initial['username'] = instance.user.username self.initial['first_name'] = instance.user.first_name self.initial['last_name'] = instance.user.last_name self.initial['email'] = instance.user.email def clean_email(self): email = self.cleaned_data['email'] if not getattr(self.instance, 'pk'): return email if email == self.instance.user.email: return email try: u = User.objects.get(email=email) except ObjectDoesNotExist: return email if u == self.instance: return u.email raise forms.ValidationError( _("A user with that email already exists.")) def clean_user(self): if not self.instance.pk: return User.objects.get(pk=self.cleaned_data['user']) if self.instance.user.pk == int(self.cleaned_data['user']): return self.instance.user raise forms.ValidationError(_("User error.")) def clean_username(self): username = self.cleaned_data['username'] if not getattr(self.instance, 'pk'): return username if username == self.instance.user.username: return username try: u = User.objects.get(username=username) except ObjectDoesNotExist: return username if u == self.instance: return username raise forms.ValidationError( _("A user with that username already exists.")) def save(self, commit=True): can_register = False for b in get_backends(): if getattr(b, 'can_register', None): can_register = True instance = super().save(commit=commit) user = instance.user if can_register: user.username = self.cleaned_data['username'] user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return instance