class SellerUpdateForm(SellerForm): seller_logo_image = ImageField(label='seller_logo_image', help_text='for Seller logo', required=False) seller_category_logo_image = ImageField( label='seller Category logo ', help_text='for Seller category logo', required=False)
def add_location(self, latitude, longitude, lot_type, address=None, pictures=None, description=None): """ Adds a new Location object to the database Returns the newly created Location object """ new_location = Location() new_location.latitude = latitude new_location.longitude = longitude new_location.address = address new_location.lot_type = lot_type new_location.description = description # Validate the picture to make sure it's not a malicious file try: if pictures: i = 1 for picture in pictures[:3]: setattr(new_location, "picture%i" % i, ImageField().clean(picture)) i += 1 except ValidationError as ve: e = Exception(self) e.message = '; '.join(ve.messages) raise e new_location.save() return new_location
class PhotoForm(ModelForm): image_file = ImageField() age_range = ChoiceField( choices=Photographer.AGE_RANGE_CHOICES, widget=forms.RadioSelect(), initial=0, ) gender = ChoiceField( choices=Photographer.GENDER_CHOICES, widget=forms.RadioSelect(), initial=0, ) gender_other = CharField(max_length=20, required=False) consent = BooleanField() class Meta: fields_required = [ 'taken_year', 'author_focus_keywords', 'author_reason', ] model = Photo fields = [ 'image_file', 'taken_year', 'taken_month', 'location', # TODO: split into three inputs? 'author_focus_keywords', 'author_feeling_category', 'author_feeling_keywords', 'author_reason', # 'photographer__age_range', 'age_range', # 'photographer__gender', 'gender', # 'photographer__gender_other', 'gender_other', 'consent', ] widgets = { 'location': OSMWidget(dict( default_lon=-0.13, default_lat=51.5, )), 'author_feeling_category': forms.RadioSelect(), # 'taken_month': forms.RadioSelect() } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) fields_required = getattr(self.Meta, 'fields_required', []) for key in fields_required: self.fields[key].required = True
class DomainGlobalSettingsForm(forms.Form): default_timezone = TimeZoneChoiceField( label=ugettext_noop("Default Timezone"), initial="UTC") logo = ImageField( label=_("Custom Logo"), required=False, help_text=_("Upload a custom image to display instead of the " "CommCare HQ logo. It will be automatically resized to " "a height of 32 pixels.")) delete_logo = BooleanField( label=_("Delete Logo"), required=False, help_text=_("Delete your custom logo and use the standard one.")) def __init__(self, *args, **kwargs): self.can_use_custom_logo = kwargs.pop('can_use_custom_logo', False) super(DomainGlobalSettingsForm, self).__init__(*args, **kwargs) if not self.can_use_custom_logo: del self.fields['logo'] del self.fields['delete_logo'] def clean_default_timezone(self): data = self.cleaned_data['default_timezone'] timezone_field = TimeZoneField() timezone_field.run_validators(data) return smart_str(data) def save(self, request, domain): try: if self.can_use_custom_logo: logo = self.cleaned_data['logo'] if logo: input_image = Image.open(io.BytesIO(logo.read())) input_image.load() input_image.thumbnail(LOGO_SIZE) # had issues trying to use a BytesIO instead tmpfilename = "/tmp/%s_%s" % (uuid.uuid4(), logo.name) input_image.save(tmpfilename, 'PNG') with open(tmpfilename) as tmpfile: domain.put_attachment(tmpfile, name=LOGO_ATTACHMENT) elif self.cleaned_data['delete_logo']: domain.delete_attachment(LOGO_ATTACHMENT) global_tz = self.cleaned_data['default_timezone'] domain.default_timezone = global_tz users = WebUser.by_domain(domain.name) for user in users: dm = user.get_domain_membership(domain.name) if not dm.override_global_tz: dm.timezone = global_tz user.save() domain.save() return True except Exception: return False
class UpdateProfileForm(ModelForm): input_field_class = 'bg-gray-700 bg-opacity-0 ml-2 pb-1 outline-none text-white placeholder-gray-600' profile_image = ImageField(label='', widget=FileInput(attrs={ 'class': 'hidden', 'accept': '.jpg,.png' })) background_image = ImageField(widget=FileInput(attrs={ 'class': 'hidden', 'accept': '.jpg,.png' })) bio = CharField(required=False, widget=Textarea( attrs={ 'class': input_field_class + ' resize-none', 'placeholder': 'Add your bio', 'rows': 3 })) location = CharField( required=False, widget=TextInput(attrs={ 'class': input_field_class, 'placeholder': 'Add your location' })) website = URLField( required=False, max_length=100, widget=URLInput(attrs={ 'class': input_field_class, 'placeholder': 'Add your website' })) class Meta: model = Profile fields = [ 'profile_image', 'background_image', 'bio', 'location', 'website' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
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']
def update_location(self, id, lot_type=None, address=None, pictures=None, description=None): """ Updates an existing Location object to the database Returns the newly created Location object """ updated = False locations = Location.objects.filter(id=id) if locations and len(locations) == 1: location = locations[0] else: e = Exception(self) e.message = "Location with that ID not found" raise e if lot_type: location.lot_type = lot_type updated = True if address: location.address = address updated = True if description: location.description = description updated = True try: if pictures: i = 1 for picture in pictures[:3]: setattr(location, "picture%i" % i, ImageField.clean(picture)) i += 1 updated = True except ValidationError as ve: e = Exception(self) e.message = '; '.join(ve.messages) raise e if updated: location.save() return location
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 UploadImage(Form): """Form for uploading image.""" url_upload = URLField(required=False) file_upload = ImageField(required=False) def clean(self): if bool(self.data.get('url_upload')) == bool( self.files.get('file_upload')): raise ValidationError("Выберите что-то одно.") cleaned_data = super().clean() if url_upload := cleaned_data.get('url_upload'): try: response = request.urlopen(url_upload) content_type = response.getheader('Content-Type') if not content_type or not content_type.startswith('image'): raise ValidationError("Ссылка не похожа на изображение.") content_length = int(response.getheader('Content-Length', 0)) if content_length > settings.FILE_UPLOAD_MAX_SIZE: raise ValidationError("Слишком большой файл.") image_bytes = BytesIO() while chunk := response.read(1024 * 1024): image_bytes.write(chunk) if image_bytes.tell() > settings.FILE_UPLOAD_MAX_SIZE: raise ValidationError("Слишком большой файл.") except (HTTPError, URLError) as e: raise ValidationError("Ошибка скачивания файла.") from e image_name = parse.urlparse(response.url).path.split('/')[-1] if '.' not in image_name: image_name += '.' + content_type.removeprefix('image/') self.files['url_upload'] = ImageFile(image_bytes, name=image_name) return cleaned_data
class BaseBannerForm(ModelForm): default_banner_fields = ['link', 'applink', 'position', 'status', 'img_file'] # Never modify a base class !! # sitebanner use active_status instead of status sitebanner_default_fields = ['link', 'applink', 'position', 'img_file'] img_file = ImageField(label='upload banner image') def __init__(self, *args, **kwargs): super(BaseBannerForm, self).__init__(*args, **kwargs) for key, field in self.fields.items(): field.widget.attrs.update({'class': 'form-control'}) class Meta: abstract = True def handle_images(self): image_field_pair = {'img_file': 'image'} for form_field_name, model_field_name in image_field_pair.items(): self.handle_image_field(form_field_name, model_field_name) def handle_image_field(self, form_field_name, model_field_name): if not self.cleaned_data.get(form_field_name): return _image_path = self._handle_post_image(form_field_name) setattr(self.instance, model_field_name, _image_path) def _handle_post_image(self, form_field_name): _image = HandleImage(image_file=self.cleaned_data.get(form_field_name)) _image_path = _image.icon_save() return _image_path def save(self, commit=True, *args, **kwargs): self.handle_images() return super(BaseBannerForm, self).save(commit=True, *args, **kwargs)
class BaseBannerCreateForm(BaseBannerForm): img_file = ImageField(label='upload banner image', required=True)
class TinyMCEUpload(Form): file = ImageField()
class PostCreateView(forms.ModelForm): phone_regex = RegexValidator( regex=r'^\+?1?\d{10,15}$', message= "Phone number must be entered in the format: '999999999'. Up to 15 digits " "allowed.") animal_child = forms.IntegerField( widget=forms.NumberInput(attrs={'class': 'form-control'}), label='Child', required=False, initial=1) animal_age = forms.IntegerField( widget=forms.NumberInput(attrs={'class': 'form-control'}), label='Age', required=False, initial=8) animal_weight = forms.IntegerField( widget=forms.NumberInput(attrs={'class': 'form-control'}), label='Weight(KG)', required=False, initial=250) animal_info = forms.CharField( widget=forms.Textarea(attrs={ 'class': 'form-control', 'id': 'animal_info', "rows": 2, "cols": 100 }), label='Information', required=False) animal_price = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), label='Price', required=False, initial=25000) front_image = ImageField(required=False, label="Front", widget=forms.FileInput(attrs={ 'class': 'form-control', 'id': 'id_front_image' })) back_image = ImageField(required=False, label="Back", widget=forms.FileInput) left_image = ImageField(required=False, label="Left", widget=forms.FileInput) right_image = ImageField(required=False, label="Right", widget=forms.FileInput) user_name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'id': 'user_name' }), label='Name', required=False) user_contact = forms.CharField( widget=forms.TextInput(attrs={ 'class': 'form-control', 'id': 'user_contact' }), max_length=15, label='Enter Mobile No', required=False) user_village = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=15, label='Village', required=False) user_address = forms.CharField( widget=forms.Textarea(attrs={ 'class': 'form-control', 'id': 'user_address', "rows": 2, "cols": 100 }), label='Information', required=False) user_teh = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), label='Tehsil (Block)', required=False) user_dist = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), label='District', required=False) user_late = forms.CharField( widget=forms.HiddenInput(attrs={'class': 'form-control'}), label='user late', required=False, initial=22.72473954) user_long = forms.CharField( widget=forms.HiddenInput(attrs={'class': 'form-control'}), label='user long', required=False, initial=75.88166449) CHOICES = [('1', 'Black White'), ('2', 'White'), ('3', 'Black'), ('4', 'Light Black'), ('5', 'Brown White'), ('6', 'Brown')] animal_color = forms.ChoiceField( widget=forms.RadioSelect(attrs={'class': 'radio_field'}), choices=CHOICES, initial=3) milk_list = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ] animal_group = forms.ChoiceField( widget=forms.Select(attrs={ 'class': 'form-control animal_group', 'id': 'animal_group' }), choices=[(group.id, str(group.en_name)) for group in load_group()], required=False, initial='1') animal_breed = forms.ChoiceField( widget=forms.Select(attrs={ 'class': 'form-control animal_grouptype', 'id': 'animal_grouptype' }), choices=[(type.id, str(type.en_type)) for type in load_all_type()], required=False) animal_milk = forms.ChoiceField( widget=forms.Select(attrs={ 'class': 'form-control milkquantity', 'id': 'milkquantity' }), choices=[(milk, str(milk)) for milk in milk_list], required=False, initial='0') user_state_id = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), choices=[(state.id, str(state.name)) for state in load_state()], required=False, initial='4') user_country_id = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), choices=[(country.id, str(country.name)) for country in load_country()], required=False, initial='1') class Meta: model = Post fields = [ 'animal_group', 'animal_breed', 'animal_milk', 'animal_color', 'animal_child', 'animal_age', 'animal_weight', 'animal_info', 'animal_price', 'front_image', 'back_image', 'left_image', 'right_image', 'user_name', 'user_contact', 'user_late', 'user_long', 'user_village', 'user_address', 'user_dist', 'user_teh', 'user_state_id', 'user_country_id' ]
def __init__(self, *args, **kwargs): max_length = kwargs.pop('max_length', None) del max_length fields = (ImageField(label='Image'), CharField(required=False)) super(VersatileImagePPOIClickField, self).__init__(tuple(fields), *args, **kwargs)
class BaseBannerUpdateForm(BaseBannerForm): img_file = ImageField(label='upload banner image', required=False)
class CustomerCreateForm(UserCreationForm): birth_date = DateField(initial=set_min_age_for_datefield, widget=DateInput(attrs={'type': 'date'})) photo = ImageField() class Meta: model = User fields = ['username', 'password1', 'password2', 'first_name', 'last_name', 'email', 'birth_date', 'photo']
def setUp(self): self.gallery= ImageField(first_name = 'James', last_name ='Muriuki', email ='*****@*****.**')
class SellerForm(ModelForm): # seller_user_id = IntegerField(required=False) seller_logo_image = ImageField(label='seller_logo_image', help_text='for Seller logo', required=False) seller_category_logo_image = ImageField( label='seller Category logo ', help_text='for Seller category logo', required=False) related_article_url = URLField(label='interview article address', help_text='FOR SELLER interview article', required=False) def __init__(self, *args, **kwargs): super(SellerForm, self).__init__(*args, **kwargs) # self.fields['seller_user_id'].widget.attrs.update({'class':'user-id-input form-control'}) self.fields['seller_name'].widget.attrs.update( {'class': 'form-control'}) # self.fields['logo'].widget.attrs.update({'class':'form-control'}) self.fields['seller_logo_image'].widget.attrs.update( {'class': 'form-control'}) self.fields['seller_category_logo_image'].widget.attrs.update( {'class': 'form-control'}) self.fields['shop_title'].widget.attrs.update( {'class': 'form-control'}) self.fields['shop_link'].widget.attrs.update({'class': 'form-control'}) self.fields['shop_desc'].widget.attrs.update({'class': 'form-control'}) self.fields['status'].widget.attrs.update({'class': 'form-control'}) self.fields['business_section'].widget.attrs.update( {'class': 'form-control'}) self.fields['gk_stars'].widget.attrs.update({'class': 'form-control'}) self.fields['related_article_url'].widget.attrs.update( {'class': 'form-control'}) # self.fields['is2016store'].widget.attrs.update({'class':'form-control'}) # self.fields['is2015store'].widget.attrs.update({'class':'form-control'}) class Meta: model = Seller_Profile fields = [ # 'seller_user_id',\ 'seller_name','seller_logo_image','seller_category_logo_image',\ 'shop_title','shop_link', 'shop_desc', 'status', 'business_section',\ 'gk_stars', 'related_article_url', 'is2016store', 'is2015store' ] def clean_related_article_url(self): url = self.cleaned_data.get('related_article_url') if not url: return None p = re.compile(r'articles/(\d+)') k = p.search(url) if k is None: raise ValidationError('can not find article id in URL') return None article_id = k.group(1) try: article = Article.objects.get(pk=article_id) except Article.DoesNotExist: raise ValidationError('can not find article object') return None return url def handle_related_article_url(self): url = self.cleaned_data.get('related_article_url') if not url: return p = re.compile(r'articles/(\d+)') k = p.search(url) article_id = k.group(1) article = Article.objects.get(pk=article_id) self.instance.related_article = article def handle_post_image_by_name(self, image_name): _image = HandleImage(image_file=self.cleaned_data.get(image_name)) _image_path = _image.icon_save() return _image_path def handle_category_logo_image(self): image_name = 'seller_category_logo_image' if not self.cleaned_data.get(image_name): return _image_path = self.handle_post_image_by_name(image_name) self.instance.category_logo = _image_path return def handle_logo_image(self): image_name = 'seller_logo_image' if not self.cleaned_data.get(image_name): return _image_path = self.handle_post_image_by_name(image_name) self.instance.logo = _image_path return def save(self, commit=True, *args, **kwargs): self.handle_logo_image() self.handle_category_logo_image() self.handle_related_article_url() seller_profile = super(SellerForm, self).save(commit=True, *args, **kwargs)