def test_empty_value(self): f = SlugField(required=False) self.assertEqual(f.clean(''), '') self.assertEqual(f.clean(None), '') f = SlugField(required=False, empty_value=None) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None))
class LoginForm(Form): team_token = SlugField() competition_token = SlugField() def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_action = reverse_lazy('login') self.helper.form_method = "POST" self.helper.add_input(Submit('submit', 'Login'))
class UserEditForm(UserMixin, ModelForm): username = SlugField(disabled=True) helper = FormHelper() helper.form_method = 'POST' helper.form_action = reverse_lazy("user:edit") helper.add_input(Submit('edit', 'Изменить', css_class='btn-primary'))
class GroupDescriptionUpdateForm(ModelFormSetLabelSuffix): """A custom ModelForm for updating a GroupDescription""" name = CharField( required=False, help_text= 'The name of the group. It has been set and cannot be changed.', disabled=True) slug = SlugField( required=False, help_text= 'URL-safe identifier for the group. It has been set and cannot be changed.', disabled=True) class Meta: model = GroupDescription fields = ['name', 'slug', 'description'] widgets = { 'description': Textarea( attrs={ 'cols': 80, 'rows': 20, 'wrap': 'off', 'data-allowed-tags': ','.join(DEFAULT_ALLOWED_TAGS) }), }
class ResourceUpdateForm(ModelFormSetLabelSuffix): """A custom ModelForm for updating Resources""" slug = SlugField( required=False, help_text= 'URL-safe identifier for the resource. It has been set and cannot be changed.', disabled=True) class Meta: model = Resource fields = [ 'name', 'slug', 'low_codes_threshold', 'low_codes_email', 'description', 'hidden' ] widgets = { 'description': Textarea( attrs={ 'cols': 80, 'rows': 20, 'wrap': 'off', 'data-allowed-tags': ','.join(DEFAULT_ALLOWED_TAGS) }), }
class AgreementUpdateForm(AgreementBaseForm): """A custom ModelForm for updating Departments""" slug = SlugField( required=False, help_text= 'URL-safe identifier for the agreement. It has been set and cannot be changed.', disabled=True) class Meta: model = Agreement fields = [ 'title', 'slug', 'resource', 'start', 'end', 'body', 'hidden', 'redirect_url', 'redirect_text' ] widgets = { 'body': Textarea( attrs={ 'cols': 80, 'rows': 20, 'wrap': 'off', 'data-allowed-tags': ','.join(DEFAULT_ALLOWED_TAGS) }), }
def test_slugfield_unicode_normalization(self): f = SlugField(allow_unicode=True) self.assertEqual(f.clean("a"), "a") self.assertEqual(f.clean("1"), "1") self.assertEqual(f.clean("a1"), "a1") self.assertEqual(f.clean("你好"), "你好") self.assertEqual(f.clean(" 你-好 "), "你-好") self.assertEqual(f.clean("ıçğüş"), "ıçğüş") self.assertEqual(f.clean("foo-ıç-bar"), "foo-ıç-bar")
def test_slugfield_unicode_normalization(self): f = SlugField(allow_unicode=True) self.assertEqual(f.clean('a'), 'a') self.assertEqual(f.clean('1'), '1') self.assertEqual(f.clean('a1'), 'a1') self.assertEqual(f.clean('你好'), '你好') self.assertEqual(f.clean(' 你-好 '), '你-好') self.assertEqual(f.clean('ıçğüş'), 'ıçğüş') self.assertEqual(f.clean('foo-ıç-bar'), 'foo-ıç-bar')
class CreateClassroomForm(Form): scheduler_email_1 = EmailField(required=False) scheduler_email_2 = EmailField(required=False) slug = SlugField() name = CharField() def cleaned_emails(self): return [self.cleaned_data[email_field] for email_field in \ ['scheduler_email_1', 'scheduler_email_2'] \ if self.cleaned_data[email_field]]
class AwardCategory(models.Model): uuid = UUIDField(primary_key=True) slug = SlugField() title = models.TextField() order = models.IntegerField(null=True, unique=True) def __str__(self): return "#%s - %s" % (str(self.order), self.title) class Meta: ordering = ['order']
class FacultyUpdateForm(ModelFormSetLabelSuffix): """A custom ModelForm for updating Faculties""" slug = SlugField( required=False, help_text= 'URL-safe identifier for the faculty. It has been set and cannot be changed.', disabled=True) class Meta: model = Faculty fields = ['name', 'slug']
def save(self, commit=True): slug = SlugField(required=False) # e=super().save(commit=False) #error e = super().save() category_list = self.cleaned_data.get('category', "").strip() category_list = category_list if category_list else "Uncategorized" e.categories.clear() for c in category_list.split(','): cateobj = Category.objects.get_or_create(title=c)[0] e.categories.add(cateobj) return e.save()
class LinkCreateForm(ModelForm): subpart = SlugField(required=False) class Meta: model = Link fields = ('url', 'subpart') def clean_subpart(self): subpart = self.cleaned_data.get('subpart', '') if subpart: if not Link.is_unique_subpart(subpart): raise ValidationError('URL abbreviation of your choice is already taken') return subpart
class Award(models.Model): AWARD_RANKING = ( (0, 'Winner'), (98, 'Highly Commended'), (99, 'Highly Commended'), ) uuid = UUIDField(primary_key=True) provider = models.ForeignKey('products.Provider') product = models.ForeignKey('products.MasterProduct', null=True, blank=True) slug = SlugField() ranking = models.IntegerField(choices=AWARD_RANKING) category = models.ForeignKey(AwardCategory) awarded_date = models.DateField(default=datetime.today) def __str__(self): return " ".join([ self.get_ranking_display(), self.category.title, self.provider.title ]) def image_url(self): return "img/awards/%s-%s-%s-image.png" % ( self.get_ranking_display(), self.category.title.replace( ' ', '_'), self.awarded_date) class Meta: ordering = ['ranking'] def save(self, *args, **kwargs): super(Award, self).save(*args, **kwargs) from pages.tasks import create_award_image create_award_image.apply_async(kwargs={ 'award_id': self.pk, 'year': True, 'ranking': True, 'details': False }, countdown=1)
class AllFieldTypesForm(Form): char = CharField() int_ = IntegerField() date = DateField() time = TimeField() datetime_ = DateTimeField() regex = RegexField(regex='^[a-f]{3}$') email = EmailField() file = FileField() # image = ImageField() url = URLField() bool = BooleanField() nullbool = NullBooleanField() choice = ChoiceField(choices=(('test choice', 'yay test choice'), )) multichoice = MultipleChoiceField(choices=( ('test choice', 'yay test choice'), ('test choice 2', 'yay another choice'), ('test choice 3', 'yay test choice'), )) float = FloatField() decimal = DecimalField() ip = IPAddressField() generic_ip = GenericIPAddressField() filepath = FilePathField(path=tempfile.gettempdir(), allow_files=True, allow_folders=True) slug = SlugField() typed_choice = TypedChoiceField(choices=( (1, 'test'), (2, 'test 2'), (3, 'bah'), ), coerce=int) typed_multichoice = TypedMultipleChoiceField(choices=( (1, 'test'), (2, 'test 2'), (3, 'bah'), ), coerce=int) model_choice = ModelChoiceField(queryset=get_user_model().objects.all()) model_multichoice = ModelMultipleChoiceField( queryset=get_user_model().objects.all())
def auth_register(request, error_code): username_f = SlugField(max_length=30) password_f = CharField(max_length=30, widget=PasswordInput) email_f = EmailField() username = request.POST.get('reg_name', None) password = request.POST.get('reg_pass', None) email = request.POST.get('reg_email', None) for field, value in [(username_f, username), (password_f, password), (email_f, email)]: try: field.clean(value) except ValidationError: error_code = 2 return HttpResponseRedirect(reverse('board:login_form', args=(error_code, ))) break else: if User.objects.filter(username=username).exists(): error_code = 3 return HttpResponseRedirect(reverse('board:login_form', args=(error_code, ))) else: User.objects.create_user(username=username, email=email, password=password) user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect(reverse('board:index', args=(0, 0)))
class FieldInlineForm(ModelForm): slug = SlugField(required=True) class Meta: model = Field fields = '__all__'
def test_slugfield_normalization(self): f = SlugField() self.assertEqual(f.clean(' aa-bb-cc '), 'aa-bb-cc')
class URLForm(ModelForm): def clean_target(self): """ Prevent redirect loop links """ # get the entered target link target = self.cleaned_data.get('target') return target # Custom target URL field target = URLField(required=True, label='Long URL (Required)', max_length=1000, widget=URLInput( attrs={ 'placeholder': 'https://yoursite.com/', 'class': 'urlinput form-control', })) # short -------------------------------------------------------------------- def unique_short(value): """ Check to make sure the short url has not been used """ try: # if we're able to get a URL with the same short url URL.objects.get(short__iexact=value) except URL.DoesNotExist as ex: return # then raise a ValidationError raise ValidationError('Short URL already exists.') # Custom short-url field with validators. short = SlugField( required=False, label='Short URL (Optional)', widget=TextInput(attrs={ 'class': 'urlinput form-control', }), validators=[unique_short], max_length=20, min_length=3, ) # expires ------------------------------------------------------------------ # Define some string date standards DAY = '1 Day' WEEK = '1 Week' MONTH = '1 Month' # CUSTOM = 'Custom Date' NEVER = 'Never' # Define a tuple of string date standards to be used as our date choices EXPIRATION_CHOICES = ( (DAY, DAY), (WEEK, WEEK), (MONTH, MONTH), (NEVER, NEVER), # (CUSTOM, CUSTOM), ) # Add preset expiration choices. expires = ChoiceField( required=True, label='Expiration (Required)', choices=EXPIRATION_CHOICES, initial=NEVER, widget=RadioSelect(attrs={'class': 'radios'}), ) def valid_date(value): """ Check if the selected date is a valid date """ # a valid date is one that is greater than today if value > timezone.now(): return # raise a ValidationError if the date is invalid else: raise ValidationError('Date must be after today.') def __init__(self, *args, **kwargs): """ On initialization of the form, crispy forms renders this layout """ # Grab that host info self.host = kwargs.pop('host', None) super(URLForm, self).__init__(*args, **kwargs) self.target_title = 'Paste the URL you would like to shorten:' self.short_title = 'Create a custom Go address:' self.expires_title = 'Set when you would like your Go address to expire:' self.action = '/newLink' class Meta: """ Metadata about this ModelForm """ # what model this form is for model = URL # what attributes are included fields = ['target']