class CustomUserCreationForm(UserCreationForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password Confirmation', widget=forms.PasswordInput) class Meta(UserCreationForm.Meta): model = MentokiUser fields = ('username', 'email') def clean_username(self): username = self.cleaned_data.get('username') try: MentokiUser._default_manager.get(username=username) except MentokiUser.DoesNotExist: return username raise forms.ValidationError(self.error_messages('Duplicate username')) def clean_password2(self): #check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError('Passwords do not match') def save(self, commit=True): # save the provided password in hashed format user = super(CustomUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) logging.info('Benutzer [%s]: neues Passwort' % self) if commit: user.save() return user
class DjangoBackendPasswordChangeForm(PasswordChangeForm): old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput) new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput) new_password2 = forms.CharField(label=_("New password (repeat)"), widget=forms.PasswordInput)
class SignupForm(forms.Form): """ User Signup Form """ first_name = forms.CharField( label='Vorname', max_length=30, widget=forms.TextInput(attrs={ 'placeholder': 'Vorname', 'autofocus': 'autofocus' })) last_name = forms.CharField( label='Nachname', max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Nachname'})) def signup(self, request, user): """ signup of users if an anonymous user was redirected to the signup form, it is memorized, what he wanted to buy in the "unfinshed_product_pk". :param request: :param user: :return: None """ user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if request.session.has_key('unfinished_checkout'): user.checkout_product_pk=\ request.session['unfinished_product_pk'] logger.info('Benutzer [%s] wird gespeichert mit Wunsch: [%s]' % (user, user.checkout_product_pk)) user.save()
class MessageTopicForm(forms.ModelForm): subject = forms.CharField( max_length=100, label=_('A subject'), widget=TextInput(attrs={'placeholder': 'Contact'})) name = forms.CharField( max_length=30, label=_('Your full name'), widget=TextInput(attrs={'placeholder': 'Name Surname'})) email = forms.EmailField( label=_('Email'), widget=EmailInput(attrs={'placeholder': '*****@*****.**'})) class Meta: model = Message fields = [ 'message', ] widgets = { 'message': Textarea(attrs={ 'placeholder': 'your contact reason...', 'rows': 4, }), } def __init__(self, *args, **kws): super(MessageTopicForm, self).__init__(*args, **kws) self.fields.keyOrder = ['subject', 'name', 'email', 'message']
class BuscaInicialForm(forms.Form): tipo_interesse = forms.CharField() tipo_imovel = forms.CharField() cidade = forms.CharField() imovel_ref = forms.CharField(required=False) residencial_comercial = forms.CharField() def __init__(self, *args, **kwargs): super(BuscaInicialForm, self).__init__(*args, **kwargs) self.fields['tipo_interesse'] = forms.ChoiceField( choices=InteresseBase.TIPOS_INTERESSE) self.fields['tipo_interesse'].label = "Interesse" self.fields['tipo_imovel'] = forms.ChoiceField( choices=tuple(Imovel.TIPO_IMOVEL)) self.fields['tipo_imovel'].label = "Tipo do imóvel" cidades_qs = Cidade.objects.all() cidade_list = [(cidade.nome, cidade.nome) for cidade in cidades_qs] self.fields['cidade'] = forms.ChoiceField( choices=cidade_list) opcoes_list = (('residencial', 'Residencial'), ('comercial', 'Comercial'), ) self.fields['residencial_comercial'] = forms.ChoiceField( label='', choices=tuple(opcoes_list), initial='residencial', widget=RadioSelect())
class LoginForm(forms.Form): """ Formulaire de connexion """ username = forms.CharField( required=True, widget=forms.TextInput(attrs={'placeholder': _("User name or email")}), label=_("Identifier")) password = forms.CharField( required=True, widget=forms.PasswordInput(attrs={'placeholder': _("Password")}), label=_("Password")) def __init__(self, *args, **kwargs): """ Initialiser le formulaire """ super(LoginForm, self).__init__(*args, **kwargs) self.request = kwargs.get('request', None) # Validation def clean(self): """ Valider et renvoyer les données du formulaire """ username = self.cleaned_data.get('username', None) password = self.cleaned_data.get('password', None) if username and password: User.sign(self.request, { 'username': username, 'password': password }, fake=True) return self.cleaned_data raise ValidationError( _("You must provide an username or email and a password."))
class EscalationMessageForm(forms.Form): subject = forms.CharField( label=_("Subject"), max_length=230, widget=forms.TextInput(attrs={"class": "form-control"})) message = forms.CharField( widget=forms.Textarea(attrs={"class": "form-control"}), label=_("Your message"), ) def __init__(self, foirequest, *args, **kwargs): super(EscalationMessageForm, self).__init__(*args, **kwargs) self.foirequest = foirequest def clean_message(self): message = self.cleaned_data['message'] message = message.replace('\r\n', '\n').strip() empty_form = self.foirequest.get_escalation_message_form() if message == empty_form.initial['message'].strip(): raise forms.ValidationError( _('You need to fill in the blanks in the template!')) return message def clean(self): throttle_message = check_throttle(self.foirequest.user, FoiMessage) if throttle_message: raise forms.ValidationError(throttle_message) def save(self): self.foirequest.add_escalation_message(**self.cleaned_data)
class ChangePasswordForm(forms.Form): success_message = _('Your password was changed successfully') current_password = forms.CharField(label=_('Current password'), widget=forms.PasswordInput) new_password = forms.CharField(label=_('New password'), widget=forms.PasswordInput) new_password2 = forms.CharField(label=_('New password (confirm)'), widget=forms.PasswordInput) def __init__(self, *args, **kwargs): self.user = kwargs.pop('instance') super().__init__(*args, **kwargs) def clean_current_password(self): password = self.cleaned_data['current_password'] if not self.user.check_password(password): raise forms.ValidationError(_('Incorrect password')) return password def clean_new_password2(self): password_1 = self.cleaned_data.get('new_password', '') if self.cleaned_data['new_password2'] != password_1: raise forms.ValidationError(_("The two passwords didn't match")) return password_1 def save(self): self.user.set_password(self.cleaned_data['new_password']) self.user.save()
class LoginForm(AuthenticationForm, forms.Form): """ Override the default authentication """ message_incorrect_password = "******" message_inactive = "This account is inactive." username = forms.CharField( max_length=76, widget=TextInput(attrs={'placeholder': 'Email or Username'})) password = forms.CharField(widget=PasswordInput( attrs={'placeholder': 'Password'})) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if '@' in username: UserModel = get_user_model() user_email = UserModel._default_manager.filter( email__iexact=username) if user_email: username = user_email[0].username if username and password: self.user_cache = authenticate(username=username, password=password) if (self.user_cache is None): raise forms.ValidationError(self.message_incorrect_password) if not self.user_cache.is_active: raise forms.ValidationError(self.message_inactive) self.check_for_test_cookie() return self.cleaned_data
class LoginClientForm(AuthenticationForm, forms.Form): """ Override the default authentication """ message_incorrect_password = "******" message_inactive = "This account is inactive." username = forms.CharField(max_length=76, widget=TextInput(attrs={'placeholder': '*****@*****.**'})) password = forms.CharField(widget=PasswordInput(attrs={'placeholder': '12991...'})) def __init__(self, *args, **kwargs): super(LoginClientForm, self).__init__(*args, **kwargs) self.fields['username'].label = "Email" self.fields['password'].label = "Telefone" def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if '@' in username: UserModel = get_user_model() user_email = UserModel._default_manager.filter(email__iexact=username) if user_email: username = user_email[0].username if username and password: self.user_cache = authenticate(username=username, password=password) if (self.user_cache is None): raise forms.ValidationError(self.message_incorrect_password) if not self.user_cache.is_active: raise forms.ValidationError(self.message_inactive) # self.check_for_test_cookie() return self.cleaned_data
class UserDeleteForm(forms.Form): CONFIRMATION_PHRASE = str(_('Freedom of Information Act')) password = forms.CharField( widget=forms.PasswordInput(), label=_('Password'), help_text=_('Please type your password to confirm.')) confirmation = forms.CharField( widget=ConfirmationWidget({'placeholder': CONFIRMATION_PHRASE}), label=_('Confirmation Phrase'), help_text=_('Type the phrase above exactly as displayed.')) def __init__(self, user, *args, **kwargs): self.user = user super(UserDeleteForm, self).__init__(*args, **kwargs) def clean_password(self): password = self.cleaned_data['password'] user = auth.authenticate(username=self.user.email, password=password) if not user: raise forms.ValidationError(_('You provided the wrong password!')) return '' def clean_confirmation(self): confirmation = self.cleaned_data['confirmation'] if confirmation != self.CONFIRMATION_PHRASE: raise forms.ValidationError( _('You did not type the confirmation phrase exactly right!')) return ''
class PublicBodyForm(forms.Form): name = forms.CharField(label=_("Name of Public Body")) description = forms.CharField(label=_("Short description"), widget=forms.Textarea, required=False) email = forms.EmailField(widget=forms.EmailInput, label=_("Email Address for Freedom of Information Requests")) url = forms.URLField(label=_("Homepage URL of Public Body"))
class MessageSearchForm(forms.Form): """ Formulaire de recherche de messages """ query = forms.CharField(max_length=128, required=False) ip = forms.GenericIPAddressField(required=False) q = forms.CharField(max_length=48, required=False) when = forms.DateTimeField(widget=SelectDateWidget( years=range(2010, 2012)))
class SignUpForm(forms.ModelForm): error_messages = { 'duplicate_email': _("A user with that email already exists."), 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput, help_text=_("Enter the same password as above," " for verification.")) class Meta: model = Person fields = ('email', 'first_name', 'middle_name', 'last_name', 'name_order') def __init__(self, request, *args, **kwargs): self.request = request super(SignUpForm, self).__init__(*args, **kwargs) def clean_email(self): # Since Person.email is unique, this check is redundant, # but it sets a nicer error message. email = self.cleaned_data["email"] q = models.Q(email=email) | models.Q(confirmed_email=email) if Person._default_manager.filter(q).exists(): raise ValidationError( self.error_messages['duplicate_email'], code='duplicate_email', ) return email def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def save(self): person = super(SignUpForm, self).save(commit=False) person.set_password(self.cleaned_data["password1"]) person.save() if 'email' in self.changed_data: ConfirmationMailer(person=self.instance, site=get_current_site(self.request), secure=self.request.is_secure()).send( [self.instance.email]) user = authenticate(email=self.cleaned_data['email'], password=self.cleaned_data['password1']) login(self.request, user) return person
class FormWithCity(BetterBsForm, _CityBasedForm): """Form with city""" country = forms.ChoiceField(required=False, label=_('Country')) zip_code = forms.CharField(required=False, label=_('zip code')) city = forms.CharField(required=False, label=_('City')) def __init__(self, *args, **kwargs): super(FormWithCity, self).__init__(*args, **kwargs) self._post_init(*args, **kwargs)
class NewUserWithPasswordForm(NewUserForm): password = forms.CharField(widget=forms.PasswordInput, label=_('Password')) password2 = forms.CharField(widget=forms.PasswordInput, label=_('Password (repeat)')) def clean(self): cleaned = super(NewUserWithPasswordForm, self).clean() if cleaned['password'] != cleaned['password2']: raise forms.ValidationError(_("Passwords do not match!")) return cleaned
class ContatarAnuncianteForm(forms.Form): imovel_ref = forms.CharField(widget=forms.HiddenInput()) email = forms.EmailField( widget=forms.TextInput(attrs={'placeholder': 'Digite seu email'}), label='E-mail') telefone = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Digite seu telefone'})) nome = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Digite seu nome'}), label='Nome') sobrenome = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Digite seu sobrenome'}), label='Sobrenome') mensagem = forms.CharField( widget=forms.Textarea(attrs={'rows': 3, 'cols': 45, 'placeholder': 'Precisa mais informações do imóvel ou gostaria de agendar uma visita?'}, ), label='Mensagem', required=False) def __init__(self, *args, **kwargs): super(ContatarAnuncianteForm, self).__init__(*args, **kwargs) def clean_telefone(self): telefone = self.cleaned_data['telefone'] # not re.match(r'^(\(\d{2}\)) ?(\d{5}-\d{4}|\d{9}|\d{4}-\d{4}|\d{8})$', # telefone) if len(telefone) < 9: raise forms.ValidationError("Digite um telefone válido.") return telefone def envia_email(self): sender = MagicEmail("{0}".format(settings.DEFAULT_FROM_EMAIL)) current_site = Site.objects.get_current() subject = "[SJC Vale Imóveis] Novo Contato: Ref: {0} ".format( self.cleaned_data['imovel_ref']) data = {'domain': current_site.domain, 'body': subject, 'imovel_ref': self.cleaned_data['imovel_ref'], 'email': self.cleaned_data['email'], 'telefone': self.cleaned_data['telefone'], 'nome': self.cleaned_data['nome'], 'sobrenome': self.cleaned_data['sobrenome'], 'mensagem': self.cleaned_data['mensagem'], 'url': reverse('buscador.lista.imovel_referencia', args=[self.cleaned_data['imovel_ref'], ]), } email_contato = preferences.ImobiliariaPreferences.email_contato sender.using_template( "contato_cliente_imovel", data) \ .with_subject(subject) \ .reply_to(self.cleaned_data['email']) \ .send_to([email_contato, ])
class SimpleForm(forms.Form): name = forms.CharField( max_length=64, widget=widgets.TextInput(attrs={"placeholder": "Jane Doe"}) ) email = forms.CharField( max_length=128, widget=widgets.TextInput(attrs={"placeholder": "*****@*****.**"}), ) tos = forms.BooleanField( label="", widget=SwitchInput(), help_text="Terms of Service" )
class CredentialsForm(ServiceForm): """A form that checks an external service using Basic Auth on a URL""" username = forms.CharField(label=_('Username')) password = forms.CharField(label=_('Password'), widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(CredentialsForm, self).__init__(*args, **kwargs) if self.service == 'instapaper': self.fields['username'].help_text = _('Your Instapaper username ' 'is an email address.') def check_readitlater(self): """Checks that the readitlater credentials are valid""" data = self.cleaned_data data['apikey'] = settings.API_KEYS['readitlater'] response = requests.get('https://readitlaterlist.com/v2/auth', params=data) if response.status_code != 200: raise forms.ValidationError( _('Unable to verify your readitlaterlist credentials. Please ' 'double-check and try again.')) self.user.read_later_credentials = json.dumps(self.cleaned_data) def check_instapaper(self): """Get an OAuth token using xAuth from Instapaper""" self.check_xauth( settings.INSTAPAPER['CONSUMER_KEY'], settings.INSTAPAPER['CONSUMER_SECRET'], 'https://www.instapaper.com/api/1/oauth/access_token', ) def check_readability(self): """Get an OAuth token using the Readability API""" self.check_xauth( settings.READABILITY['CONSUMER_KEY'], settings.READABILITY['CONSUMER_SECRET'], 'https://www.readability.com/api/rest/v1/oauth/access_token/', ) def check_xauth(self, key, secret, token_url): """Check a generic xAuth provider""" auth = OAuth1(key, secret) params = { 'x_auth_username': self.cleaned_data['username'], 'x_auth_password': self.cleaned_data['password'], 'x_auth_mode': 'client_auth', } response = requests.post(token_url, auth=auth, data=params) if response.status_code != 200: raise forms.ValidationError( _("Unable to verify your %s credentials. Please double-check " "and try again") % self.service, ) request_token = dict(urlparse.parse_qsl(response.text)) self.user.read_later_credentials = json.dumps(request_token)
class LecturerSignUpForm(UserCreationForm): # Declare user option fields to form first_name = forms.CharField(required=True, widget=forms.TextInput( attrs={'placeholder': 'First name'})) other_name = forms.CharField(required=True, widget=forms.TextInput( attrs={'placeholder': 'Other name'})) last_name = forms.CharField(required=True, widget=forms.TextInput( attrs={'placeholder': 'Surname '})) birth_place = forms.ChoiceField(required=True, choices=STATES) sex = forms.ChoiceField(required=True, choices=GENDER) birth_date = forms.DateField(required=True, widget=forms.DateInput) email = forms.EmailField(widget=forms.EmailInput( attrs={'placeholder': 'Enter email address'}), required=True) phone = forms.CharField(required=True, widget=forms.PhoneNumberInput( attrs={'placeholder': 'Mobile Number'})) address = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'House/Street/City/Town '}), max_length=100) faculty = forms.ModelChoiceField( queryset=Faculty.objects.all(), required=False) class Meta: model = User fields = ('first_name', 'other_name', 'last_name', 'sex', 'birth_place', 'address', 'phone', 'email', 'faculty', 'birth_date', 'username',) # Add placeholder to UserCreationForm fields def __init__(self, *args, **kwargs): super(LecturerSignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'placeholder': 'Choose A Unique Username'}) self.fields['password1'].widget.attrs.update( {'placeholder': 'Choose A Password'}) self.fields['password2'].widget.attrs.update( {'placeholder': 'Verify Password'}) # Check if inputted email has not been used by another user def clean_email(self): email = self.cleaned_data['email'] check = User.objects.values('email') if email in check: msg = 'this email has been used!' self.add_error('email', msg) return email def save(self, commit=True): user = super().save(commit=False) user.is_lecturer = True if commit: user.save() # Create lecturer object with user id Lecturer.objects.create(user=user) return user
def __init__(self, *args, **kwargs): self.instance = kwargs.get('instance') super(EditGroupForm, self).__init__(*args, **kwargs) self.fields['entities'] = forms.CharField( widget=forms.HiddenInput(), initial=[elt.id for elt in self.instance.entities.all()] if self.instance.id else [], required=False, ) self.fields['contacts'] = forms.CharField( widget=forms.HiddenInput(), initial=[elt.id for elt in self.instance.contacts.all()] if self.instance.id else [], required=False)
class JobSearchForm(forms.Form): q = forms.CharField( label='What', required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'job title, keywords or tags', }), ) l = forms.CharField( label='Where', required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'job title, keywords or tags', }), ) is_visual_impairment_accepted = forms.BooleanField( label='visual disabilities', required=False, initial=False) is_hearing_impairment_accepted = forms.BooleanField( label='hearing disabilities', required=False, initial=False) is_motor_impairment_accepted = forms.BooleanField( label='motor disabilities', required=False, initial=False) def search(self, jobs): q = self.cleaned_data.get('q') if q: jobs = jobs.filter(title__icontains=q) l = self.cleaned_data.get('l') if l: jobs = jobs.filter(location__icontains=l) impairements_filter = {} for name in [ 'visual', 'hearing', 'motor', ]: impairment = 'is_{}_impairment_accepted'.format(name) value = self.cleaned_data.get(impairment) if value: impairements_filter[impairment] = value if impairements_filter: jobs = jobs.filter(**impairements_filter) return jobs
class ThreadForm(MessageForm): """ Formulaire de fil de discussion """ # Constantes SUBJECT_LENGTH_MIN = 1 # Champs supplémentaires subject = forms.CharField(max_length=48, required=False, widget=forms.TextInput()) recipient = forms.IntegerField(required=True, widget=forms.HiddenInput()) # Validation def clean_subject(self): """ Valider et renvoyer les données du champ sujet """ subject = self.data['subject'] if len(subject) < ThreadForm.SUBJECT_LENGTH_MIN: raise forms.ValidationError( _("Your subject must be at least {} characters long.").format( ThreadForm.SUBJECT_LENGTH_MIN)) return subject def clean_recipient(self): """ Valider et renvoyer les données du champ destinataire """ recipient = int(self.data['recipient']) if get_user_model().objects.get_or_none(id=recipient) is None: raise forms.ValidationError(_("The recipient does not exist.")) return get_user_model().objects.get(id=recipient)
class DeleteAccountForm(forms.Form): password = forms.CharField( widget=forms.PasswordInput, label=_('Password'), help_text=_('Please enter your password to confirm your ownership ' 'of this account.')) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super().__init__(*args, **kwargs) def clean_password(self): password = self.cleaned_data['password'] correct = self.user.check_password(password) if not correct: raise forms.ValidationError( _('The password you entered was ' 'incorrect.')) return password @transaction.atomic def save(self): user_id = self.user.pk self.user.delete() es.client.delete_by_query( index=es.user_alias(user_id), doc_type='entries', body={'query': { 'filtered': { 'filter': { 'match_all': {} } } }}, )
class UndoReadForm(forms.Form): action = forms.ChoiceField( choices=( ('undo-read', 'undo-read'), ), widget=forms.HiddenInput, initial='undo-read', ) pks = forms.CharField(widget=forms.HiddenInput) def __init__(self, user=None, *args, **kwargs): self.user = user super(UndoReadForm, self).__init__(*args, **kwargs) def clean_pks(self): return json.loads(self.cleaned_data['pks']) def save(self): pks = self.cleaned_data['pks'] index = es.user_alias(self.user.pk) ops = [{ '_op_type': 'update', '_index': index, '_type': 'entries', '_id': pk, 'doc': {'read': False}, } for pk in pks] with es.ignore_bulk_error(404, 409): es.bulk(ops, raise_on_error=True, params={'refresh': True}) return len(pks)
class PostalReplyForm(PostalBaseForm): FIELD_ORDER = [ 'public_body', 'sender', 'date', 'subject', 'text', 'files', 'not_publishable' ] PUBLIC_BODY_LABEL = _('Sender public body') sender = forms.CharField( label=_("Sender name"), widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": _("Sender Name") }), required=True) not_publishable = forms.BooleanField( label=_("You are not allowed to publish some received documents"), initial=False, required=False, help_text= _('If the reply explicitly states that you are not allowed to publish some of the documents (e.g. due to copyright), check this.' )) def contribute_to_message(self, message): message.is_response = True message.sender_name = self.cleaned_data['sender'] message.sender_public_body = message.request.public_body message.not_publishable = self.cleaned_data['not_publishable'] return message
class StudentWorkCommentForm(ParticipationCheckHiddenFormMixin, forms.ModelForm): text = forms.CharField(widget=FroalaEditor) class Meta: model = Comment fields = ('title', 'text')
class StudentWorkUpdatePrivateForm(ParticipationCheckHiddenFormMixin, forms.ModelForm): text = forms.CharField(widget=FroalaEditor) class Meta: model = StudentsWork fields = ('title', 'text', 'published')
class ProjectForm(forms.ModelForm): topics = forms.ModelMultipleChoiceField( queryset=Topic.objects.all(), widget=forms.SelectMultiple(attrs={ 'inline': True, 'class': 'multiselect', }), required=False) events = forms.ModelMultipleChoiceField( queryset=Event.objects.all(), widget=forms.SelectMultiple(attrs={ 'inline': True, 'class': 'multiselect', }), required=False) technologies = forms.ModelMultipleChoiceField( queryset=Technology.objects.all(), widget=forms.SelectMultiple(attrs={ 'inline': True, 'class': 'multiselect', }), required=False) color = forms.CharField(widget=forms.TextInput(attrs={ 'inline': True, 'class': 'colorpicker', }), required=False) class Meta: model = Project fields = [ 'title', 'description', 'status', 'public_url', 'dev_url', 'screenshot', 'git_url', 'topics', 'events', 'technologies', 'color' ]
def __init__(self, *args, **kwargs): super(PermissionsForm, self).__init__(*args, **kwargs) for role in Group.objects.all(): for feature in models.Feature.objects.all(): for permission in feature.permissions.all(): is_enabled = role.permissions.filter( pk=permission.pk).exists() name = '-'.join((role.name, feature.name, permission.name)) checkbox = forms.BooleanField( required=False, initial=is_enabled, ) checkbox.role = role checkbox.permission = permission self.fields[name] = checkbox for feature in models.Feature.objects.all(): for permission in feature.permissions.all(): users = User.objects.filter( user_permissions=permission).values_list('username', flat=True) users = '|'.join(users) name = '%s-%s' % (permission.content_type_id, permission.codename) self.fields[name] = forms.CharField(required=False, initial=users) self.fields[name].permission = permission