class ProductsForm(forms.Form): name = forms.CharField(required=True, label='Наименование товара') description = forms.CharField(required=False,max_length=2000, label='Описание', widget=widgets.Textarea) category = forms.ChoiceField(required=False,label='Категория', choices=STATUS_CHOICES) balance = forms.IntegerField(label='Остаток', min_value=0) price = forms.DecimalField(max_digits=7, decimal_places=2, label='Цена')
class UserProfile(forms.Form): """Form used to modify user profile information""" prename = forms.CharField( required=True, label='Prename', error_messages={'required': 'Please insert your first name.'}, ) surname = forms.CharField( required=True, label='Surname', error_messages={'required': 'Please insert your last name.'}, ) email = forms.CharField( required=True, label='E-Mail:', error_messages={'required': 'Please insert your last e-mail.'}, ) age = forms.IntegerField( required=True, label='Age', error_messages={'required': 'Please insert an age.'}, ) birthday = forms.DateField(required=True, label='Birthday (YYYY-MM-DD)', error_messages={ 'required': """Please insert birthday in the \ format of (yyyy-mm-dd)""" }) motherland = forms.CharField( required=True, label="Motherland", error_messages={ 'required': 'Please insert the country of your native land' }, ) school = forms.CharField( required=True, label="School", error_messages={'required': 'Please insert the name of your school'}, ) major = forms.CharField( required=True, label="Major", error_messages={ 'required': """Please insert your main subject of studies. \ Ex: Software Engineering""" }) city = forms.CharField( required=True, label="city", error_messages={ 'required': 'Please insert the name of your current city' }, ) image = forms.ImageField(required=False, label="profile_picture")
class OTPCheckForm(forms.Form): otp = forms.IntegerField()
class URLInputForm(forms.Form, BaseFormFieldPluginForm): """Form for ``URLPlugin``.""" plugin_data_fields = [ ("label", ""), ("name", ""), ("help_text", ""), ("initial", ""), ("max_length", str(DEFAULT_MAX_LENGTH)), ("required", False), ("placeholder", ""), ] label = forms.CharField( label=_("Label"), required=True, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class} ) ) name = forms.CharField( label=_("Name"), required=True, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class} ) ) help_text = forms.CharField( label=_("Help text"), required=False, widget=forms.widgets.Textarea( attrs={'class': theme.form_element_html_class} ) ) initial = forms.URLField( label=_("Initial"), required=False, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class} ) ) max_length = forms.IntegerField( label=_("Max length"), required=True, widget=NumberInput(attrs={'class': theme.form_element_html_class, 'min': str(DEFAULT_MIN_LENGTH)}), initial=DEFAULT_MAX_LENGTH, validators=[MinValueValidator(DEFAULT_MIN_LENGTH)] ) required = forms.BooleanField( label=_("Required"), required=False, widget=forms.widgets.CheckboxInput( attrs={'class': theme.form_element_checkbox_html_class} ) ) placeholder = forms.CharField( label=_("Placeholder"), required=False, widget=forms.widgets.TextInput( attrs={'class': theme.form_element_html_class} ) ) def clean(self): super(URLInputForm, self).clean() max_length = self.cleaned_data.get('max_length', DEFAULT_MAX_LENGTH) if self.cleaned_data['initial']: len_initial = len(self.cleaned_data['initial']) if len_initial > max_length: self.add_error( 'initial', _("Ensure this value has at most {0} characters " "(it has {1}).".format(max_length, len_initial)) )
class SubmitForm(forms.Form): selection = forms.IntegerField(min_value=1, max_value=POCET_PRVKOV, label="Druhá najlepšia zlúčenina")
class AdditionForm(forms.Form): a = forms.IntegerField() b = forms.IntegerField()
class RouterForm(forms.Form): id = forms.IntegerField(required=False) sapid = forms.CharField(max_length=18) hostname = forms.CharField(max_length=14) loopback = forms.GenericIPAddressField(protocol='IPv4') mac_address = forms.CharField(max_length=17) def clean(self): cleaned_data = super(RouterForm, self).clean() mac_add = cleaned_data.get('mac_address', None) if not mac_add: return cleaned_data allowed = re.compile(r""" ( ^([0-9A-F]{2}[-]){5}([0-9A-F]{2})$ |^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$ ) """, re.VERBOSE | re.IGNORECASE) if allowed.match(mac_add) is None: raise forms.ValidationError('Entered Mac Address was Wrong!') id = cleaned_data.get('id', None) if not id: loopback = cleaned_data.get('loopback', None) check_ip_exist = RouterInfo.objects.filter(loopback=loopback, is_active=True).exclude(id=id) if check_ip_exist: raise forms.ValidationError('Entered LoopBack field is already exist!') sapid = cleaned_data.get('sapid', None) check_sap_exist = RouterInfo.objects.filter(sapid=sapid, is_active=True).exclude(id=id) if check_sap_exist: raise forms.ValidationError('Entered Sapid is already exist!') hostname = cleaned_data.get('hostname', None) check_host_exist = RouterInfo.objects.filter(hostname=hostname, is_active=True).exclude(id=id) if check_host_exist: raise forms.ValidationError('Entered Hostname is already exist!') mac_address = cleaned_data.get('mac_address', None) check_macadd_exist = RouterInfo.objects.filter(mac_address=mac_address,is_active=True).exclude(id=id) if check_macadd_exist: raise forms.ValidationError('Entered Mac Add is already exist!') else: loopback = cleaned_data.get('loopback', None) check_ip_exist = RouterInfo.objects.filter(loopback=loopback, is_active=True).exclude(id=id) if check_ip_exist: raise forms.ValidationError('Entered LoopBack field is already exist!') sapid = cleaned_data.get('sapid', None) check_sap_exist = RouterInfo.objects.filter(sapid=sapid, is_active=True).exclude(id=id) if check_sap_exist: raise forms.ValidationError('Entered Sapid is already exist!') hostname = cleaned_data.get('hostname', None) check_host_exist = RouterInfo.objects.filter(hostname=hostname, is_active=True).exclude(id=id) if check_host_exist: raise forms.ValidationError('Entered Hostname is already exist!') mac_address = cleaned_data.get('mac_address', None) check_macadd_exist = RouterInfo.objects.filter(mac_address=mac_address, is_active=True).exclude(id=id) if check_macadd_exist: raise forms.ValidationError('Entered Mac Add is already exist!') return cleaned_data
class RobokassaForm(BaseRobokassaForm): # login магазина в обменном пункте MrchLogin = forms.CharField(max_length=20, initial=LOGIN) # требуемая к получению сумма OutSum = forms.DecimalField( min_value=0, max_digits=20, decimal_places=2, required=False ) # номер счета в магазине (должен быть уникальным для магазина) InvId = forms.IntegerField(min_value=0, required=False) # описание покупки Desc = forms.CharField(max_length=100, required=False) # контрольная сумма MD5 SignatureValue = forms.CharField(max_length=32) # предлагаемая валюта платежа IncCurrLabel = forms.CharField(max_length=10, required=False) # e-mail пользователя Email = forms.CharField(max_length=100, required=False) # язык общения с клиентом (en или ru) Culture = forms.CharField(max_length=10, required=False) # Параметр с URL'ом, на который форма должны быть отправлена. # Может пригодиться для использования в шаблоне. target = FORM_TARGET def __init__(self, *args, **kwargs): super(RobokassaForm, self).__init__(*args, **kwargs) if TEST_MODE is True: self.fields["isTest"] = forms.BooleanField(required=False) self.fields["isTest"].initial = 1 # скрытый виджет по умолчанию for field in self.fields: self.fields[field].widget = forms.HiddenInput() self.fields["SignatureValue"].initial = self._get_signature() def get_redirect_url(self): """ Получить URL с GET-параметрами, соответствующими значениям полей в форме. Редирект на адрес, возвращаемый этим методом, эквивалентен ручной отправке формы методом GET. """ def _initial(name, field): val = self.initial.get(name, field.initial) return val fields = [ (name, _initial(name, field)) for name, field in list(self.fields.items()) if _initial(name, field) ] params = urlencode(fields, encoding='1251') return self.target + "?" + params def _initial_val(self, name): value = ( self.initial[name] if name in self.initial else self.fields[name].initial ) if value is None: return "" return str(value) def _get_signature_string(self): _val = self._initial_val standard_part = ":".join( [_val("MrchLogin"), _val("OutSum"), _val("InvId"), PASSWORD1] ) return self._append_extra_part(standard_part, _val)
class itemClickForm(forms.Form): user_id = forms.IntegerField(help_text="User ID: ") item_id = forms.IntegerField(help_text="Item ID: ")
class ProfileEditingForm(forms.Form): fname = forms.CharField(max_length=100, label='First Name', widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'First name' })) lname = forms.CharField(max_length=100, label='Last Name', widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'Last name' })) jobtitle = forms.CharField(max_length=100, label='Jobtitle', widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'Your Designation at work' })) workplace = forms.CharField(max_length=100, label='Workplace', widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'The name of Your Office' })) email = forms.EmailField(max_length=100, label='Email Address', widget=forms.EmailInput({ 'class': 'form-control', 'placeholder': 'eg. [email protected]' })) birth_date = forms.DateField(label='Birth Date', widget=forms.SelectDateWidget( { 'class': 'form-control date-selector', }, years=range(1950, 2020))) current_address = forms.CharField(label='Current Address', widget=forms.Textarea({ 'class': 'form-control textarea-selector', 'placeholder': 'Type in your present address' })) permanent_address = forms.CharField(label='Permanent Address', widget=forms.Textarea({ 'class': 'form-control textarea-selector', 'placeholder': 'Type in your permanent address' })) phone_mobile = forms.IntegerField(label='Mobile No.', widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'eg. +91 00000 00000' })) phone_home = forms.IntegerField(label='Personal Phone', widget=forms.TextInput({ 'class': 'form-control', 'placeholder': 'eg. +91 00000 00000' })) phone_work = forms.IntegerField(label='Work Contact', widget=forms.NumberInput({ 'class': 'form-control', 'placeholder': 'eg. +91 00000 00000' })) relationship_status = forms.ChoiceField( choices=( ('MR', 'Married'), ('SN', 'Single'), ('RL', 'In a Relationship'), ('DV', 'Divorced'), ), widget=forms.RadioSelect({'class': 'form-control choice-selector'}))
class FailRedirectForm(BaseRobokassaForm): """Форма приема результатов для перенаправления на страницу Fail""" OutSum = forms.CharField(max_length=15) InvId = forms.IntegerField(min_value=0) Culture = forms.CharField(max_length=10)
class MyForm(forms.Form): StartingSalary = forms.IntegerField(initial = 10000) YearlyHikePercent = forms.FloatField(initial = 10, min_value=0.0, max_value=100.0) PromotionCycle = forms.IntegerField(initial = 2,min_value=1, max_value=5) Tenure = forms.IntegerField(initial = 3) # Option = forms.CharField( widget=forms.Select(choices=School_CHOICES))
class AddForm(forms.Form): price = forms.FloatField(label='输入外币售价') #售价 weight = forms.IntegerField(label='输入重量g') purchase_price = forms.FloatField(label='输入采购价¥') #采购价 volume = forms.FloatField(label='输入体积m³', initial=0.001, required=False)
class EditPartnerPrefrencesForm(forms.ModelForm): age = forms.IntegerField(required=True, widget=forms.TextInput( attrs={ 'class': 'form-control', 'autocomplete': 'off', 'pattern': '[0-9 ]+', 'title': 'Enter Characters Only ' })) sex = forms.CharField(required=True, widget=forms.TextInput( attrs={ 'class': 'form-control', 'autocomplete': 'off', 'pattern': '[A-Za-z ]+', 'title': 'Enter Characters Only ' })) location = forms.CharField(required=True, widget=forms.TextInput( attrs={ 'class': 'form-control', 'autocomplete': 'off', 'pattern': '[\w ]+', 'title': 'Enter Characters Only ' })) ethnicity = forms.CharField(required=True, widget=forms.TextInput( attrs={ 'class': 'form-control', 'autocomplete': 'off', 'pattern': '[A-Za-z ]+', 'title': 'Enter Characters Only ' })) def clean(self): form_data = self.cleaned_data age = self.cleaned_data.get('age') sex = self.cleaned_data.get('sex') location = self.cleaned_data.get('location') ethnicity = self.cleaned_data.get('ethnicity') if age is None or not 18 < age < 112: self.errors["age"] = [ "Your age must be a identified by a number between 18 and 112" ] if sex is None: self.errors["sex"] = [ "Your Sex must be identified in lower case male, female, or other" ] return form_data if location is None: self.errors["location"] = [ "Make your location a valid address e.g 35 Swanston Street Melbourne" ] return form_data if ethnicity is None: self.errors["ethnicity"] = [ "Ensure you enter a valid Race you belong to" ] return form_data class Meta: model = PartnerPrefrences fields = {'location', 'sex', 'age', 'ethnicity'}
class VisualizationRequestForm(RequestForm): bounds = forms.CharField(required=False) zoom = forms.IntegerField(required=False)
class EventAttendanceForm(forms.Form): attendee_count = forms.IntegerField(label='', widget=forms.HiddenInput())
class MultiplePizzaForm(forms.Form): number = forms.IntegerField(min_value=2, max_value=6)
class QueryForm(forms.Form): query = forms.CharField(required=True, max_length=100) lang = forms.ChoiceField(widget=forms.Select(), choices=([('en', 'en'), ('id', 'id')]), initial='en', required=True) count = forms.IntegerField(required=True, min_value=1, max_value=100)
class UnsubscribeForm(forms.Form): email = forms.EmailField() id = forms.IntegerField()
class DeleteExpenseForm(forms.Form): """ Delete expense form """ expense_pk = forms.IntegerField(widget=forms.HiddenInput)
class CreateUserForm(forms.Form): total = forms.IntegerField( validators=[MinValueValidator(5), MaxValueValidator(500)])
class order1(forms.Form): it_quantity = forms.IntegerField()
class DataSetAdminForm(forms.ModelForm): class Meta: model = DataSet fields = ('market', 'description', 'reveal_interval', 'is_training') # the amount of random entries to generate. n_random_entries = forms.IntegerField(initial=0, required=False) # the uploaded file to use as an input. upload_file = forms.ModelChoiceField(queryset=Document.objects.none(), empty_label='None', required=False) # gets the files this user has uploaded # also removes the upload buttons if editing a set def __init__(self, *args, **kwargs): super(DataSetAdminForm, self).__init__(*args, **kwargs) if self.instance.id: # if the set is already created # disable uploading new data self.fields['n_random_entries'].widget.attrs['readonly'] = 'True' self.fields['upload_file'].widget.attrs['readonly'] = 'True' # disable market changing self.fields['market'].queryset = Market.objects.filter( dataset=self.instance) self.is_new = False else: self.is_new = True self.fields['upload_file'].queryset = Document.objects.filter( user=self.user) # makes sure the selected market has events # only checked for new datasets as existing ones can't have their market changed. def clean_market(self): market = self.cleaned_data.get('market', 0) if self.is_new: # raise error if trying to add a dataset for an empty market # (a market with no events) event_count = market.events.count() if event_count == 0: raise forms.ValidationError( "The current market has no events!") return market # check whether only one of random/file data sources is set def clean(self): if self.is_new: cleaned_data = super(DataSetAdminForm, self).clean() file = cleaned_data.get('upload_file', None) n_random = cleaned_data.get('n_random_entries', 0) gen_random = n_random > 0 has_file = file != None if (gen_random == has_file): raise forms.ValidationError( "You must choose exactly one data source for the set. ") # no uploaded file parsing yet. # TODO: check uploaded file's schema # and raise error if it doesn't match events if has_file: raise forms.ValidationError( "Uploaded file parsing is not yet implemented!") # save the cleaned data to the form def save(self, commit=True): self.file = self.cleaned_data.get('upload_file', None) self.n_random = self.cleaned_data.get('n_random_entries', 0) return super().save(commit=commit)
class CorporateMemberSignUpForm(forms.ModelForm): amount = forms.IntegerField( label='Donation amount', help_text='Enter an integer in US$ without the dollar sign.', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.checkbox_fields = [] self.radio_select_fields = [] self.label_fields = [] self.fields['logo'].required = True self.fields['django_usage'].required = True for name, field in self.fields.items(): help_text = field.help_text if help_text: help_text = ' (' + help_text + ')' self.fields[name].help_text = '' self.fields[name].widget.attrs = {'placeholder': field.label + help_text} if isinstance(field.widget, forms.CheckboxInput): self.checkbox_fields.append(name) elif isinstance(field.widget, forms.RadioSelect): self.radio_select_fields.append(name) elif isinstance(field.widget, (forms.FileInput, forms.Select)): self.label_fields.append(name) self.fields['billing_name'].widget.attrs['placeholder'] = ( "Billing name (If different from above name)." ) self.fields['billing_name'].help_text = ( "For example, this might be your full registered company name." ) self.fields['display_name'].widget.attrs['placeholder'] = ( "Your organization's name as you'd like it to appear on our website." ) self.fields['address'].widget.attrs['placeholder'] = ( 'Mailing address' ) self.fields['address'].help_text = ( 'We can send the invoice by email, but we need a contact address.' ) self.fields['description'].widget.attrs['placeholder'] = ( "A short paragraph that describes your organization and its " "activities, written as if the DSF were describing your company " "to a third party." ) self.fields['description'].help_text = ( """We'll use this text on the <a href="/foundation/corporate-members/"> corporate membership page</a>; you can use the existing descriptions as a guide for flavor we're looking for.""" ) self.fields['django_usage'].widget.attrs['placeholder'] = ( 'How does your organization use Django?' ) self.fields['django_usage'].help_text = ( "This won't be displayed publicly but helps the DSF Board " "to evaluate your application." ) self.fields['amount'].help_text = ( """Enter an amount above and the appropriate membership level will be automatically selected. Or select a membership level below and the minimum donation will be entered for you. See <a href="/foundation/corporate-membership/#dues">dues</a> for details on the levels.""" ) class Meta: fields = [ 'display_name', 'billing_name', 'logo', 'url', 'contact_name', 'contact_email', 'billing_email', 'address', 'description', 'django_usage', 'amount', 'membership_level', ] model = CorporateMember @property def is_renewing(self): return not self.instance._state.adding def save(self, *args, **kwargs): is_renewing = self.is_renewing # self.is_renewing changes after super() instance = super().save(*args, **kwargs) send_mail( 'Django Corporate Membership %s: %s' % ( 'Renewal' if is_renewing else 'Application', self.instance.display_name, ), "Thanks for %s a corporate member of the Django Software Foundation! " "Your application is received and we'll follow up with an invoice soon." % ( 'renewing as' if is_renewing else 'applying to be' ), settings.FUNDRAISING_DEFAULT_FROM_EMAIL, [ settings.FUNDRAISING_DEFAULT_FROM_EMAIL, self.instance.contact_email, '*****@*****.**', '*****@*****.**', ], ) instance.invoice_set.create(amount=self.cleaned_data['amount']) return instance
class ReviewForm(forms.Form): review = forms.CharField(widget=forms.Textarea, required=True) score = forms.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(5)])
class RegistrationForm(forms.Form): name = forms.CharField( widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': ' Enter Your Name' } ) ) contact = forms.IntegerField( widget=forms.NumberInput( attrs={ 'class': 'form-control', 'placeholder': ' Enter Your Mobile No.' } ) ) email = forms.EmailField( widget=forms.EmailInput( attrs={ 'class': 'form-control', 'placeholder': ' Enter Your Email' } ) ) uname = forms.CharField( widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': ' Enter Your Username' } ) ) password1 = forms.CharField( label='Password', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': ' Enter Your Password' } ) ) password2 = forms.CharField( label='Confirm Password', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Confirm password' } ) ) image = forms.ImageField( widget=forms.FileInput( attrs={ 'class': 'form-control', } ) ) def clean_name(self): name = self.cleaned_data.get('name') if len(name)<=3 or len(name)>=30: raise forms.ValidationError("Name Must Have more than 3 or less than 30 Characters ") return name def clean_uname(self): uname = self.cleaned_data.get('uname') qs = ProData.objects.filter(uname=uname) if qs.exists(): raise forms.ValidationError("User name is taken already.") elif len(uname)<=5: raise forms.ValidationError("User Name Must have more than 5 Chars") return uname def clean_email(self): email = self.cleaned_data.get('email') qs = ProData.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("Email name is taken already.") elif not 'gmail.com' in email: raise forms.ValidationError("Email has to end with gmail.com") return email def clean_contact(self): contact = self.cleaned_data.get('contact') mob = ProData.objects.filter(contact=contact) if mob.exists(): raise forms.ValidationError('Mobile Number Already Taken') elif len(str(contact)) != 10: raise forms.ValidationError('Enter Valid Mobile Number') return contact def clean(self): data = self.cleaned_data password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password2 != password1 : raise forms.ValidationError("Passwords must match.") elif len(password1) <= 4 or len(password1) >= 15: raise forms.ValidationError("Password length must be more then 4 chars or less then 15") return data
class VendorCreationForm(UserCreationForm): contact_number = forms.IntegerField() class Meta: model = User fields = ['username', 'email', 'contact_number']
class GEMObservationForm(BaseRoboticObservationForm): """ The GEMObservationForm defines and collects the parameters for the Gemini Target of Opportunity (ToO) observation request API. The Gemini ToO process is described at https://www.gemini.edu/node/11005 The team must have have an approved ToO program on Gemini and define ToO template observations, complete observations without defined targets, during the Phase 2 process. Authentication is done via a "User key" tied to an email address. See the following page for help on getting a user key and the password needed for the trigger request. https://www.gemini.edu/node/12109 The following parameters are available. prog - program id email - email address for user key password - password for user key associated with email, site specific, emailed by the ODB obsnum - id of the template observation to clone and update, must be 'On Hold' target - name of the target ra - target RA [J2000], format 'HH:MM:SS.SS' dec - target Dec[J2000], format 'DD:MM:SS.SSS' mags - target magnitude information (optional) noteTitle - title for the note, "Finding Chart" if not provided (optional) note - text to include in a "Finding Chart" note (optional) posangle - position angle [degrees E of N], defaults to 0 (optional) exptime - exposure time [seconds], if not given then value in template used (optional) group - name of the group for the new observation (optional) gstarget - name of guide star (optional, but must be set if any gs* parameter given) gsra - guide star RA [J2000] (optional, but must be set if any gs* parameter given) gsdec - guide star Dec[J2000] (optional, but must be set if any gs* parameter given) gsmags - guide star magnitude (optional) gsprobe - PWFS1, PWFS2, OIWFS, or AOWFS (optional, but must be set if any gs* parameter given) ready - if "true" set the status to "Prepared/Ready", otherwise remains at "On Hold" (default "true") windowDate - interpreted in UTC in the format 'YYYY-MM-DD' windowTime - interpreted in UTC in the format 'HH:MM' windowDuration - integer hours elevationType - "none", "hourAngle", or "airmass" elevationMin - minimum value for hourAngle/airmass elevationMax - maximum value for hourAngle/airmass The server authenticates the request, finds the matching template observation, clones it, and then updates it with the remainder of the information. That way the template observation can be reused in the future. The target name, ra, and dec are straightforward. The note text is added to a new note, the identified purpose of which is to contain a link to a finding chart. The "ready" parameter is used to determine whether to mark the observation as "Prepared" (and thereby generate the TOO trigger) or keep it "On Hold". The exposure time parameter, if given, only sets the exposure time in the instrument "static component", which is tied to the first sequence step. Any exposure times defined in additional instrument iterators in the template observation sequence will not be changed. If the exposure time is not given then the value defined in the template observation is used. The exposure time must be an integer between 1 and 1200 seconds. If the group is specified and it does not exist (using a case-sensitive match) then a new group is created. The guide star ra, dec, and probe are optional but recommended since there is no guarantee, especially for GMOS, that a guide star will be available at the requested position angle. If no guide star is given then the OT will attempt to find a guide star. If any gs* parameter is specified, then gsra, gsdec, and gsprobe must all be specified. Otherwise an HTTP 400 (Bad Request) is returned with the message "guide star not completely specified". If gstarget is missing or "" but other gs* parameters are present, then it defaults to "GS". If "target", "ra", or "dec" are missing, then an HTTP 400 (Bad Request) is returned with the name of the missing parameter. If any ra, dec, or guide probe parameter cannot be parsed, it also generates a bad request response. Magnitudes are optional, but when supplied must contain all three elements (value, band, system). Multiple magnitudes can be supplied; use a comma to delimit them (for example "24.2/U/Vega,23.4/r/AB"). Magnitudes can be specified in Vega, AB or Jy systems in the following bands: u, U, B, g, V, UC, r, R, i, I, z, Y, J, H, K, L, M, N, Q, AP. """ # Form fields obsid = forms.MultipleChoiceField(choices=obs_choices()) ready = forms.ChoiceField(initial='true', choices=(('true', 'Yes'), ('false', 'No'))) brightness = forms.FloatField(required=False, label='Target Brightness') brightness_system = forms.ChoiceField(required=False, initial='AB', label='Brightness System', choices=(('Vega', 'Vega'), ('AB', 'AB'), ('Jy', 'Jy'))) brightness_band = forms.ChoiceField( required=False, initial='r', label='Brightness Band', choices=(('u', 'u'), ('U', 'U'), ('B', 'B'), ('g', 'g'), ('V', 'V'), ('UC', 'UC'), ('r', 'r'), ('R', 'R'), ('i', 'i'), ('I', 'I'), ('z', 'z'), ('Y', 'Y'), ('J', 'J'), ('H', 'H'), ('K', 'K'), ('L', 'L'), ('M', 'M'), ('N', 'N'), ('Q', 'Q'), ('AP', 'AP'))) posangle = forms.FloatField(min_value=0., max_value=360., required=False, initial=0.0, label='Position Angle') exptimes = forms.CharField(required=False, label='Exptime(s) [s]') group = forms.CharField(required=False, label='Group Name') notetitle = forms.CharField(required=False, initial='Finding Chart', label='Note Title') note = forms.CharField(required=False, label='Note Text') eltype = forms.ChoiceField(required=False, label='Airmass/Hour Angle', choices=(('none', 'None'), ('airmass', 'Airmass'), ('hourAngle', 'Hour Angle'))) elmin = forms.FloatField(required=False, min_value=-5.0, max_value=5.0, label='Min Airmass/HA', initial=1.0) elmax = forms.FloatField(required=False, min_value=-5.0, max_value=5.0, label='Max Airmass/HA', initial=2.0) gstarg = forms.CharField(required=False, label='Guide Star Name') gsra = forms.CharField(required=False, label='Guide Star RA') gsdec = forms.CharField(required=False, label='Guide Star Dec') gsbrightness = forms.FloatField(required=False, label='Guide Star Brightness') gsbrightness_system = forms.ChoiceField(required=False, initial='Vega', label='Brightness System', choices=(('Vega', 'Vega'), ('AB', 'AB'), ('Jy', 'Jy'))) gsbrightness_band = forms.ChoiceField( required=False, initial='UC', label='Brightness Band', choices=(('UP', 'u'), ('U', 'U'), ('B', 'B'), ('GP', 'g'), ('V', 'V'), ('UC', 'UC'), ('RP', 'r'), ('R', 'R'), ('IP', 'i'), ('I', 'I'), ('ZP', 'z'), ('Y', 'Y'), ('J', 'J'), ('H', 'H'), ('K', 'K'), ('L', 'L'), ('M', 'M'), ('N', 'N'), ('Q', 'Q'), ('AP', 'AP'))) gsprobe = forms.ChoiceField( required=False, label='Guide Probe', initial='OIWFS', choices=(('OIWFS', 'OIWFS'), ('PWFS1', 'PWFS1'), ('PWFS2', 'PWFS2'), ('AOWFS', 'AOWFS'))) # GS probe (PWFS1/PWFS2/OIWFS/AOWFS) window_start = forms.CharField( required=False, # widget=forms.TextInput(attrs={'type': 'date'}), widget=forms.DateTimeInput(attrs={'type': 'datetime'}, format='%Y-%m-%d %H:%M:%S'), label='Timing Window') window_duration = forms.IntegerField(required=False, min_value=1, label='Window Duration [hr]') # Fields needed for running parangle/gsselect pamode = forms.ChoiceField(required=False, label='PA Mode', choices=(('flip', 'Flip180'), ('fixed', 'Fixed'), ('find', 'Set PA for brightest guide star'), ('parallactic', 'Parallactic Angle'))) obsdate = forms.CharField( required=False, # widget=forms.TextInput(attrs={'type': 'date'}), widget=forms.DateTimeInput(attrs={'type': 'datetime'}, format='%Y-%m-%d %H:%M:%S'), label='UT DateTime (Par)') # Eventually select instrument from obsid text? inst = forms.ChoiceField(required=False, label='Instrument', initial='GMOS', choices=(('GMOS', 'GMOS'), ('GNIRS', 'GNIRS'), ('NIFS', 'NIFS'), ('NIRIF/6', 'NIRIF/6'), ('NIRIF/14', 'NIRIF/14'), ('NIRIF/32', 'NIRIF/32'))) gsprobe = forms.ChoiceField( required=False, label='Guide Probe', initial='OIWFS', choices=(('OIWFS', 'OIWFS'), ('PWFS1', 'PWFS1'), ('PWFS2', 'PWFS2'), ('AOWFS', 'AOWFS'))) # GS probe (PWFS1/PWFS2/OIWFS/AOWFS) port = forms.ChoiceField(required=False, label='ISS Port', choices=(('side', 'Side'), ('up', 'Up'))) ifu = forms.ChoiceField(required=False, label='IFU Mode', choices=(('none', 'None'), ('two', 'Two Slit'), ('red', 'One Slit Red'))) overwrite = forms.ChoiceField(required=False, label='Overwrite previous?', initial='False', choices=(('False', 'No'), ('True', 'Yes'))) chop = False # Chopping (no longer used, should be False) l_pad = 7. # Padding applied to WFS FoV (to account for uncertainties in shape) [arcsec] l_rmin = -1. # Minimum radius for guide star search [arcmin], -1 to use default iq = forms.ChoiceField(required=False, label='Image Quality', initial='Any', choices=(('20', '20%-tile'), ('70', '70%-tile'), ('85', '85%-tile'), ('Any', 'Any'))) cc = forms.ChoiceField(required=False, label='Cloud Cover', initial='Any', choices=(('50', '50%-tile'), ('70', '70%-tile'), ('80', '80%-tile'), ('Any', 'Any'))) sb = forms.ChoiceField(required=False, label='Sky Brightness', initial='Any', choices=(('20', '20%-tile'), ('50', '50%-tile'), ('80', '80%-tile'), ('Any', 'Any'))) gssearch = forms.ChoiceField(initial='true', required=False, label='Guide star search?', choices=(('true', 'Yes'), ('false', 'No'))) def layout(self): return Div( HTML('<big>Observation Parameters</big>'), HTML('<p>Select the Obsids of one or more templates. <br>'), HTML( 'Setting Ready=No will keep the new observation(s) On Hold. <br>' ), HTML( 'If a value is not set, then the template default is used. <br>' ), HTML( 'If setting Exptime, then provide a list of values if selecting more than one Obsid.</p>' ), Div(Div('obsid', css_class='col'), Div('ready', css_class='col'), Div('group', css_class='col'), css_class='form-row'), Div(Div('posangle', 'brightness', 'eltype', 'exptimes', 'notetitle', css_class='col'), Div('pamode', 'brightness_band', 'elmin', 'window_start', 'note', css_class='col'), Div('obsdate', 'brightness_system', 'elmax', 'window_duration', css_class='col'), css_class='form-row'), HTML('<big>Optional Guide Star Parameters</big>'), HTML('<p>If any one of Name/RA/Dec is given, then all must be.<br>' ), HTML( 'Auto guide star search not done if there is a manual entry.</p>' ), Div(Div('gstarg', 'gsbrightness', 'inst', 'iq', 'gssearch', css_class='col'), Div('gsra', 'gsbrightness_band', 'gsprobe', 'cc', 'overwrite', css_class='col'), Div('gsdec', 'gsbrightness_system', 'ifu', 'sb', 'port', css_class='col'), css_class='form-row')) def is_valid(self): super().is_valid() errors = GEMFacility.validate_observation(self.observation_payload()) if errors: self.add_error(None, flatten_error_dict(self, errors)) return not errors def observation_payload(self): def isodatetime(value): isostring = parse(value).isoformat() ii = isostring.find('T') date = isostring[0:ii] time = isostring[ii + 1:] return date, time def findgs(obs): gstarg = '' gsra = '' gsdec = '' gsmag = '' sgsmag = '' gspa = 0.0 spa = str(gspa).strip() l_pa = self.cleaned_data['posangle'] # Convert RA to hours target = Target.objects.get(pk=self.cleaned_data['target_id']) ra = target.ra / 15. dec = target.dec # l_site = get_site(self.cleaned_data['obsid'],location=True) l_site = get_site(obs, location=True) l_pad = 7. l_chop = False l_rmin = -1. # Parallactic angle? l_pamode = self.cleaned_data['pamode'] if l_pamode == 'parallactic': if self.cleaned_data['obsdate'].strip() == '': print( 'WARNING: Observation date must be set in order to calculate the parallactic angle.' ) return gstarg, gsra, gsdec, sgsmag, spa else: odate, otime = isodatetime(self.cleaned_data['obsdate']) l_pa = parangle(str(ra), str(dec), odate, otime, l_site).value l_pamode = 'flip' # in case of guide star selection # print(str(ra), str(dec), odate, otime, l_pa, l_site) # Guide star overw = self.cleaned_data['overwrite'] == 'True' gstarg, gsra, gsdec, gsmag, gspa = gsselect( target.name, str(ra), str(dec), pa=l_pa, imdir=settings.MEDIA_ROOT, site=l_site, pad=l_pad, cat='UCAC4', inst=self.cleaned_data['inst'], ifu=self.cleaned_data['ifu'], port=self.cleaned_data['port'], wfs=self.cleaned_data['gsprobe'], chopping=l_chop, pamode=l_pamode, rmin=l_rmin, iq=self.cleaned_data['iq'], cc=self.cleaned_data['cc'], sb=self.cleaned_data['sb'], overwrite=overw, display=False, verbose=False, figout=True, figfile='default') if gstarg != '': sgsmag = str(gsmag).strip() + '/UC/Vega' spa = str(gspa).strip() return gstarg, gsra, gsdec, sgsmag, spa payloads = [] target = Target.objects.get(pk=self.cleaned_data['target_id']) spa = str(self.cleaned_data['posangle']).strip() nobs = len(self.cleaned_data['obsid']) if self.cleaned_data['exptimes'] != '': expvalues = self.cleaned_data['exptimes'].split(',') if len(expvalues) != nobs: payloads.append({ "error": "If exptimes given, the number of values must equal the number of obsids " "selected." }) return payloads # Convert exposure times to integers exptimes = [] try: [exptimes.append(round(float(exp))) for exp in expvalues] except Exception: payloads.append( {"error": "Problem converting string to integer."}) return payloads for jj in range(nobs): obs = self.cleaned_data['obsid'][jj] ii = obs.rfind('-') progid = obs[0:ii] obsnum = obs[ii + 1:] payload = { "prog": progid, # "password": self.cleaned_data['userkey'], "password": GEM_SETTINGS['api_key'][get_site(obs)], # "email": self.cleaned_data['email'], "email": GEM_SETTINGS['user_email'], "obsnum": obsnum, "target": target.name, "ra": target.ra, "dec": target.dec, "ready": self.cleaned_data['ready'] } if self.cleaned_data[ 'notetitle'] != 'Finding Chart' or self.cleaned_data[ 'note'] != '': payload["noteTitle"] = self.cleaned_data['notetitle'] payload["note"] = self.cleaned_data['note'] if self.cleaned_data['brightness'] is not None: smags = str(self.cleaned_data['brightness']).strip() + '/' + \ self.cleaned_data['brightness_band'] + '/' + \ self.cleaned_data['brightness_system'] payload["mags"] = smags if self.cleaned_data['exptimes'] != '': payload['exptime'] = exptimes[jj] if self.cleaned_data['group'].strip() != '': payload['group'] = self.cleaned_data['group'].strip() # timing window? if self.cleaned_data['window_start'].strip() != '': wdate, wtime = isodatetime(self.cleaned_data['window_start']) payload['windowDate'] = wdate payload['windowTime'] = wtime payload['windowDuration'] = str( self.cleaned_data['window_duration']).strip() # elevation/airmass if self.cleaned_data['eltype'] is not None: payload['elevationType'] = self.cleaned_data['eltype'] payload['elevationMin'] = str( self.cleaned_data['elmin']).strip() payload['elevationMax'] = str( self.cleaned_data['elmax']).strip() # Guide star gstarg = self.cleaned_data['gstarg'] if gstarg != '': gsra = self.cleaned_data['gsra'] gsdec = self.cleaned_data['gsdec'] if self.cleaned_data['gsbrightness'] is not None: sgsmag = str(self.cleaned_data['gsbrightness']).strip() + '/' + \ self.cleaned_data['gsbrightness_band'] + '/' + \ self.cleaned_data['gsbrightness_system'] elif self.cleaned_data['gssearch'] == 'true': gstarg, gsra, gsdec, sgsmag, spa = findgs(obs) if gstarg != '': payload['gstarget'] = gstarg payload['gsra'] = gsra payload['gsdec'] = gsdec payload['gsmags'] = sgsmag payload['gsprobe'] = self.cleaned_data['gsprobe'] payload['posangle'] = spa payloads.append(payload) return payloads
class CreateClassForm(forms.Form): class_name = forms.CharField() credits = forms.IntegerField()
class ProductForm(forms.Form): nombre = forms.CharField(label='nombre', max_length=50) precio = forms.CharField(label='precio', max_length=50) stock = forms.IntegerField(label='stock') descripcion = forms.CharField(label='descripcion', max_length=100) categoria = forms.CharField(label='categoria', max_length=50)