smtplib.SMTPConnectError: (421, b'Service not available') event after 2-step verification and used generated app password as the HOST_USER_PASSWORD - django

I am trying to incorporate email confirmation to user registration in my project. The user is supposed to get a confirmation link in their email before successful registration. To achieve this, I used django.core.mail.backends.smtp.EmailBackend as the email backend but I got the error below:
Internal Server Error: /account/register/
Traceback (most recent call last):
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\handlers\base.py", line 197, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\lenovo\Desktop\ecommerce4\account\views.py", line 88, in account_register
user.email_user(subject=subject, message=message)
File "C:\Users\lenovo\Desktop\ecommerce4\account\models.py", line 59, in email_user
send_mail(
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail_init.py", line 87, in send_mail
return mail.send()
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail\message.py", line 298, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail\backends\smtp.py", line 124, in send_messages
new_conn_created = self.open()
File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail\backends\smtp.py", line 80, in open
self.connection = self.connection_class(
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 258, in init
raise SMTPConnectError(code, msg)
smtplib.SMTPConnectError: (421, b'Service not available')
I allowed two step authentication to my gmail account and then created app password. I used the app password generated for my account as the HOST_USER_PASSWORD
Below is the code how I configured the the setings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER='my gmail'
EMAIL_HOST_PASSWORD='the generated app password'
EMAIL_PORT=587
EMAIL_USE_TLS=True
Below is the model.py for user
import uuid
from django.conf import settings
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager,
PermissionsMixin)
from django.core.mail import send_mail
from django.db import models
from django.utils.translation import gettext_lazy as _
class Customer(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
name = models.CharField(max_length=150)
mobile = models.CharField(max_length=20, blank=True)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
class Meta:
verbose_name = "Accounts"
verbose_name_plural = "Accounts"
def email_user(self, subject, message):
send_mail(
subject,
message,
settings.EMAIL_HOST_USER,
[self.email],
fail_silently=False,
)
def __str__(self):
return self.name:
The view for user registration
from django.contrib import messages
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.sites.shortcuts import get_current_site
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.encoding import force_bytes, force_str
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from orders.models import Order
from orders.views import user_orders
from store.models import Product
from .forms import RegistrationForm, UserAddressForm, UserEditForm
from .models import Address, Customer
from .tokens import account_activation_token
def account_register(request):
if request.user.is_authenticated:
return redirect("account:dashboard")
if request.method == "POST":
registerForm = RegistrationForm(request.POST)
if registerForm.is_valid():
user = registerForm.save(commit=False)
user.email = registerForm.cleaned_data["email"]
user.set_password(registerForm.cleaned_data["password"])
current_site = get_current_site(request)
subject = "Activate your Account"
message = render_to_string(
"account/registration/account_activation_email.html",
{
"user": user,
"domain": current_site.domain,
"uid": urlsafe_base64_encode(force_bytes(user.pk)),
"token": account_activation_token.make_token(user),
},
)
user.email_user(subject=subject, message=message)
user.is_active = False
user.save()
return render(request, "account/registration/register_email_confirm.html", {"form": registerForm})
else:
registerForm = RegistrationForm()
return render(request, "account/registration/register.html", {"form": registerForm})

Related

How do I view the profile of the authenticated user in Django Rest Framework using the Token

I am learning DRF and creating a simple DRF app that lets user login, and view the profile and update the profile. I am using Django's default User model and using Knox for Token Authentication (if it can be done easier using Django Rest Authentication, please let me know and also tell me the procedure).
I have successfully created the API to register and login the user which works fine, but I am stuck at showing the profile to the Authenticated User through a Token.
I am only one Model that is Details which acts as to store the Profile details of the user. I have LoginSerializer which is connected to Login API and MainUserSerializer & UserSerializer, both of which are connected to User API (which acts to show the Profile details on frontend).
I have tried a lot, searched everywhere, but all they show is how to authenticate the user with token through a url (some thing like using curl https://localhost:8000/api/user... etc.), postman, somehing like http post -a... command in terminal and other ways, but I don't want to test or implement using these ways. I want something that if I open my user profile url after logging in the user using the link localhost:8000/user, then at the backend it should do like following as mentioned here enter link description here:
import requests
url = 'http://127.0.0.1:8000/hello/'
headers = {'Authorization': 'Token 9054f7aa9305e012b3c2300408c3dfdf390fcddf'}
r = requests.get(url, headers=headers)
I have tried really hard, but I am unable to successfully go to the details page by authenticating user via token.
My models.py is:
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
class Detail(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
file = models.FileField(verbose_name="CSV File", upload_to='csv_files')
file_desc = models.TextField("CSV File Description")
def __str__(self):
return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name))
def __unicode__(self):
return (self.file_desc)
My serializers.py is:
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from .models import Detail
from rest_framework import serializers
class MainUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email',)
class UserSerializer(serializers.ModelSerializer):
usr = MainUserSerializer()
class Meta:
model = Detail
fields = ['usr', 'file', 'file_desc']
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(**{'username': data['email'], 'password': data['password']})
if user and user.is_active:
return user
raise serializers.ValidationError('Incorrect Credentials Passed.')
My views.py is:
import requests
from rest_framework import permissions
from knox.models import AuthToken
from .serializers import UserSerializer, LoginSerializer
from django.shortcuts import redirect
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.views import APIView
from django.urls import reverse
from django.http import HttpResponseRedirect
class LoginAPIHTML(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'accounts/login.html'
def get(self, request):
serializer = LoginSerializer()
return Response({'serializer': serializer})
def post(self, request):
serializer = LoginSerializer(data=request.data)
if not serializer.is_valid():
return Response({'serializer': serializer})
user = serializer.validated_data
url = 'http://' + str(request.get_host()) + str(reverse('user', args=None))
headers = {
'Authorization': 'Token ' + str(AuthToken.objects.create(user)[1])
}
r = requests.get(url, headers=headers, format='json')
return HttpResponseRedirect(r)
My urls.py is:
from django.urls import path, include
from .views import LoginAPIHTML
urlpatterns = [
path('api/v1/', include('knox.urls')),
path('login', LoginAPIHTML.as_view(), name='login'),
path('user', UserAPI.as_view(), name='user'),
]
and below is my settings.py:
INSTALLED_APPS = [
'accounts',
'rest_framework',
'rest_framework.authtoken',
'knox',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'knox.auth.TokenAuthentication',
]
}
REST_AUTH_TOKEN_MODEL = 'knox.models.AuthToken'
REST_AUTH_TOKEN_CREATOR = 'project.apps.accounts.utils.create_knox_token'
Whenever, I put the correct credentials in the Login API at localhost:8000/login, then instead of redirecting to the details page at localhost:8000/user, I get the following error:
TypeError at /login
quote_from_bytes() expected bytes
Request Method: POST
Request URL: http://127.0.0.1:8000/login
Django Version: 4.0.3
Exception Type: TypeError
Exception Value:
quote_from_bytes() expected bytes
Traceback Switch to copy-and-paste view
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 55, in inner
response = get_response(request) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py, line 54, in wrapped_view
return view_func(*args, **kwargs) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py, line 84, in view
return self.dispatch(request, *args, **kwargs) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 509, in dispatch
response = self.handle_exception(exc) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 469, in handle_exception
self.raise_uncaught_exception(exc) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 480, in raise_uncaught_exception
raise exc …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 506, in dispatch
response = handler(request, *args, **kwargs) …
Local vars
C:\Users\Khubaib Khawar\Downloads\Meistery\Round2\backend_dev_trial_ass_r2\accounts\views.py, line 202, in post
return HttpResponseRedirect(r) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\http\response.py, line 538, in __init__
self["Location"] = iri_to_uri(redirect_to) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\encoding.py, line 139, in iri_to_uri
return quote(iri, safe="/#%[]=:;$&()+,!?*#'~") …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py, line 870, in quote
return quote_from_bytes(string, safe) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\urllib\parse.py, line 895, in quote_from_bytes
raise TypeError("quote_from_bytes() expected bytes") …
Local vars
I am fed up of this. It would be better if it sets up either using Knox or using Django Rest Authentication.
This should be of help:
https://studygyaan.com/django/django-rest-framework-tutorial-register-login-logout
I use this has a guide anytime am using Knox with drf.
Looking at the error logs you posted:
Local vars C:\Users\Khubaib Khawar\Downloads\Meistery\Round2\backend_dev_trial_ass_r2\accounts\views.py, line 202, in post return HttpResponseRedirect(r) …
HttpResponseRedirect expects the url or endpoint to be redirected to.
But the variable r is returning a response from the GET request made at:
r = requests.get(url, headers=headers, format='json')
hence the error:
raise TypeError("quote_from_bytes() expected bytes") …
I think this is similar to :
TypeError: quote_from_bytes() expected bytes after redirect
Based on your second comment:
you could try based off your code:
from rest_framework.response import Response
....
r = requests.get(url, headers=headers, format='json')
return Response(r.json(), status=status.HTTP_200_OK)
or
You could try separating your login view from your profile view. There is something called single responsibility in
SOLID principle. your login view should authenticate the user and return a valid token. And your profile view should be a protected view
that requires the user to be authenticated and has the right permission to view his user profile.
your profile view would look like this:
from rest_framework import mixins, authentication, permissions, status, viewsets
from rest_framework.response import Response
from core import models
from users.serializers import UserProfileSerializer
class UserProfileViewSet(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
):
"""User profile endpoint"""
authentication_classes = (authentication.TokenAuthentication, )
permission_classes = (permissions.IsAuthenticated,)
queryset = models.UserProfile.objects.all()
serializer_class = UserProfileSerializer
def get_queryset(self):
return models.UserProfile.objects.filter(
user=self.request.user.id)
def perform_create(self, serializer):
return serializer.save(user=self.request.user)
def update(self, request, *args, **kwargs):
user_obj = models.UserProfile.objects.get(id=kwargs['pk'])
user = request.user
if user_obj.user.id == user.id:
serializer = UserProfileSerializer(
user_obj,
data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
else:
return Response(
'Unauthorized',
status=status.HTTP_401_UNAUTHORIZED)
I hope this helps

ModelForm has no model class specified while using model form

path('', include('farmingwave.urls')), File "F:\farm\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module) File "C:\Users\Mohit\AppData\Local\Programs\Python\Python39\lib\importlib_init_.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File
"", line 1007, in _find_and_load File
"", line 986, in _find_and_load_unlocked
File "", line 680, in _load_unlocked
File "", line 790, in
exec_module File "", line 228, in
call_with_frames_removed File "F:\farm\fwave\farmingwave\urls.py", line 3, in
from . import views File "F:\farm\fwave\farmingwave\views.py", line 3, in
from .forms import ContactForm File "F:\farm\fwave\farmingwave\forms.py", line 3, in
from django.forms import contactForm ImportError: cannot import name 'contactForm' from 'django.forms'
(F:\farm\lib\site-packages\django\forms_init.py)
my views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import contactForm
from django.forms import ModelForm
from django.core.mail import send_mail
def contact(request):
if request.method == 'GET':
form = contactForm()
else:
form = contactForm(request.POST)
if form.is_valid():
form.save()
name = form.cleaned_data['name']
email = form.cleaned_data['email']
Phonenumber = form.cleaned_data['Phonenumber']
try:
send_mail(subject, message, from_email,['admin#example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "contact-form.html", {'form': form})
my form.py
from django import forms
from django.core.validators import RegexValidator
# from django.forms import contactForm
from .models import contactForm
class contactForm(forms.ModelForm):
name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'class' :
'form-control col-lg-12', 'placeholder': 'Name'}), label='')
email = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'form-control col-lg-12', 'placeholder': 'Email'}), label='')
Phonenumber = forms.CharField(max_length=10, validators= [RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class' : 'form-control col-lg-12', 'placeholder': 'Mobile'}), label='')
class contactForm(forms.ModelForm):
class Meta:
model = contactForm
fields = '__all__'
my model.py
from django.db import models
from django.forms import ModelForm
from django.core.validators import RegexValidator
class contactForm(models.Model):
name = models.CharField(max_length=255)
Phonenumber = models.CharField(max_length=10, validators=[RegexValidator(r'^\d{1,10}$')])
email = models.EmailField(max_length=254)
First of all you should post some code like your forms.py for clarification but seeing the error message, it shows django.forms import contactForm cannot import name 'contactForm' from 'django.forms'.Seems like contactForm is the name of the model on which you want to shape your form.
As that is model how can we import this from django.forms?
Use this code;
from .models import contactForm
from django.forms import modelForm #modelForm helps to create forms from models
class yourForm(modelForm):
class Meta:
model = contactForm #here we provide the name of the model from which the form is to be inherited
fields = ('here_provide_the_name_of_the_fields_of_the_model_which_you_want_to_Include_in_the_form')
Different fields will be placed as different elements of the fields tuple.
If you want to include all the fields in the form;
fields = __all__

Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'

i have problem with my code when i want signup error appear Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser' , i try solotion of other questions same like Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser' but all of them asking to replace User = User = get_user_model() but i am not use any User in my code or i dont know where i used that.im new in django , python , js and etc so if my question is silly forgivme .
for more information :1) i used Django Signup Tutorial for create signup method . first that was working well but after i expand my homework project i get error .2)in others app ("products" and "search") no where im not import User and even i dont use CustomUser too bez not need to work with User in this apps.just memebers work with User and CustomUser.
model.py :
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
def __str__(self):
return self.email
class Meta:
verbose_name = "member"
verbose_name_plural = "members"
setting.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'card.apps.CardConfig',
'members.apps.MembersConfig',
'search.apps.SearchConfig',
'products.apps.ProductsConfig',
'rest_framework',
]
AUTH_USER_MODEL = 'members.CustomUser'
admin.py:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username']
admin.site.register(CustomUser, CustomUserAdmin)
form.py:
# users/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('username', 'email')
error:
27/Feb/2019 12:36:01] "GET /signup/ HTTP/1.1" 200 5293
Internal Server Error: /signup/
Traceback (most recent call last):
File "C:\shopping\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\shopping\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\shopping\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\shopping\venv\lib\site-packages\django\views\generic\edit.py", line 141, in post
if form.is_valid():
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 180, in errors
self.full_clean()
File "C:\shopping\venv\lib\site-packages\django\forms\forms.py", line 383, in full_clean
self._post_clean()
File "C:\shopping\venv\lib\site-packages\django\contrib\auth\forms.py", line 107, in _post_clean
super()._post_clean()
File "C:\shopping\venv\lib\site-packages\django\forms\models.py", line 403, in _post_clean
self.instance.full_clean(exclude=exclude, validate_unique=False)
File "C:\shopping\venv\lib\site-packages\django\db\models\base.py", line 1137, in full_clean
self.clean()
File "C:\shopping\venv\lib\site-packages\django\contrib\auth\models.py", line 338, in clean
self.email = self.__class__.objects.normalize_email(self.email)
File "C:\shopping\venv\lib\site-packages\django\db\models\manager.py", line 188, in __get__
cls._meta.swapped,
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'
[27/Feb/2019 12:36:04] "POST /signup/ HTTP/1.1" 500 113770
Modify views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
to
from .forms import CustomUserCreationForm
from django.urls import reverse_lazy
from django.views import generic
class SignUp(generic.CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
In your forms.py make changes as:
from django.contrib.auth import get_user_model
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('username', 'email')
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('username', 'email')
Also add this script in your members/init.py file:
default_app_config = 'members.apps.MembersConfig'

'NoneType' object has no attribute '_meta'

I am trying to build register api. Here i am stuck with the problem and hoping you guys will address my mistake and will lead me to right way. Anyway thanks in advance. Hoping for your soon response. Thank you .
serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
""" Create and return a new user"""
user = User.objects.create_user(**validated_data)
return user
models.py
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
from django.contrib.auth import get_user_model
class UserRegisterManager(BaseUserManager):
""" Helps django work with our custom user model """
def createUser(self, email, name, password=None):
""" Creates a new user profile object """
if not email:
raise ValueError("User must have an email address.")
email = self.normalize_email(email)
user = self.model(email=email, name=name)
user.set_password(password) # set_password helps to convert str into hash
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
""" Creates and saves a new superuser with given details. """
user = self.create_user(email, name, password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class UserRegister(AbstractBaseUser, PermissionsMixin):
""" Represents a 'user register' inside our system """
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True) # user is currently active or not
is_staff = models.BooleanField(default=False)
objects = UserRegisterManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
""" Used to get user fullname """
return self.name
def get_short_name(self):
""" Used to get user short name """
return self.name
def __str__(self):
""" Django uses this when it need to convert the object to a string """
return self.email
this is my model
views.py
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from .serializers import UserSerializer
from . import permissions
from django.contrib.auth import get_user_model
User = get_user_model()
class UserViewSet(viewsets.ModelViewSet):
""" API endpoint that allows users to be viewed or edited. """
serializer_class = UserSerializer
queryset = User.objects.all()
# authentication_classes = (TokenAuthentication,)
# permission_classes = (permissions.UpdateProfile,)
setting.py
AUTH_USER_MODEL = 'register.UserRegister'
this helps to switch to costume user.
admin.py
from django.contrib import admin
from .models import UserRegister
admin.site.register(UserRegister)
And this is how i register my model
Error
This is error
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/register/
Django Version: 2.1.5
Python Version: 3.7.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'register',
'corsheaders']
Installed 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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware']
Traceback:
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\base.py" in _get_response
156. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\core\handlers\base.py" in _get_response
154. response = response.render()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\django\template\response.py" in render
106. self.content = self.rendered_content
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\response.py" in rendered_content
72. ret = renderer.render(self.data, accepted_media_type, context)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in render
733. context = self.get_context(data, accepted_media_type, renderer_context)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in get_context
663. raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\renderers.py" in get_raw_data_form
574. data = serializer.data.copy()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in data
563. ret = super(Serializer, self).data
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in data
266. self._data = self.get_initial()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in get_initial
413. for field in self.fields.values()
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in fields
363. for key, value in self.get_fields().items():
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\serializers.py" in get_fields
1024. info = model_meta.get_field_info(model)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\utils\model_meta.py" in get_field_info
39. forward_relations = _get_forward_relationships(opts)
File "C:\Users\Pashupati Pariyar\Desktop\Django + Angular\Backend\api\lib\site-packages\rest_framework\utils\model_meta.py" in _get_forward_relationships
96. not field.remote_field.through._meta.auto_created
Exception Type: AttributeError at /api/register/
Exception Value: 'NoneType' object has no attribute '_meta'
from django.contrib.auth import get_user_model
User = get_user_model()
Always use that to access the user model instead of this
from django.contrib.auth.models import User
to account for custom user models.

Emails won't send after upgrading from Django 1.6.x to Django > 1.7.x

I am currently using Django Allauth and a modified version of Django Invitations (https://github.com/bee-keeper/django-invitations). The only thing added is a field for which group to add the user to, and the application works perfectly when Django 1.6.x is being used. I would like to upgrade to Django 1.7.x or 1.8 but this somehow breaks the emailing feature.
The specific piece of code is here:
'import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.encoding import python_2_unicode_compatible
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from allauth.account.adapter import DefaultAccountAdapter
from allauth.account.adapter import get_adapter
from .managers import InvitationManager
from . import app_settings
from . import signals
...(other code)
def send_invitation(self, request, **kwargs):
current_site = (kwargs['site'] if 'site' in kwargs
else Site.objects.get_current())
invite_url = reverse('invitations:accept-invite',
args=[self.key])
invite_url = request.build_absolute_uri(invite_url)
ctx = {
'invite_url': invite_url,
'current_site': current_site,
'email': self.email,
'key': self.key,
}
email_template = 'invitations/email/email_invite'
get_adapter().send_mail(email_template,
self.email,
ctx)
self.sent = timezone.now()
self.save()
signals.invite_url_sent.send(
sender=self.__class__,
instance=self,
invite_url_sent=invite_url)'
found here (https://github.com/bee-keeper/django-invitations/blob/master/invitations/models.py)
This also references the code from allauth here:
from __future__ import unicode_literals import re
import warnings
import json
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist
from django.contrib.sites.models import Site
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib import messages
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_unicode as force_text
from ..utils import (import_attribute, get_user_model,
generate_unique_username,
resolve_url)
from . import app_settings
USERNAME_REGEX = re.compile(r'^[\w.#+-]+$', re.UNICODE)
........ (other code)
def render_mail(self, template_prefix, email, context):
"""
Renders an e-mail to `email`. `template_prefix` identifies the
e-mail that is to be sent, e.g. "account/email/email_confirmation"
"""
subject = render_to_string('{0}_subject.txt'.format(template_prefix),
context)
# remove superfluous line breaks
subject = " ".join(subject.splitlines()).strip()
subject = self.format_email_subject(subject)
bodies = {}
for ext in ['html', 'txt']:
try:
template_name = '{0}_message.{1}'.format(template_prefix, ext)
bodies[ext] = render_to_string(template_name,
context).strip()
except TemplateDoesNotExist:
if ext == 'txt' and not bodies:
# We need at least one body
raise
if 'txt' in bodies:
msg = EmailMultiAlternatives(subject,
bodies['txt'],
settings.DEFAULT_FROM_EMAIL,
[email])
if 'html' in bodies:
msg.attach_alternative(bodies['html'], 'text/html')
else:
msg = EmailMessage(subject,
bodies['html'],
settings.DEFAULT_FROM_EMAIL,
[email])
msg.content_subtype = 'html' # Main content is now text/html
return msg
def send_mail(self, template_prefix, email, context):
msg = self.render_mail(template_prefix, email, context)
msg.send()'
found at (allauth/account/adapter.py)
The form always saves an invitation element into the database but breaks at the sending email line. (all infor stored is correct, so that isn't breaking it). If the email is removed, all code afterwards runs fine. I have even tried to just send a basic email like such in place:
from django.core.mail import EmailMessage
msg = EmailMessage("TEST", "HELLO", my_email, [some_email])
msg.send()
but this, too does not send emails.
I am hoping this is super simple, but any help would be appreciated.
I had the same problem, the execution just hung when running this code in a django shell (Django 1.7):
from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', 'from#example.com',
['to#example.com'], fail_silently=False)
Following the Django docs on email settings, I used in settings.py:
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
EMAIL_PORT = 465
This worked.