質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

1964閲覧

djangoの自作したカスタムユーザーモデルにユーザー情報が保存されない

omyu

総合スコア22

Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2019/10/08 13:43

編集2019/10/10 02:55

djangoでUserというカスタムユーザーモデルを作り、djangoの管理画面にもそのカスタムユーザーモデルが適用されているのですが、views.pyのregister関数が呼び出すフォームで送信してもデータベースに保存されません。
どうすれば保存できるようになるか、また、UserCreationFormを継承するとパスワード入力欄が3つ出てきてしまうのですが、2つか1つにする方法も教えていただけると嬉しいです。

python

1 2###views.py 3 4from django.shortcuts import render, redirect, get_object_or_404 5from django.views.generic import CreateView, DeleteView 6from django.urls import reverse_lazy 7from django.http import HttpResponse 8from django.contrib.auth import authenticate, login, logout, get_user_model 9from django.contrib.auth.decorators import login_required 10 11User = get_user_model() 12 13from .forms import UserCreateForm 14from .models import User 15 16 17# Create your views here. 18 19def register(request): 20 21 if request.method == 'POST': 22 form = UserCreateForm(request.POST) 23 if form.is_valid(): 24 email = form.cleaned_data.get('email') 25 password = form.cleaned_data.get('password') 26 location = form.cleaned_data.get('location') 27 user = User.objects.create_user(email, password, location) 28 user.save() 29 return redirect('register_comp') 30 31 32 return render(request, 'register.html', {'form': UserCreateForm()}) 33

python

1 2###models.py 3 4from django.db import models 5from django.core.mail import send_mail 6from django.contrib.auth.models import PermissionsMixin 7from django.contrib.auth.base_user import AbstractBaseUser 8from django.utils.translation import ugettext_lazy as _ 9from django.utils import timezone 10from django.contrib.auth.base_user import BaseUserManager 11 12 13class UserManager(BaseUserManager): 14 """ユーザーマネージャー.""" 15 16 use_in_migrations = True 17 18 def _create_user(self, email, password, **extra_fields): 19 """Create and save a user with the given username, email, and 20 password.""" 21 if not email: 22 raise ValueError('The given email must be set') 23 email = self.normalize_email(email) 24 25 user = self.model(email=email, **extra_fields) 26 user.set_password(password) 27 user.save(using=self._db) 28 return user 29 30 def create_user(self, email, password=None, **extra_fields): 31 extra_fields.setdefault('is_staff', False) 32 extra_fields.setdefault('is_superuser', False) 33 return self._create_user(email, password, **extra_fields) 34 35 def create_superuser(self, email, password, **extra_fields): 36 extra_fields.setdefault('is_staff', True) 37 extra_fields.setdefault('is_superuser', True) 38 39 if extra_fields.get('is_staff') is not True: 40 raise ValueError('Superuser must have is_staff=True.') 41 if extra_fields.get('is_superuser') is not True: 42 raise ValueError('Superuser must have is_superuser=True.') 43 44 return self._create_user(email, password, **extra_fields) 45 46 47LOCATION = (('130010', '東京'), ('230010', '名古屋'), ('270000', '大阪'), ('400010', '福岡')) 48class User(AbstractBaseUser, PermissionsMixin): 49 """カスタムユーザーモデル.""" 50 51 email = models.EmailField(_('email address'), unique=True) 52 first_name = models.CharField(_('first name'), max_length=30, blank=True) 53 last_name = models.CharField(_('last name'), max_length=150, blank=True) 54 location = models.CharField( 55 '住所', 56 max_length = 20, 57 choices = LOCATION 58 ) 59 60 is_staff = models.BooleanField( 61 _('staff status'), 62 default=False, 63 help_text=_( 64 'Designates whether the user can log into this admin site.'), 65 ) 66 is_active = models.BooleanField( 67 _('active'), 68 default=True, 69 help_text=_( 70 'Designates whether this user should be treated as active. ' 71 'Unselect this instead of deleting accounts.' 72 ), 73 ) 74 date_joined = models.DateTimeField(_('date joined'), default=timezone.now) 75 76 objects = UserManager() 77 78 EMAIL_FIELD = 'email' 79 USERNAME_FIELD = 'email' 80 REQUIRED_FIELDS = [] 81 82 class Meta: 83 verbose_name = _('user') 84 verbose_name_plural = _('users') 85 86 def get_full_name(self): 87 """Return the first_name plus the last_name, with a space in 88 between.""" 89 full_name = '%s %s' % (self.first_name, self.last_name) 90 return full_name.strip() 91 92 def get_short_name(self): 93 """Return the short name for the user.""" 94 return self.first_name 95 96 def email_user(self, subject, message, from_email=None, **kwargs): 97 """Send an email to this user.""" 98 send_mail(subject, message, from_email, [self.email], **kwargs) 99 100 101

python

1 2###forms.py 3 4from django import forms 5from django.contrib.auth.forms import UserCreationForm 6from django.contrib.auth import get_user_model 7User = get_user_model() 8 9 10 11class UserCreateForm(UserCreationForm): 12 password = forms.CharField(widget=forms.PasswordInput) 13 password1 = forms.CharField(required=False) 14 password2 = password1 15 16 class Meta: 17 model = User 18 fields = ('email', 'password', 'location') 19 20

python

1""" 2Django settings for weathermailproject project. 3 4Generated by 'django-admin startproject' using Django 2.2.5. 5 6For more information on this file, see 7https://docs.djangoproject.com/en/2.2/topics/settings/ 8 9For the full list of settings and their values, see 10https://docs.djangoproject.com/en/2.2/ref/settings/ 11""" 12 13import os 14 15# Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 18 19# Quick-start development settings - unsuitable for production 20# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 22# SECURITY WARNING: keep the secret key used in production secret! 23SECRET_KEY = '_3&*rp@a@yxu1_8%w%rw7qh7&^@57#15s6(mbep2(1&!nl8=+h' 24 25# SECURITY WARNING: don't run with debug turned on in production! 26DEBUG = True 27 28ALLOWED_HOSTS = [] 29 30 31# Application definition 32 33INSTALLED_APPS = [ 34 'django.contrib.admin', 35 'django.contrib.auth', 36 'django.contrib.contenttypes', 37 'django.contrib.sessions', 38 'django.contrib.messages', 39 'django.contrib.staticfiles', 40 'weathermail', 41] 42 43MIDDLEWARE = [ 44 'django.middleware.security.SecurityMiddleware', 45 'django.contrib.sessions.middleware.SessionMiddleware', 46 'django.middleware.common.CommonMiddleware', 47 'django.middleware.csrf.CsrfViewMiddleware', 48 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 'django.contrib.messages.middleware.MessageMiddleware', 50 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51] 52 53ROOT_URLCONF = 'weathermailproject.urls' 54 55TEMPLATES = [ 56 { 57 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 'DIRS': [BASE_DIR, 'templates'], 59 'APP_DIRS': True, 60 'OPTIONS': { 61 'context_processors': [ 62 'django.template.context_processors.debug', 63 'django.template.context_processors.request', 64 'django.contrib.auth.context_processors.auth', 65 'django.contrib.messages.context_processors.messages', 66 ], 67 }, 68 }, 69] 70 71WSGI_APPLICATION = 'weathermailproject.wsgi.application' 72 73 74# Database 75# https://docs.djangoproject.com/en/2.2/ref/settings/#databases 76 77DATABASES = { 78 'default': { 79 'ENGINE': 'django.db.backends.sqlite3', 80 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 } 82} 83 84 85# Password validation 86# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 87 88AUTH_PASSWORD_VALIDATORS = [ 89 { 90 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 }, 92 { 93 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 }, 95 { 96 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 }, 98 { 99 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 }, 101] 102 103 104# Internationalization 105# https://docs.djangoproject.com/en/2.2/topics/i18n/ 106 107LANGUAGE_CODE = 'ja' 108 109TIME_ZONE = 'Asia/Tokyo' 110 111USE_I18N = True 112 113USE_L10N = True 114 115USE_TZ = True 116 117 118# Static files (CSS, JavaScript, Images) 119# https://docs.djangoproject.com/en/2.2/howto/static-files/ 120 121STATIC_URL = '/static/' 122 123LOGIN_URL = 'login' 124 125AUTH_USER_MODEL = 'weathermail.User' 126

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問