class Change(forms.Form): price = forms.DecimalField(required=True) discount = forms.IntegerField(required=True) description = forms.CharField(required=True) short_description = forms.CharField(required=True) is_active = forms.BooleanField(required=True) update = forms.DateField(widget=forms.SelectDateWidget())
def __init__(self, *args, **kwargs): a = kwargs.pop('a') super(Feedback_Ans_Form, self).__init__(*args, **kwargs) for i in a: print('answer' + str(i)) self.fields['answer' + str(i)] = forms.IntegerField(required=False)
class DeviceProfileForm(forms.ModelForm): owner = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.HiddenInput(), label='เจ้าของ ') device_id = forms.IntegerField( widget=forms.TextInput(attrs={'class': 'form-control'}), label='รหัสระจำตัวอุปกรณ์ ') device_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), label='ชื่ออุปกรณ์ ') openTime = forms.DateTimeField( widget=forms.DateTimeInput(attrs={'class': 'form-control'}), initial=(timezone.make_aware(datetime.datetime.now(), timezone.get_default_timezone())), label='เวลาเปิดอุปกรณ์ ', required=False) closeTime = forms.DateTimeField( widget=forms.DateTimeInput(attrs={'class': 'form-control'}), initial=(timezone.make_aware(datetime.datetime.now(), timezone.get_default_timezone())), label='เวลาปิดอุปกรณ์ ', required=False) class Meta: model = DeviceProfile fields = ('owner', 'device_id', 'device_name', 'openTime', 'closeTime')
def __init__(self, *args, **kwargs): pack = kwargs.pop('pack') super(ResultForm, self).__init__(*args, **kwargs) for i, q in pack: print('obtained_marks' + str(i) + str(q)) self.fields['obtained_marks' + str(i) + str(q)] = forms.IntegerField(required=False)
class Add(forms.Form): Username = forms.CharField(label='Your name', max_length=100,initial=" ") Password=forms.CharField(widget=forms.PasswordInput,label="Password",initial=" ") Email = forms.EmailField(label="Email Id:", initial="",) age=forms.IntegerField(label="Your age") Description=forms.CharField(label="Describe Yourself",widget=forms.Textarea) Profile_Picture = forms.FileField(label="Your Profile Picture:")
class ProductCategoryAdminUpdateForm(ModelForm): discount = forms.IntegerField(label='скидка', required=False, min_value=0, max_value=90, initial=0) class Meta: model = ProductCategory # fields = '__all__' exclude = () def __init__(self, *args, **kwargs): super(ProductCategoryAdminUpdateForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' field.help_text = ''
class Add(forms.Form): Username = forms.CharField(label='Your name', max_length=100, initial=" ") Password = forms.CharField(widget=forms.PasswordInput, label="Password", initial=" ") Email = forms.EmailField( label="Email Id:", initial="", ) age = forms.IntegerField(label="Your age") Description = forms.CharField(label="Describe Yourself", widget=forms.Textarea) OPTIONS = (("Java", "Java"), ("C++", "C++"), ("C", "C"), ("Python", "Python"), ("JavaScript", "JavaScript"), ("Ruby", "Ruby")) Languages = forms.MultipleChoiceField( required=True, widget=forms.CheckboxSelectMultiple, choices=OPTIONS, ) Profile_Picture = forms.FileField(label="Your Profile Picture:")
class SimpleFormTestCase(TestCase): rate = forms.IntegerField() def setUp(self) -> None: self.user = User.objects.create(username='******', email='*****@*****.**') self.movie = Movie.objects.create(title='wonder woman', duration=100, original_language='EN', country='USA') self.form = SimpleForm(user=self.user, data={ 'rate': 1, 'movie': self.movie.id, 'user': self.user }) def test_simple_form_should_return_data_if_any_movierate_exist_for_user_and_movie( self): self.form.is_valid() data = self.form.clean() self.assertEqual(data, {'rate': 1, 'movie': self.movie.id})
class TeacherInformationForm(forms.Form): fullname = forms.CharField(max_length=64, required=True) options = [('Masters', 'Masters'), ('Graduation', 'Graduation'), ('UnderGraduate', 'Under Graduate')] qualification = forms.ChoiceField(widget=forms.RadioSelect(), choices=options, required=True) university = forms.CharField(max_length=32, required=True) phonenumber = forms.CharField(max_length=12, required=True) country = forms.CharField(max_length=32, required=True) experience = forms.IntegerField() def clean_experience(self): if (self.cleaned_data['experience'] <= 0): raise forms.ValidationError("Experience should be greater than 0") else: return self.cleaned_data['experience'] def clean_phonenumber(self): if (self.cleaned_data['phonenumber'].__len__() < 10): raise forms.ValidationError("Invalid Phone Number") else: return self.cleaned_data['phonenumber']
class ResultFacultyForm(forms.Form): program = forms.CharField(max_length=10) semester = forms.ChoiceField(choices=[(tag.name, tag.value) for tag in Semester]) year = forms.IntegerField()
class ComentForm(forms.Form): id_recipe = forms.IntegerField() message = forms.CharField()
class ScoopWizardForm(forms.ModelForm, LinkForm): form_name = "create_scoop" scope_prefix = 'innerscope' legend = _("scoop details") product_name = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Write a name...' })) product_code = forms.IntegerField(widget=forms.NumberInput( attrs={ 'class': 'form-control', 'placeholder': 'enter code...' })) time_duration = forms.TimeField(widget=forms.TimeInput( attrs={ 'class': 'form-control', 'placeholder': 'enter time...' })) caption = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Write a caption...' })) description = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Write a description...' })) manufacturer = forms.ModelChoiceField( required=False, queryset=Manufacturer.objects.all(), label='', help_text=_("Top seller or Top rated"), ) class Meta: model = Product fields = ( 'product_name', 'slug', 'caption', 'description', 'product_code', 'manufacturer', 'unit_price', 'active', 'images', ) def __init__(self, *args, **kwargs): user = kwargs.pop('user', '') super(ScoopWizardForm, self).__init__(*args, **kwargs) self.fields['user_defined_code'] = forms.ModelChoiceField( queryset=Product.objects.filter(manufacturer=Manufacturer))
class SurfacePublishForm(forms.Form): """Form for publishing surfaces.""" license = forms.ChoiceField(widget=forms.RadioSelect, choices=Surface.LICENSE_CHOICES, required=True) agreed = forms.BooleanField( widget=forms.CheckboxInput, required=True, label= "I understand the implications of publishing this surface and I agree.", help_text= """Please read the implications of publishing listed above and check.""" ) copyright_hold = forms.BooleanField( widget=forms.CheckboxInput, required=True, label= "I hold copyright of this data or have been authorized by the copyright holders.", help_text="""Please make sure you're not publishing data """ """from others without their authorization.""") authors = forms.CharField(max_length=MAX_LEN_AUTHORS_FIELD, required=False) # we be filled in clean() method num_author_fields = forms.IntegerField(required=True) helper = FormHelper() helper.form_method = 'POST' error_text_inline = False helper.attrs = { "onsubmit": "on_submit()" } # call JS function for disabling button # this prevents multiple submissions by clicking several times fast helper.layout = Layout( Div(HTML('<h2 class="alert-heading">Please enter the authors</h2>'), Field('authors', template="manager/multi_author_field.html"), css_class="alert alert-primary"), Div(HTML('<h2 class="alert-heading">Please choose a license</h2>'), Field('license', template="manager/license_radioselect.html"), css_class="alert alert-primary"), Div(HTML('<h2 class="alert-heading">Final checks</h2>'), Field('agreed'), Field('copyright_hold'), FormActions( Submit('save', 'Yes, publish this surface', css_class='btn-success'), HTML(""" <a href="{% url 'manager:surface-detail' surface.pk %}" class="btn btn-default" id="cancel-btn">Cancel</a> """), ), ASTERISK_HELP_HTML, css_class="alert alert-primary"), ) def __init__(self, *args, **kwargs): num_author_fields = kwargs.pop('num_author_fields', 1) super().__init__(*args, **kwargs) for i in range(num_author_fields): self.fields[f'author_{i}'] = forms.CharField( required=False, label=f"{i + 1}. Author") def clean(self): cleaned_data = super().clean() authors = [] for i in range(self.cleaned_data.get('num_author_fields')): field_name = f'author_{i}' author = self.cleaned_data.get(field_name) if author: author = author.strip() if author in authors: raise forms.ValidationError( "Author '%(author)s' is already in the list.", code='duplicate_author', params={'author': author}) elif len(author) > 0: authors.append(author) if len(authors) == 0: raise forms.ValidationError("At least one author must be given.") authors_string = ", ".join(authors) if len(authors_string) > MAX_LEN_AUTHORS_FIELD: msg = """Representation of authors is too long, at maximum %(max_len)s characters are allowed.""" raise forms.ValidationError( msg, code='authors_too_long', params=dict(max_len=MAX_LEN_AUTHORS_FIELD)) cleaned_data['authors'] = bleach.clean( authors_string) # prevent XSS attacks return cleaned_data