[Python] How to customize {% bootstrap_form form %} in django?

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    There is Problem

    Hello I'm creating a project, I created a register form, but I tried to create an email authentication submit button in the form near EmailInput, but I could not find it I'm currently using {% bootstrap_form form%} to render automatically in a register form

    What I want

    I would like to have the Submit Email Authentication button appear on the form near EmailInput,

    When the user clicks the Send Email Authentication button, it sends an authentication email to the user's email

    Then, when the user clicks the link attached to the mail, the user is informed that the confirmation has been made on the register window and When the user clicks the sign up button, the registration is completed

    What I've tried

    I created a register form using UserCreationForm supported by django, I tested using gmail smtp to send email from django. It works well

    The Code in /django-blog/blog/settings.py

    import os

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = 'y$a)3faq3*h#r0g5b^cxsw^lgdxbbu&#lsqek!_0ju+d*c!ups'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = ['localhost']


    # Application definition

    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 내가 만든 앱
    'my_blog',
    #USER APP
    'users',

    # Apps created by others
    'bootstrap3',

    # Restful api Framework
    'rest_framework',
    # Social
    'social_django',
    "social_core",

    ]

    MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'social_django.middleware.SocialAuthExceptionMiddleware',
    ]

    ROOT_URLCONF = 'blog.urls'

    TEMPLATES = [
    {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'blog/templates')],
    'APP_DIRS': True,
    'OPTIONS': {
    'context_processors': [
    'django.template.context_processors.debug',
    'django.template.context_processors.request',
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'social_django.context_processors.backends',
    'social_django.context_processors.login_redirect',
    ],
    },
    },
    ]

    WSGI_APPLICATION = 'blog.wsgi.application'


    # Database
    # https://docs.djangoproject.com/en/2.1/ref/settings/#databases

    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
    }


    # Password validation
    # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
    {
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
    ]


    # Internationalization
    # https://docs.djangoproject.com/en/2.1/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True


    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.1/howto/static-files/

    STATIC_URL = '/static/'

    # 내 설정
    LOGIN_URL = '/users/login/'

    # django-bootstrap3 settings
    BOOTSTRAP3 = {
    'include_jquery' : True,
    }

    # Heroku settings

    cwd = os.getcwd()
    if cwd == '/app' or cwd[:4] == '/tmp':
    import dj_database_url
    DATABASES = {
    'default': dj_database_url.config(default='postgres://localhost')
    }

    # request.is_secure()에 대해 'X-Forwarded-Proto'를 우선적으로 사용한다.
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

    # 모든 호스트 헤더를 허용한다.
    ALLOWED_HOSTS = ['choco-blog.herokuapp.com']

    DEBUG = False

    # Static asset configuration
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    STATIC_ROOT = 'staticfiles'
    STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    )

    # AUTHENTICATION_BACKENDS settings
    AUTHENTICATION_BACKENDS = [
    'social_core.backends.open_id.OpenIdAuth', # for Google authentication
    'social_core.backends.google.GoogleOpenId', # for Google authentication
    'social_core.backends.google.GoogleOAuth2', # for Google authentication
    'social_core.backends.github.GithubOAuth2', # for Github authentication
    'social_core.backends.kakao.KakaoOAuth2', # for Kakaotlak authentication

    'django.contrib.auth.backends.ModelBackend', # Django 기본 유저모델
    ]

    SOCIAL_AUTH_URL_NAMESPACE = 'social'
    LOGIN_REDIRECT_URL='/'

    # Google login
    SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ='843562355161-3atsmmageh4j0758g4am6e4ncefckupf.apps.googleusercontent.com'
    SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET ='ZVKObQDFPhTdz1GXWfaYuulq'
    # Github Login
    SOCIAL_AUTH_GITHUB_KEY = 'e2fc4a9cf1f213b0a10f'
    SOCIAL_AUTH_GITHUB_SECRET = 'c4d1efe407175230a47d7fa547db0667b4f08721'

    # Kakaotalk login
    SOCIAL_AUTH_KAKAO_KEY = '490c43bc63dd3351e6068f6bbf4e0bfd'

    # Verification Email settings
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_USE_TLS = 'True'
    EMAIL_PORT = 587
    EMAIL_HOST = 'smtp.gmail.com'
    EMAIL_HOST_USER = 'user@gmail.com'
    EMAIL_HOST_PASSWORD = os.environ.get('KBOARD_PASSWORD')
    SERVER_EMAIL = 'user@gmail.com'
    DEFAULT_FROM_MAIL = 'my_blog'


    /django-blog/user/forms.py

    from django import forms
    from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
    from django.contrib.auth.models import User

    class UserCreationForm(UserCreationForm):
    """유저 가입양식 정의"""
    first_name = forms.CharField(widget = forms.TextInput(
    attrs={'class': 'form-control', 'placeholder': 'First Name'}),
    max_length=32, help_text='First name', label='이름')

    last_name = forms.CharField(widget =
    forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'}),
    max_length=32, help_text='Last name', label='성')

    email = forms.EmailField(widget = forms.EmailInput(attrs=
    {'class':'form-control', 'placeholder': 'Email',}),
    max_length=64, help_text='유효한 이메일 주소를 입력하세요',
    error_messages={'invalid': ("Email 이 비어있습니다")},)

    terms = forms.BooleanField(
    label =('My blog of service'),
    widget=forms.CheckboxInput(
    attrs={
    'required': 'True',
    }
    ),
    error_messages={
    'required':('당신의 My blog of service 에 대한 동의가 필요합니다. ')
    }
    )

    privacy = forms.BooleanField(
    label=('Privacy policy'),
    widget=forms.CheckboxInput(
    attrs={
    'required':'True',
    }
    ),
    error_messages={
    'required=':('당신의 Privacy policy 동의가 필요합니다.')
    }
    )

    class Meta(UserCreationForm.Meta):
    model = User
    fields = UserCreationForm.Meta.fields + ('first_name',
    'last_name', 'email')


    /django-blog/user/urls.py

    """users 앱의 URL 패턴을 정의하는 파일"""

    from django.urls import re_path
    from django.contrib.auth import views as auth_views

    from . import views

    app_name = 'users'

    urlpatterns = [
    # 로그인 페이지
    re_path(r'^login/$',
    auth_views.LoginView.as_view(template_name='users/login.html'),
    name = 'login'),

    # 로그아웃 페이지
    re_path(r'^logout/$',views.logout_view, name='logout'),

    # 유저 등록 페이지
    re_path(r'^register/$', views.register, name='register'),
    ]


    /django-blog/user/templates/user/register.html

    {% extends "my_blog/base.html" %}
    {% load bootstrap3 %}

    {% block header %}
    <h2>회원가입</h2>
    {% endblock %}

    {% block content %}

    <form method='post' action="{% url 'users:register' %}" class="form">
    {% csrf_token %}
    {% bootstrap_form form %}

    {% buttons %}
    <button name="submit" class="btn btn-success">유저 등록하기</button>
    {% endbuttons %}
    <input type="hidden" name="text" value="{% url 'my_blog:index' %}">
    </form>
    {% endblock %}


    /django-blog/user/views.py

    from django.shortcuts import render
    from django.urls import reverse
    from django.contrib.auth import login, logout, authenticate
    from django.http import HttpResponseRedirect
    from .forms import UserCreationForm


    def logout_view(request):
    """사용자 로그아웃"""
    logout(request)
    return HttpResponseRedirect(reverse('my_blog:index'))

    def register(request):
    """새 사용자를 등록한다."""
    if request.method != 'POST':
    # 빈 폼을 보여준다.
    form = UserCreationForm()
    else:
    # 전송받은 폼을 처리한다.
    form =UserCreationForm(data = request.POST)

    if form.is_valid():
    new_user = form.save()
    # 사용자를 로그인시키고 홈페이지로 리다이렉트한다.
    authenticated_user = authenticate(username=new_user.username,
    password=request.POST['password1'])
    login(request, authenticated_user)
    return HttpResponseRedirect(reverse('my_blog:index'))

    context = {'form' : form}
    return render(request, 'users/register.html', context)


    I have attached a register screen photo enter image description here

    If you need information to solve this problem, please ask me :)

    Continue reading...

Compartilhe esta Página