Friday, April 17, 2020

Reg: Django signal not working

Hi,

I am creating a Django signup form through "User" model and "UserCreationForm" and customized the User model to accommodate single user defined field "contact".

However, the signal that I have written seems not to be working.
Whenever, I am filling the form, I am getting below error:

AttributeError at /auth/register/
'User' object has no attribute 'profile'

Full traceback log as below:

Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'phone_field',
 'AUTHENTICATION']
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:\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\anshu\djago-project\SkoolSkill\AUTHENTICATION\views.py", line 50, in register_user
    save1 = form.save()
  File "C:\Python38\lib\site-packages\django\contrib\auth\forms.py", line 137, in save
    user.save()
  File "C:\Python38\lib\site-packages\django\contrib\auth\base_user.py", line 66, in save
    super().save(*args, **kwargs)
  File "C:\Python38\lib\site-packages\django\db\models\base.py", line 745, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Python38\lib\site-packages\django\db\models\base.py", line 793, in save_base
    post_save.send(
  File "C:\Python38\lib\site-packages\django\dispatch\dispatcher.py", line 173, in send
    return [
  File "C:\Python38\lib\site-packages\django\dispatch\dispatcher.py", line 174, in <listcomp>
    (receiver, receiver(signal=self, sender=sender, **named))
  File "C:\Users\anshu\djago-project\SkoolSkill\AUTHENTICATION\models.py", line 17, in save_user_profile
    instance.profile.save()

Exception Type: AttributeError at /auth/register/
Exception Value: 'User' object has no attribute 'profile'

I have uploaded the project in google drive with below location link, just in case if somebody wishes to test it.

https://drive.google.com/file/d/1COB3BBoRb95a85cLi9k1PdIYD3bmlnc0/view?usp=sharing

My environment:

Django==3.0.5 python 3.8.2

Not sure what is the mistake. Please help.

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class SignUp(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    Contact = models.TextField(max_length=500, blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        SignUp.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

forms.py

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from  .models import SignUp

class SignUpForm(UserCreationForm):
    email = forms.EmailField()
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
#    phone = format()

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')


class CustomSignUpPage(forms.ModelForm):
    Contact = forms.CharField(max_length=10)
    class Meta:
        model = SignUp
        fields = ('Contact', )

views.py

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
#from django.contrib.auth.forms import UserCreationForm
from .forms import SignUpForm, CustomSignUpPage

def home(request):
   return render(request, 'authenticate\home.html', {})

def login_user(request):
   if request.method == 'POST':
      username = request.POST['username']
      password = request.POST['password']
      user = authenticate(request, username=username, password=password)
      if user is not None:
         login(request, user)
         messages.success(request, ('login success'))
         return redirect('home')
      else:
         messages.success(request, ('error while login, please try again'))
         return redirect('login')
   else:
      return render(request, 'authenticate\login.html', {})

def logout_user(request):
   logout(request)
   messages.success(request, ('logout successful'))
   return redirect('home')

def register_user(request):
   if request.method == "POST":
      form = SignUpForm(request.POST)
      cus_form = CustomSignUpPage(request.POST)
      if form.is_valid() and cus_form.is_valid():
         save1 = form.save()
         save1.refresh_from_db()
         cus_form = CustomSignUpPage(request.POST, instance=request.save1.profile)
         cus_form.full_clean()
         cus_form.save()
         username = form.cleaned_data['username']
         password = form.cleaned_data['password1']
         user = authenticate(request, username=username, password=password)
         login(request, user)
         messages.success(request, f'Registration successful')
         return redirect('home')
      else:
         messages.error(request, f'Please correct the error below.')
   else:
      form = SignUpForm()
      cus_form = CustomSignUpPage()

   return render(request, 'authenticate\\register.html', context={'form': form, 'cus_form': cus_form})

Note: As per my understanding the two lines from the above code snippet which have been written in bold letters and red in color is the issue. However I could be completely wrong. 

Regards,
Amitesh


No comments:

Post a Comment