class PostingForm(ModelForm): #사용자가 업로드할 파일/이미지를 입력받는 공간 생성 #forms.ImageField : 사용자가 이미지를 선택할 수 있는 입력공간 #required : forms.xxField의 공용 매개변수 #required : 사용자가 꼭 입력하지 않아도 되는 설정을 하는 매개변수 #ClearableFileInput : <input type='file'>형태의 입력공간에 파일 관련 추가설정을 할 수 있는 위젯 #multiple : True -> 하나의 입력공간에 여러개의 파일을 선택할 수 있도록 허용 images = ImageField(required=False, widget=ClearableFileInput(attrs={'multiple': True})) files = FileField(required=False, widget=ClearableFileInput(attrs={'multiple': True})) class Meta: model = Post fields = ['category', 'title', 'content']
class Meta: model = SiteUser fields = ["first_name", "last_name", "location", "avatar", "roles"] widgets = { "first_name": forms.TextInput( attrs={ 'class': 'form-control', "placeholder": "First name (maximum of 20 characters)" }), "last_name": forms.TextInput( attrs={ 'class': 'form-control', "placeholder": "Last name (maximum of 20 characters)" }), "location": forms.TextInput( attrs={ 'class': 'form-control', "placeholder": "Location (maximum of 50 characters)" }), "roles": AddAnotherWidgetWrapper( forms.SelectMultiple(attrs={'class': 'form-control'}), reverse_lazy('siteuser:role_create')), 'avatar': ClearableFileInput( attrs={ 'class': 'form-control', 'accept': '.png, .PNG, .jpg, .JPG, .jpeg, .JPG' }), }
def file_form_field(form_input): fn_name = 'file_input_change()' attrs = {'class': 'js-file-field-input', 'onchange': fn_name} return dict(field=form_input.as_widget(widget=ClearableFileInput(), attrs=attrs), context=form_input.field.widget.get_context(name=form_input.name, value=form_input.value, attrs=attrs), value=form_input.value, label=form_input.label, input_id=form_input.id_for_label, errors=form_input.errors, fn_name=fn_name)
class Meta: model = SiteUser fields = ["first_name", "last_name", "location", "avatar"] widgets = { "first_name": forms.TextInput( attrs={ 'class': 'form-control', "placeholder": "First name (maximum of 20 characters)" }), "last_name": forms.TextInput( attrs={ 'class': 'form-control', "placeholder": "Last name (maximum of 20 characters)" }), "location": forms.TextInput( attrs={ 'class': 'form-control', "placeholder": "Location (maximum of 50 characters)" }), 'avatar': ClearableFileInput( attrs={ 'class': 'form-control', 'accept': '.png, .PNG, .jpg, .JPG, .jpeg, .JPG' }), }
class Meta: model = Shelter fields = [ 'name', 'square_logo', 'legal_name', 'is_published', 'region', 'address', 'email', 'phone', 'website', 'facebook', 'instagram', ] widgets = { 'square_logo': ClearableFileInput( attrs={ 'class': 'photo', 'data-show-remove': 'false', 'data-provide': "dropify", }), } help_texts = { 'is_published': "", } labels = { 'is_published': "Rodyti prieglaudą ir jos gyvūnus GetPet'e", }
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs): """Get form field instances.""" if self.data.allowed_extensions: attrs = {'accept': self.data.allowed_extensions.replace(' ', '')} else: attrs = {} field_kwargs = { 'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, 'required': self.data.required, 'widget': ClearableFileInput(attrs=attrs), } if self.data.max_length is not None: field_kwargs['max_length'] = self.data.max_length if self.data.allowed_extensions: field_kwargs['allowed_extensions'] = self.data.allowed_extensions return [(self.data.name, FileField, field_kwargs)]
class CompanySignupForm(forms.Form): name = forms.CharField( label=_('Company Name'), widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Name', 'name': 'name' }), max_length=120) logo = forms.ImageField( label=_('Company Logo'), widget=ClearableFileInput(attrs={ 'class': 'form-control', 'style': 'padding-top:30px;', 'name': 'logo' }), required=False) website = forms.URLField( widget=forms.URLInput(attrs={ 'name': 'website', 'placeholder': 'http://www.example.com' }), max_length=150, required=False) bio = forms.CharField( label=_('About'), widget=forms.Textarea(attrs={ 'placeholder': 'Tell us about your company.', 'name': 'bio' }), max_length=500, required=False)
class Meta: model = PostImages exclude = "__all__" fields = ('post_imgs', ) widgets = { 'post_imgs': ClearableFileInput(attrs={'multiple': True}), }
class Meta: model = User fields = ['first_name', 'last_name', 'city', 'sex', 'bdate', 'phone', 'avatar'] widgets = { 'bdate': SelectDateWidget(years=list(range(1945, 2017))), 'avatar': ClearableFileInput() }
def test_render_without_value(self): """ If value not passed, use super widget. """ widget = widgets.ImageClearableFileInput() base_widget = ClearableFileInput() html = widget.render('photo', None) base_html = base_widget.render('photo', None) self.assertEqual(base_html, html)
class Meta: model = Uploads fields = ['image'] widgets = { 'image': ClearableFileInput(attrs={ 'multiple': True }), 'type': 'jpg/jpeg' }
def is_fileupload(field): ''' Tests if a field element is a file upload, as it needs to be handled slightly different :param field: a form field :return: boolen ''' return field.field.widget.__class__.__name__ == ClearableFileInput( ).__class__.__name__
class CompanySettingsForm(forms.ModelForm): """ A form used for companies to update their account information. """ name = forms.CharField(label=_('Company Name *'), widget=forms.TextInput(), max_length=120) username = forms.SlugField(label=_('Company Username *'), widget=forms.TextInput(), max_length=120) logo = forms.ImageField( widget=ClearableFileInput(attrs={'class': 'form-control'}), help_text='Max height is 150px', required=False) website = forms.URLField(label=_('Website'), widget=forms.URLInput(), max_length=150, required=False) bio = forms.CharField( label=_('About'), widget=forms.Textarea( attrs={ 'style': 'height: 7em;', 'placeholder': 'Tell us a little about your company' }), max_length=500, required=False) class Meta: model = Company fields = ( 'name', 'username', 'logo', 'website', 'bio', ) def __init__(self, *args, **kwargs): self.company = kwargs.pop('company') super(CompanySettingsForm, self).__init__(*args, **kwargs) def clean_username(self): """ Verify that the new username is not already taken. """ _username = self.cleaned_data['username'].lower() if Company.objects.filter( Q(username__iexact=_username) & ~Q(pk=self.company.pk)).exists(): raise forms.ValidationError( _('This username is already taken. ' 'Please try a different one.')) return _username
class PostingForm(ModelForm): #사용자가 업로드할 파일/이미지를 입력받는 공간 생성 #import시 주의 사항 forms에 있는 ImageField import할것! #forms.ImageField : 사용자가 이미지를 선택할 수 잇는 입력공간 #required : formsXXField의 공용 매개 변수로 사용자가 꼭 입력하지 않아도 되는 설정을 하는 매개변수 #여러개를 동시에 입력할 수 있게 하려면 위젯을 달아주면 된다. #ClearableFileInput : <input type ='file' 형태의 입력공간에 # 파일관련 추가설정을 할 수 있는 위젯 #multiple : True -> 하나의 입력공간에 여러개의 파일을 선택할 수 있도록 허용 images = ImageField(required=False, widget=ClearableFileInput(attrs={'multiple': True})) #forms.ImageField()로 해도 된다. #더블클릭해서 ClearableFileInput import #form class에 있는 FileField import files = FileField(required=False, widget=ClearableFileInput(attrs={'multiple': True})) class Meta: model = Post fields = ['category', 'title', 'content'] #사용자에게 입력 받을 것들
class Meta: model = Score fields = ('notation', 'part', 'media_file') widgets = { 'part' : AddAnotherWidgetWrapper( forms.Select(attrs={'class' : 'form-control'}), reverse_lazy('song-media:new_part')), 'notation' : AddAnotherWidgetWrapper( forms.Select(attrs={'class' : 'form-control'}), reverse_lazy('song-media:new_notation')), 'media_file' : ClearableFileInput(attrs={'class' : 'form-control', 'accept' : '.pdf'}), }
class Meta: model = Midi fields = ('part', 'description', 'media_file') widgets = { 'part' : AddAnotherWidgetWrapper( forms.Select(attrs={'class' : 'form-control'}), reverse_lazy('song-media:new_part')), 'media_file' : ClearableFileInput(attrs={'class' : 'form-control', 'accept' : '.mp3, .mid, .midi'}), 'description' : forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Enter a short description (optional)'}), }
def get_form_field_instances(self, request=None, form_entry=None, form_element_entries=None, **kwargs): """Get form field instances.""" field_kwargs = { 'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, 'required': self.data.required, 'widget': ClearableFileInput(attrs={}), } if self.data.max_length: field_kwargs['max_length'] = self.data.max_length return [(self.data.name, FileField, field_kwargs)]
class CompanyBasicsChangeForm(forms.ModelForm): company_name = forms.CharField(widget=forms.TextInput(), max_length=120, required=True, label='Company name') company_logo = forms.ImageField( required=False, widget=ClearableFileInput(attrs={'class': 'form-control'})) description = forms.CharField( required=False, max_length=200, label='Company slogan or description', widget=forms.Textarea(attrs={"style": "height: 5em;"})) company_website = forms.CharField( required=False, max_length=90, label="Website", widget=forms.TextInput(attrs={'placeholder': 'www.company.com'})) twitter = forms.CharField( required=False, max_length=80, widget=forms.TextInput(attrs={'placeholder': 'username'})) instagram = forms.CharField( required=False, max_length=80, widget=forms.TextInput(attrs={'placeholder': 'username'})) class Meta: model = Advertiser fields = ( 'company_name', 'company_logo', 'description', 'company_website', 'twitter', 'instagram', ) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(CompanyBasicsChangeForm, self).__init__(*args, **kwargs) def clean_company_name(self): company_name = self.cleaned_data['company_name'] if Advertiser.objects.filter( Q(company_name=company_name) & ~Q(id=self.user.id)).exists(): raise forms.ValidationError("That company name is already taken. " "Please try a different one.") return company_name
def get_form_field_instances(self): """ Get form field instances. """ kwargs = { 'label': self.data.label, 'help_text': self.data.help_text, 'initial': self.data.initial, 'required': self.data.required, 'widget': ClearableFileInput(attrs={}), } if self.data.max_length: kwargs['max_length'] = self.data.max_length return [(self.data.name, FileField, kwargs)]
def render(self, name, value, attrs={}): value = value attrs.update(self.attrs) _template = '%(image_tag)s %(fileinput)s<br/><label></label><label class="%(label_class)s">%(checkbox_input)s%(label_text)s</label>' # prepare file input css class label_class = attrs.pop('label_class', '') fileinput_attrs = {} fileinput_attrs.update(attrs) fileinput_attrs['class'] = '%s %s' % (attrs.pop('input_class'), attrs.get('class', '')) if value: fileinput = ClearableFileInput().render(name, value, fileinput_attrs) checkbox_input = CheckboxInput().render('%s_remove' % name, False, attrs={'class': ''}) content = _template % { 'image_tag': '<img src="%s" width="50">' % value, 'fileinput': fileinput, 'checkbox_input': checkbox_input, 'label_class': label_class, 'label_text': _('Remove') } return mark_safe(content) else: return ClearableFileInput().render(name, value, attrs)
class Meta: model = Comment fields = ("text", "image") widgets = { "text": Textarea( attrs={ "placeholder": "Введите текст комментария", "class": "form-control", }), "image": ClearableFileInput(attrs={ "class": "form-control", }), }
class FileForm(forms.ModelForm): afile = forms.FileField(label='file upload', required=False, widget=ClearableFileInput(attrs={ 'class': 'low', })) tags = TagField(label='tags', required=False, widget=TagWidget(attrs={ 'class': 'form-control form-control-sm', })) class Meta: model = File exclude = ['created', 'modified', 'deleted', 'remarks', 'author']
def AutoFileInput(*args, **kwargs): """ A factory method that returns ether an instance of S3FileInput of ClearableFileInput depending on whether or not the S3 Key is set in django.config.settings. : Settings example: AWS_SECRET_ACCESS_KEY='asdf' : :return: S3FileInput, django.forms.ClearableFileInput """ if hasattr(settings, 'AWS_SECRET_ACCESS_KEY') \ and settings.AWS_SECRET_ACCESS_KEY: return S3FileInput(*args, **kwargs) else: return ClearableFileInput(*args, **kwargs)
def value_from_datadict(self, data, files, name): """ Gets file input value from each sub-fileinput. """ base_widget = ClearableFileInput() indices = (self.input_index(name, n, "-index") for n in data) clears = (self.input_index(name, n, "-clear") for n in data) uploads = (self.input_index(name, n) for n in files) nums = sorted(set(indices).union(clears).union(uploads) - set([None])) return [ base_widget.value_from_datadict(data, files, self.input_name(name, i)) for i in nums ]
class Meta: model = CandidateProfile fields = ( "first_name", "last_name", "address_line", "zip_code", "state", "email", "phone", "portfolio_website", "resume", "cover_letter", "gender", "ethnicity", "race", "health_conditions", "veteran", "update_profile", ) help_texts = { "resume": "Allowed file types: .pdf, .doc, .docx <br/> \ Max file size: 2 MB", "cover_letter": "Allowed file types: .pdf, .doc, .docx <br/> Max " "file size: 2 MB", } widgets = { "resume": ClearableFileInput( attrs={ "accept": "application/pdf, application/msword, " "application/vnd.openxmlformats-officedocument." "wordprocessingml.document" } ), "cover_letter": file_resubmit.widgets.ResubmitFileWidget( attrs={ "accept": "application/pdf, application/msword, " "application/vnd.openxmlformats-officedocument." "wordprocessingml.document" } ), }
class Meta: model = Examination fields = [ 'peopleid', 'doctorid', 'examinationcategorid', 'dateofexam', 'treatment', 'diagnosis', 'notes', 'comments', 'docfile', 'dayoff', 'dateoffstart', 'dateoffend', 'daysoffgiven' ] widgets = { # 'examinationcategorid': AddAnotherWidgetWrapper( 'examinationcategorid': AddAnotherEditSelectedWidgetWrapper( forms.Select, reverse_lazy('MedMOHApp:createexaminationcategory'), reverse_lazy('MedMOHApp:updateexaminationcategory', args=('__fk__', ))), 'dateofexam': DateWidget(attrs={'id': "id_dateof"}, bootstrap_version=3), 'dateoffstart': DateWidget(attrs={'id': "id_dateofstart"}, bootstrap_version=3), 'dateoffend': DateWidget(attrs={'id': "id_dateofend"}, bootstrap_version=3), 'docfile': ClearableFileInput(), 'diagnosis': forms.Textarea(attrs={ 'cols': 100, 'rows': 5 }), 'treatment': forms.Textarea(attrs={ 'cols': 100, 'rows': 5 }), 'notes': forms.Textarea(attrs={ 'cols': 100, 'rows': 5 }), 'comments': forms.Textarea(attrs={ 'cols': 100, 'rows': 5 }) }
def test_render_uploaded(self): """ The widget treats UploadedFile as no input. Rationale: When widget is used in ModelForm and the form (submitted with upload) is not valid, widget should discard the value (just like standard Django ClearableFileInput does). """ widget = widgets.ImageClearableFileInput() base_widget = ClearableFileInput() file_name = 'test.jpg' # storage=None to get raw content. image = self.create_image(None, file_name) upload_file = SimpleUploadedFile(file_name, image.getvalue()) html = widget.render('photo', upload_file) base_html = base_widget.render('photo', upload_file) self.assertEqual(base_html, html) self.assertNotIn(file_name, html) # Widget is empty.
class Meta: model = Post fields = ("group", "text", "image") widgets = { "group": Select(attrs={ "placeholder": "Выбор группы", "class": "form-control", }), "text": Textarea(attrs={ "placeholder": "Введите текст", "class": "form-control", }), "image": ClearableFileInput(attrs={ "class": "form-control", }), }
class EdicaoForm(forms.ModelForm): foto = forms.ImageField(widget=ClearableFileInput(attrs={'class': ''})) class Meta: model = Usuario #definindo o modelo como Usuario fields = ('foto', 'tipo', 'curso', 'nome', 'sobrenome', 'usuario', 'email' ) # selecionando os campos do modelo que serão utilizados widgets = { #estilizando os campos com css e definindo o campo senha como sendo de senha 'nome': forms.TextInput(attrs={ 'class': 'form-control', 'maxlenght': 100 }), 'sobrenome': forms.TextInput(attrs={ 'class': 'form-control', 'maxlenght': 100 }), 'email': forms.TextInput(attrs={ 'class': 'form-control', 'maxlenght': 100 }), 'usuario': forms.TextInput(attrs={ 'class': 'form-control', 'maxlenght': 40 }), 'tipo': forms.Select(attrs={ 'class': 'form-control', 'maxlenght': 20 }), #select para uma lista predefinida no model 'curso': forms.Select( attrs={ 'class': 'form-control', 'maxlenght': 50 } ), #select para selecionar o curso de outra tabela (a chave estrangeira foi definida no model) }
class ApplicantApplyForm(forms.ModelForm): resume = forms.FileField(label=_('Resume *'), widget=ClearableFileInput(attrs={ 'class': 'form-control', 'name': 'resume' }), validators=[validate_resume_ext]) email = forms.EmailField(label=_('Email *'), widget=forms.EmailInput(attrs={ 'class': 'form-control', 'name': 'email' }), max_length=120) cover_letter = forms.CharField( label=_('Cover Letter'), widget=forms.Textarea( attrs={ 'style': 'height: 12em;', 'class': 'textarea editor-cls form-control', 'name': 'cover_letter', 'placeholder': 'Leave a message for the employer' }), max_length=5000, required=False) class Meta: model = Applicant fields = ( 'resume', 'email', 'cover_letter', ) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ApplicantApplyForm, self).__init__(*args, **kwargs) def clean_email(self): """ Return the lowercase value of the email. """ return self.cleaned_data['email'].lower()