前提・実現したいこと
djangoの会員情報を入力後に入力したアドレスに、
本登録用のURLを送信してそのURLにアクセスしたいのですが、
TypeErrorが発生しています。
エラー内容は、通常__init __()には一つの引数だが、二つの引数が指定されたための様な
ことが書いてあるのですが、コードのどこを書き換えれば良いのかわかりません。
発生している問題・エラーメッセージ
TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: /Users/ユーザー名/.local/share/virtualenvs/config-7no8nuUI/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response,
TrackBack
response = wrapped_callback(request, *callback_args, **callback_kwargs)
views.py
from django.shortcuts import render from django.views import generic from .models import * from django.contrib.auth.views import LoginView from .forms import LoginForm,SignUPForm from django.contrib.sites.shortcuts import get_current_site from django.core.signing import dumps,SignatureExpired,BadSignature,loads from django.template.loader import get_template from django.contrib import messages from django.http import HttpResponseRedirect,HttpResponseBadRequest from django.urls import reverse from django.conf import settings # Create your views here. class Lp(generic.TemplateView): template_name = 'ec/lp.html' def get_context_data(self,**kwargs): context = super().get_context_data() context = { 'items':Product.objects.all(), } return context class ItemList(generic.ListView): model = Product template_name = 'ec/item_list.html' def get_queryset(self): queryset = Product.objects.all() if "keyword" in self.request.GET and self.request.GET['keyword'] != None: keyword = self.request.GET['keyword'] queryset = Product.objects.filter(name__icontains=keyword) return queryset class ItemDetail(generic.DetailView): model = Product template_name = 'ec/item_detail.html' class Login(LoginView): form_class = LoginForm template_name = 'ec/login.html' class SignUp(generic.CreateView): template_name = 'ec/signup.html' model = User form_class = SignUPForm def form_valid(self,form): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) domain = current_site.domain context = { 'protocol':self.request.scheme, 'domain':domain, 'token':dumps(user.pk), 'user':user, } subject_template = get_template('ec/mail_template/signup/subject.txt') subject = subject_template.render(context).strip()#これがないとBudHeadErrorになる。改行を削除。 message_template = get_template('ec/mail_template/signup/message.txt') message = message_template.render(context) user.email_user(subject,message) messages.success(self.request,'本登録用のリンクを送付しました。') return HttpResponseRedirect(reverse('ec:signup')) class SignUpDone(generic.TemplateView): template_name = 'ec/signup_done.html' timeout_seconds = getattr(settings,'ACTIVATION_TIMEOUT_SECONDS',60*60*24) def get(self,request,**kwargs): token = kwargs.get('token') try: user_pk = loads(token,max_age=self.timeout_seconds) except SignatureExpired: return HttpResponseBadRequest() except BadSignature: return HttpResponseBadRequest() else: try: user = User.objects.get(pk=user_pk) except User.DoesNotExist: return HttpResponseBadRequest() else: if not user.is_active: user.active = True user.save() return super().get(request,**kwargs) return HttpResponseBadRequest()
models.py
from django.db import models from django.contrib.auth.base_user import BaseUserManager,AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ from django.utils import timezone # Create your models here. class Product(models.Model): class Meta: db_table = 'product' verbose_name ='商品' verbose_name_plural = '商品' thumbnail = models.ImageField(verbose_name='商品画像',upload_to='thumbnails/') name = models.CharField(verbose_name='名前',max_length=255,blank=False,null=False) price = models.IntegerField(verbose_name='価格') description = models.TextField(verbose_name='商品説明') class MyUserManager(BaseUserManager): use_in_migrations = True #"""ユーザーマネージャー.""" def _create_user(self,email,password,**extra_fields): #"""メールアドレスでの登録を必須にする""" if not email: raise ValueError('The given imail must be set') user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self,email,password=None,**extra_fields): #"""is_staff(管理サイトにログインできるか)と、is_superuer(全ての権限)をFalseに""" extra_fields.setdefault('is_staff',False) extra_fields.setdefault('is_superuser',False) return self._create_user(email,password,**extra_fields) def create_superuser(self,email,password,**extra_fields): #"""スーパーユーザーは、is_staffとis_superuserをTrueに""" extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) if extra_fields.get('is_staff') is not True: raise ValueError('superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('superuser must have is_superuser=True.') return self._create_user(email,password,**extra_fields) class User(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name = 'ユーザー' verbose_name_plural = 'ユーザー' #"""カスタムユーザーモデル.""" email = models.EmailField('メールアドレス',max_length=150,null=False,blank=False,unique=True) name = models.CharField('名前',max_length=150,null=False,blank=False) is_staff = models.BooleanField( '管理者', default = False, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( '有効', default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'),default=timezone.now) objects = MyUserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def email_user(self,subject,message,from_email=None,**kwargs): #"""Send an email to this user.""" send_mail(subject,message,from_email,[self.email],**kwargs) @property def username(self): """username属性のゲッター 他アプリケーションが、username属性にアクセスした場合に備えて定義 メールアドレスを返す """ return self.email
forms.py
from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import AuthenticationForm,UserCreationForm from .models import * from django.core.exceptions import ValidationError class LoginForm(AuthenticationForm): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['placeholder'] = field.label class SignUPForm(UserCreationForm): class Meta: model = User fields = ('email','name') def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['placeholder'] = field.label
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = '自分のアドレス@gmail.com' EMAIL_HOST_PASSWORD = 'パスワード' EMAIL_USE_TLS = True
補足情報(FW/ツールのバージョンなど)
python3.7.3
django2.2
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。