RelatedObjectDoesNotExist at /profiles/user-follow-feed/ User has no user - python

Well i am just trying to show feed back of the following users but got an error:RelatedObjectDoesNotExist at /profiles/user-follow-feed/
User has no user. I don't understand how can i fix it. Need help to fix it out. many thanks in advance.
views.py
class FolloweHomeView(View):
def get(self, request, *args, **kwargs):
user = request.user.userprofile
is_following_user_ids = [x.user.id for x in user.follower.all()]
qs = Post.objects.filter(username__id__in=is_following_user_ids).order_by("-create_date")[:3]
return render(request, "profiles/follower_home_feed.html", {'object_list': qs})
models.py
class ProfileManager(models.Manager):
def toggle_follow(self, request_user, username_to_toggle):
profile_ = UserProfile.objects.get(user__username__iexact=username_to_toggle)
user = request_user
is_following = False
if user in profile_.follower.all():
profile_.follower.remove(user)
else:
profile_.follower.add(user)
is_following = True
return profile_, is_following
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
follower = models.ManyToManyField(User, related_name ='is_following',blank=True,)
avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True)
create_date = models.DateField(auto_now_add=True,null=True)
objects = ProfileManager()
def __str__(self):
return f'{self.user.username}'
traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/profiles/user-follow-feed/
Django Version: 3.0.3
Python Version: 3.8.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'accounts',
'posts',
'profiles']
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']
Traceback (most recent call last):
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\AHMED\grapPub\grabpublic\profiles\views.py", line 99, in get
is_following_user_ids = [x.user.id for x in user.follower.all()]
File "C:\Users\AHMED\grapPub\grabpublic\profiles\views.py", line 99, in <listcomp>
is_following_user_ids = [x.user.id for x in user.follower.all()]
File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\fields\related_descriptors.py", line 420, in __get__
raise self.RelatedObjectDoesNotExist(
Exception Type: RelatedObjectDoesNotExist at /profiles/user-follow-feed/
Exception Value: User has no user.
if more detail is require than tell me i will update my question with that information

The follower is a ManyToManyField to the User model, so the x in the list comprehension is a User object:
is_following_user_ids = [x.id for x in user.follower.all()]
You however do not need to perform this kind of logic, you can directly filter with:
qs = Post.objects.filter(
username__user__is_following__user=request.user
).order_by('-create_date')[:3]
this will query the Post objects in a single query.
Note: A ForeignKey does not store the string representation (or name) of the
referenced object in the column, it stores the primary key of the record it
references in a column with an _id suffix to a ForeignKey field. Therefore
ForeignKeys usually do not end with a name suffix. You might want to
consider renaming the username field to author.
Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

Related

AttributeError: 'Post' object has no attribute 'post_image'

I am using DRF and Django(4.0) to make posts in a Instagram Clone. The models of the following are available below. I have successfully implemented post request, but am having problems implementing get request.
I have tried to nest two serializer inside the PostViewSerializer to serialize the data. However I am getting the following error when I do a get request.
Got AttributeError when attempting to get a value for field 'post_image' on serializer 'PostViewSerializer'.
The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance.
Original exception text was: 'Post' object has no attribute 'post_image'.
Now, I should tell you that there is not requirement that the post should contain atleast one image or video it could contain entirely either videos or posts. So, could that be the cause of the above error. If so, how can I solve it?
#models.py
class Post(Authorable, Model):
created_at = models.DateTimeField(default=timezone.now)
caption = TextField(max_length=350)
class Images(Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
images = models.FileField(upload_to="images/")
class Videos(Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
videos = models.FileField(upload_to="videos/")
#behaviours.py
class Authorable(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
abstract = True
def get_user(self):
return self.user.id
#serializers.py
class ImageViewSerializer(serializers.ModelSerializer):
class Meta:
model = Images
fields = ['images']
class VideoViewSerializer(serializers.ModelSerializer):
class Meta:
model = Videos
fields = [ 'videos']
class PostViewSerializer(serializers.ModelSerializer):
post_image = ImageViewSerializer()
post_video = VideoViewSerializer()
class Meta:
model = Post
fields = ['post_image', 'post_video', 'caption','user']
class PostUpload(APIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser, FormParser]
serializer_class = PostSerializer
def get(self, request):
user = request.user
serializer = PostViewSerializer(Post.objects.filter(user=user), many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
Edit 1:(With Full Traceback Error)
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/user/post/
Django Version: 4.0
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_simplejwt',
'core',
'authentication',
'socialuser']
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']
Traceback (most recent call last):
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\fields.py", line 457, in get_attribute
return get_attribute(instance, self.source_attrs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\fields.py", line 97, in get_attribute
instance = getattr(instance, attr)
During handling of the above exception ('Post' object has no attribute 'images'), another exception occurred:
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\suyas\Desktop\Memestagram\socialuser\views.py", line 22, in get
return Response(serializer.data, status=status.HTTP_200_OK)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 768, in data
ret = super().data
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 253, in data
self._data = self.to_representation(self.instance)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 686, in to_representation
return [
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 687, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\serializers.py", line 509, in to_representation
attribute = field.get_attribute(instance)
File "C:\Users\suyas\.virtualenvs\Memestagram-Tno8CPgV\lib\site-packages\rest_framework\fields.py", line 490, in get_attribute
raise type(exc)(msg)
Exception Type: AttributeError at /api/user/post/
Exception Value: Got AttributeError when attempting to get a value for field `post_image` on serializer `PostViewSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance.
Original exception text was: 'Post' object has no attribute 'images'.
My Serializer
class PostViewSerializer(serializers.ModelSerializer):
# access ForeignKey in reverse 🖟
post_image = ImageViewSerializer(source='images', many=True)
post_video = VideoViewSerializer(source='videos', many=True)
class Meta:
model = Post
fields = ['post_image', 'post_video', 'caption','user']
There is no ImageField, ForeignKey, ManyToManyField, etc. with post_image as name. You can access the images with .images. This thus means that you use this as source:
class PostViewSerializer(serializers.ModelSerializer):
# access ForeignKey in reverse 🖟
post_image = ImageViewSerializer(source='images_set', many=True)
post_video = VideoViewSerializer(source='videos_set', many=True)
class Meta:
model = Post
fields = ['post_image', 'post_video', 'caption','user']

Unable to delete user from Admin panel which was created using Django-Allauth

I am new to Django and trying to add social login options to a project I am working on. I am currently using Django-Allauth for the same. Currently I have incorporated only Google login into my project. Everything works fine. I have created a custom user model for my project with email as the username. When a user tries to sign up using the Sign Up template I have provided, I can delete the user from the database without any problems. But if I try to delete any user from the admin panel who signed in using the Google option of django-allauth, I get __str__ returned non-string (type CustomUser) error. Only way for me to reset everything is to simply delete the model and redo everything. Below is how my model looks like. I am using Django 3.0 and the latest version of Django-Allauth. I am not sure how to solve this problem. Any help on this would be appreciated.
models.py
class CustomUser(AbstractBaseUser):
email = models.EmailField(unique=True, max_length=100)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35)
mobile = models.CharField(max_length=11, blank=True, default='')
city = models.CharField(max_length=35, blank=True, default='')
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = CustomUserManager()
def __str__(self):
return self.email
def get_full_name(self):
if self.first_name and self.last_name:
return self.first_name + " " + self.last_name
def get_short_name(self):
if self.first_name:
return self.first_name
def has_perm(self, perm, obj=None):
"""
Does the user have a specific permission?
"""
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"""
Does the user have permissions to view the app `app_label`?
"""
# Simplest possible answer: Yes, always
return True
def get_absolute_url(self):
return reverse('users-profile', args=[str(self.id)])
Settings.py
# Application definition
INSTALLED_APPS = [
# Default Apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites', # Added
# User Apps
'users.apps.UsersConfig',
'crispy_forms',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend', # Added
)
# Required for Django-Allauth
SITE_ID = 1
# Required for Django-Allauth
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('users.urls')),
path('accounts/', include('allauth.urls')),
]
Below is the error traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/users/customuser/
Django Version: 3.0
Python Version: 3.8.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'users.apps.UsersConfig',
'contacts.apps.ContactsConfig',
'API.apps.ApiConfig',
'crispy_forms',
'admin_honeypot',
'rest_framework',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
'users.middleware.OneSessionPerUserMiddleware')
Traceback (most recent call last):
File "D:\Programs\Django\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\Programs\Django\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\Programs\Django\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner
return view(request, *args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 1704, in changelist_view
response = self.response_action(request, queryset=cl.get_queryset(request))
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 1390, in response_action
response = func(self, request, queryset)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\actions.py", line 28, in delete_selected
deletable_objects, model_count, perms_needed, protected = modeladmin.get_deleted_objects(queryset, request)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\options.py", line 1826, in get_deleted_objects
return get_deleted_objects(objs, request, self.admin_site)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 151, in get_deleted_objects
to_delete = collector.nested(format_callback)
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 211, in nested
roots.extend(self._nested(root, seen, format_callback))
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 195, in _nested
children.extend(self._nested(child, seen, format_callback))
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 197, in _nested
ret = [format_callback(obj)]
File "D:\Programs\Django\venv\lib\site-packages\django\contrib\admin\utils.py", line 126, in format_callback
no_edit_link = '%s: %s' % (capfirst(opts.verbose_name), obj)
Exception Type: TypeError at /admin/users/customuser/
Exception Value: __str__ returned non-string (type CustomUser)
AbstractBaseUser has a __str__ method, which returns the field specified on USERNAME_FIELD in the model. You can check the source code on Github.
So after you specify custom USERNAME_FIELD, you can remove your own __str__ method:
class CustomUser(AbstractBaseUser):
email = models.EmailField(unique=True, max_length=100)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35)
mobile = models.CharField(max_length=11, blank=True, default='')
city = models.CharField(max_length=35, blank=True, default='')
USERNAME_FIELD = 'email'
Also make sure that you installed and configured the packaged properly.

Django Social Auth - Google: AttributeError: 'NoneType' object has no attribute 'provider'

I am receiving this error when trying to login via google, I've tried just about everything I can think of and similar issues on SO don't seem to help. I have a custom user model setup as such:
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class Departments(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class AlluredUser(AbstractUser):
departments = models.ManyToManyField(Departments)
def __str__(self):
return self.username
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import AlluredUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = AlluredUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = AlluredUser
fields = ('username', 'email')
Social Auth Pipeline
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.social_auth.associate_by_email',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details'
)
Error Traceback
AttributeError at /auth/complete/google-oauth2/
'NoneType' object has no attribute 'provider'
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/auth/complete/google-oauth2/?state=8XLcbxz6sPSPOwJfOIXWOud88UJ5YtL2&code=4/twHRVLHTMzBV99K-VvektvJfjGuJYGBvqi254dWTuA2dLmbNFw3fIp8l5pdYSqKK89ONPGrxInG39pH8Wf-fpas&scope=email%20profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email%20openid&authuser=0&hd=allured.com&session_state=2403f8348307b18b8ab460026d3c88b1b18d759f..5dbb&prompt=none
Django Version: 2.2.4
Python Version: 3.7.4
Installed Applications:
['user.apps.UserConfig',
'issue_tracker.apps.IssueTrackerConfig',
'ytd_reports.apps.YtdReportsConfig',
'stats.apps.StatsConfig',
'scheduler.apps.SchedulerConfig',
'submissions.apps.SubmissionsConfig',
'dash_app.apps.DashAppConfig',
'contact.apps.ContactConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django']
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',
'social_django.middleware.SocialAuthExceptionMiddleware',
'dashboard.middleware.loginRequired.LoginRequiredMiddleware']
Traceback:
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_django\utils.py" in wrapper
49. return func(request, backend, *args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_django\views.py" in complete
33. *args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_core\actions.py" in do_complete
71. social_user.provider)
Exception Type: AttributeError at /auth/complete/google-oauth2/
Exception Value: 'NoneType' object has no attribute 'provider'
I'm guessing it has something to do with the custom user model I created since I didn't have this problem beforehand. Any help would be much appreciated.
The error on the link doesn't match what you mention in the title.
For the traceback, the solution is just to add this:
SESSION_COOKIE_SECURE = False

Django templated mail 'dict' object has no attribute 'get_host'

I'm trying to send a verification email after a user registers an account using django-templated-mail.
This is the error I get after the user is created:
AttributeError 'dict' object has no attribute 'get_host'
So Django is trying to call get_host() and is unable to? So it's an error because it can't retrieve my host name?
Can someone point out what am I missing here?
class UserListView(generics.ListCreateAPIView):
serializer_class = UserSerializer
def perform_create(self, serializer):
user = serializer.save()
context = {'user': user}
to = user.email
email.ActivationEmail(context).send(to)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'password', 'email')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password')
user = super(UserSerializer, self).create(validated_data)
user.set_password(password)
user.save()
return user
class ActivationEmail(BaseEmailMessage):
template_name = 'email/activation.html'
def get_context_data(self):
context = super(ActivationEmail, self).get_context_data()
user = context.get('user')
context['uid'] = utils.encode_uid(user.pk)
context['token'] = default_token_generator.make_token(user)
context['url'] = 'verify/{uid}/{token}'.format(**context)
return context
Traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/users/
Django Version: 2.0
Python Version: 3.6.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'templated_mail',
'accounts',]
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'simple_history.middleware.HistoryRequestMiddleware']
Traceback:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
483. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
443. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
480. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/generics.py" in post
244. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/code/accounts/views.py" in perform_create
54. email.ActivationEmail(context).send(to)
File "/usr/local/lib/python3.6/site-packages/templated_mail/mail.py" in send
69. self.render()
File "/usr/local/lib/python3.6/site-packages/templated_mail/mail.py" in render
61. context = make_context(self.get_context_data(), request=self.request)
File "/code/accounts/email.py" in get_context_data
12. context = super(ActivationEmail, self).get_context_data()
File "/usr/local/lib/python3.6/site-packages/templated_mail/mail.py" in get_context_data
33. site = get_current_site(self.request)
File "/usr/local/lib/python3.6/site-packages/django/contrib/sites/shortcuts.py" in get_current_site
16. return RequestSite(request)
File "/usr/local/lib/python3.6/site-packages/django/contrib/sites/requests.py" in __init__
10. self.domain = self.name = request.get_host()
Exception Type: AttributeError at /users/
Exception Value: 'dict' object has no attribute 'get_host'
Thank you much appreciate any help you may be able to render.
ActivationEmail takes the request as the first positional argument to its initializer. You're passing the context as the first positional argument, which causes ActivationEmail to fall over.
Make sure you pass the request instance as well as the context to ActivationEmail when you create it.
email.ActivationEmail(self.request, context).send(to)
You instantiated ActivationEmail incorrectly. The request parameter should be an HttpRequest object instead of a dict.

Django - one to one serializer Create function

I extended the default User model to ExtendedUser:
from django.db import models
from django.contrib.auth.models import User
class ExtendedUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
shirt_size = models.CharField(max_length=2)
User serializer:
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups', 'is_staff')
ExtendedUser serializer:
from api.resources.users.models.extended_user import ExtendedUser
from rest_framework import serializers
from django.contrib.auth.models import User
from api.resources.users.serializers.user import UserSerializer
class ExtendedUserSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer(read_only=False)
class Meta:
model = ExtendedUser
fields = ('url', 'shirt_size', 'user')
def create(self, validated_data):
user_data = validated_data.pop('user')
user = User.objects.create(**user_data)
return ExtendedUser.objects.create(user=user, **validated_data)
The main result should be that on submitting new ExtendedUser it will create a user too with one to one realation.
But I am getting this error:
User: myusername needs to have a value for field "user" before this
many-to-many relationship can be used.
Traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/users/
Django Version: 1.10.4
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'api']
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']
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\rest_framework\viewsets.py" in view
83. return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
477. response = self.handle_exception(exc)
File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception
437. self.raise_uncaught_exception(exc)
File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
474. response = handler(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\rest_framework\mixins.py" in create
21. self.perform_create(serializer)
File "C:\Python27\lib\site-packages\rest_framework\mixins.py" in perform_create
26. serializer.save()
File "C:\Python27\lib\site-packages\rest_framework\serializers.py" in save
214. self.instance = self.create(validated_data)
File "C:/Users/ozbar/PycharmProjects/usnccm/usnccm-api\api\resources\users\serializers\extended_user.py" in create
15. user = User.objects.create(**user_data)
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
85. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in create
397. obj = self.model(**kwargs)
File "C:\Python27\lib\site-packages\django\contrib\auth\base_user.py" in __init__
68. super(AbstractBaseUser, self).__init__(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in __init__
550. setattr(self, prop, kwargs[prop])
File "C:\Python27\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
499. manager = self.__get__(instance)
File "C:\Python27\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__
476. return self.related_manager_cls(instance)
File "C:\Python27\lib\site-packages\django\db\models\fields\related_descriptors.py" in __init__
783. (instance, self.source_field_name))
Exception Type: ValueError at /users/
Exception Value: "<User: oz>" needs to have a value for field "user" before this many-to-many relationship can be used.
Validated_data object`s value on POST via django-rest web view:
{u'user': OrderedDict([(u'username', u'oz'), (u'email', u'oz.barshalom#gmail.com'), (u'groups', []), (u'is_staff', True)]), u'shirt_size': u'm'}
Okay for starters, the problem has nothing to do with django-rest-framework or your python version.
It seems to be an issue with django==1.10 as I simply tried:
User.objects.create(user="hello", email="333.22#eewofw.com", groups=[], is_staff=False)
in django's shell and received the exact same error. However, if we try newer versions of django, the problem does not persist.
I have noticed that when installing django using this command:
pip install django
It will install django==1.10 and not the latest version. If you mistakenly installed this older version, I suggest to uninstall django and then install the latest version:
pip uninstall django
pip install django==1.9.12
When using django==1.9.12, you need to remove groups completely from your UserSerializer and not provide it when doing your POST.

Categories