Skip to content

Commit 0a7935a

Browse files
committed
add another django forms example code block
1 parent 9a924bb commit 0a7935a

File tree

2 files changed

+159
-0
lines changed

2 files changed

+159
-0
lines changed

content/pages/examples/django/django-forms.markdown

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,3 +454,161 @@ FILTER_FUNCS = {
454454
~~ current_row.insert(0, current_entry)
455455
~~ yield current_row
456456
```
457+
458+
459+
## Example 2 from django-allauth
460+
[django-allauth](https://github.com/pennersr/django-allauth)
461+
([project website](https://www.intenct.nl/projects/django-allauth/)) is a
462+
[Django](/django.html) code library for easily adding local and social
463+
authentication flows to Django projects. Its code is available as open
464+
source under the
465+
[MIT License](https://github.com/pennersr/django-allauth/blob/master/LICENSE).
466+
467+
[**django-allauth/allauth/account/forms.py**](https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py)
468+
469+
```python
470+
from __future__ import absolute_import
471+
472+
import warnings
473+
from importlib import import_module
474+
475+
~~from django import forms
476+
from django.contrib.auth.tokens import PasswordResetTokenGenerator
477+
from django.contrib.sites.shortcuts import get_current_site
478+
from django.core import exceptions, validators
479+
from django.urls import reverse
480+
from django.utils.translation import pgettext
481+
482+
from allauth.compat import ugettext, ugettext_lazy as _
483+
484+
from ..utils import (
485+
build_absolute_uri,
486+
get_username_max_length,
487+
set_form_field_order,
488+
)
489+
from . import app_settings
490+
from .adapter import get_adapter
491+
from .app_settings import AuthenticationMethod
492+
from .models import EmailAddress
493+
from .utils import (
494+
filter_users_by_email,
495+
get_user_model,
496+
perform_login,
497+
setup_user_email,
498+
sync_user_email_addresses,
499+
url_str_to_user_pk,
500+
user_email,
501+
user_pk_to_url_str,
502+
user_username,
503+
)
504+
505+
506+
class EmailAwarePasswordResetTokenGenerator(PasswordResetTokenGenerator):
507+
508+
def _make_hash_value(self, user, timestamp):
509+
ret = super(
510+
EmailAwarePasswordResetTokenGenerator, self)._make_hash_value(
511+
user, timestamp)
512+
sync_user_email_addresses(user)
513+
emails = set([user.email] if user.email else [])
514+
emails.update(
515+
EmailAddress.objects
516+
.filter(user=user)
517+
.values_list('email', flat=True))
518+
ret += '|'.join(sorted(emails))
519+
return ret
520+
521+
522+
default_token_generator = EmailAwarePasswordResetTokenGenerator()
523+
524+
525+
class PasswordVerificationMixin(object):
526+
def clean(self):
527+
cleaned_data = super(PasswordVerificationMixin, self).clean()
528+
password1 = cleaned_data.get('password1')
529+
password2 = cleaned_data.get('password2')
530+
if (password1 and password2) and password1 != password2:
531+
self.add_error(
532+
'password2', _("You must type the same password each time.")
533+
)
534+
return cleaned_data
535+
536+
537+
~~class PasswordField(forms.CharField):
538+
539+
~~ def __init__(self, *args, **kwargs):
540+
~~ render_value = kwargs.pop('render_value',
541+
~~ app_settings.PASSWORD_INPUT_RENDER_VALUE)
542+
~~ kwargs['widget'] = forms.PasswordInput(render_value=render_value,
543+
~~ attrs={'placeholder':
544+
~~ kwargs.get("label")})
545+
~~ super(PasswordField, self).__init__(*args, **kwargs)
546+
547+
548+
class SetPasswordField(PasswordField):
549+
550+
def __init__(self, *args, **kwargs):
551+
super(SetPasswordField, self).__init__(*args, **kwargs)
552+
self.user = None
553+
554+
def clean(self, value):
555+
value = super(SetPasswordField, self).clean(value)
556+
value = get_adapter().clean_password(value, user=self.user)
557+
return value
558+
559+
560+
~~class LoginForm(forms.Form):
561+
562+
~~ password = PasswordField(label=_("Password"))
563+
~~ remember = forms.BooleanField(label=_("Remember Me"),
564+
~~ required=False)
565+
566+
~~ user = None
567+
~~ error_messages = {
568+
~~ 'account_inactive':
569+
~~ _("This account is currently inactive."),
570+
571+
~~ 'email_password_mismatch':
572+
~~ _("The e-mail address and/or password you specified are not correct."),
573+
574+
~~ 'username_password_mismatch':
575+
~~ _("The username and/or password you specified are not correct."),
576+
~~ }
577+
578+
~~ def __init__(self, *args, **kwargs):
579+
~~ self.request = kwargs.pop('request', None)
580+
~~ super(LoginForm, self).__init__(*args, **kwargs)
581+
~~ if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL:
582+
~~ login_widget = forms.TextInput(attrs={'type': 'email',
583+
~~ 'placeholder':
584+
~~ _('E-mail address'),
585+
~~ 'autofocus': 'autofocus'})
586+
~~ login_field = forms.EmailField(label=_("E-mail"),
587+
~~ widget=login_widget)
588+
~~ elif app_settings.AUTHENTICATION_METHOD \
589+
~~ == AuthenticationMethod.USERNAME:
590+
~~ login_widget = forms.TextInput(attrs={'placeholder':
591+
~~ _('Username'),
592+
~~ 'autofocus': 'autofocus'})
593+
~~ login_field = forms.CharField(
594+
~~ label=_("Username"),
595+
~~ widget=login_widget,
596+
~~ max_length=get_username_max_length())
597+
~~ else:
598+
~~ assert app_settings.AUTHENTICATION_METHOD \
599+
~~ == AuthenticationMethod.USERNAME_EMAIL
600+
~~ login_widget = forms.TextInput(attrs={'placeholder':
601+
~~ _('Username or e-mail'),
602+
~~ 'autofocus': 'autofocus'})
603+
~~ login_field = forms.CharField(label=pgettext("field label",
604+
~~ "Login"),
605+
~~ widget=login_widget)
606+
~~ self.fields["login"] = login_field
607+
~~ set_form_field_order(self, ["login", "password", "remember"])
608+
~~ if app_settings.SESSION_REMEMBER is not None:
609+
~~ del self.fields['remember']
610+
611+
# source file continues from here with a few more good forms examples
612+
```
613+
614+

theme/templates/table-of-contents.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ <h2>Example Code</h2>
217217
<h3>Django examples</h3>
218218
<h4 class="bp"><a href="/django-conf-urls-url-examples.html">django.conf.urls.url</a></h4>
219219
<h4 class="bp"><a href="/django-db-models-signal-examples.html">django.db.models.signal</a></h4>
220+
<h4 class="bp"><a href="/django-forms-examples.html">django.forms</a></h4>
220221
<h4 class="bp"><a href="/django-dispatch-dispatcher-signal-examples.html">django.dispatch.dispatcher.Signal</a></h4>
221222

222223
<br>

0 commit comments

Comments
 (0)