Reg: Django signal not working

666 views
Skip to first unread message

Amitesh Sahay

unread,
Apr 17, 2020, 5:17:40 PM4/17/20
to Django Users
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.


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


Saurabh Ranjan Singh

unread,
Apr 18, 2020, 10:44:02 AM4/18/20
to Django users
I am having the same issue. Please fix it.

Jorge Gimeno

unread,
Apr 19, 2020, 2:12:40 PM4/19/20
to django...@googlegroups.com
Amitesh,

Where is User.profile defined?

-Jorge

On 4/18/20, Saurabh Ranjan Singh <saurm...@gmail.com> wrote:
> I am having the same issue. Please fix it.
>
> On Friday, 17 April 2020 22:47:40 UTC+5:30, Amitesh Sahay wrote:
>>
>> 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:*
>> *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*
>> * 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
>>
>>
>>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/92ccf642-03e7-4627-989e-59507e8de25c%40googlegroups.com.
>

Amitesh Sahay

unread,
Apr 20, 2020, 9:41:31 AM4/20/20
to django...@googlegroups.com
-+c Hello Jorge, 

After doing some research, I realized that the signal which is saving the user profile should have 

"instance.signup.save()" , as the name of the custom model is signup. This time I still got the error .However,  I could create the new user and login to the website. However, when I look into the admin panel, I still could't see the "contact" field getting saved after the user is registered successfully. 

Therefore the main purpose of creating the custom User model still failing. 

Below are the code snippet, and screenshot from my admin panel.

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.CharField(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):
        save2 = instance.signup.save()
print(save2)

To debug the issue, I used the print statement to see the output of "instance.signup.save()". So, after submitting the form, I checked the "runserver" console. The output was "None". So, something doesn't seems to be right.

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)

    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
-------------
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.signup.contact)

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})
Screenshot from the admin panel:

Inline image
Please suggest. If you are comfortable we can go on a web meeting where I can share my screen and we can work on it.

Regards,
> email to django-users+unsub...@googlegroups.com.

>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsub...@googlegroups.com.

To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CANfN%3DK9Luixw3ZMfZzWN32-3AuwXvS8FoP-uEdOGGdqVgOa_LA%40mail.gmail.com.

Aditya Singh

unread,
Apr 20, 2020, 10:58:59 AM4/20/20
to django...@googlegroups.com
What's the original issue please, seems like you picked things up with someone till this email.
Regards,
Aditya

To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/677369937.2215536.1587375479014%40mail.yahoo.com.

Amitesh Sahay

unread,
Apr 21, 2020, 4:05:53 AM4/21/20
to django...@googlegroups.com
Hello Aditya,

I am using Django's "User" and "UserCreationForm" to create registration and login page and it's backend logic. So far so good. I could add the default fields to my registration page and it's working as per required.

However, I want to add a custom field "contact" as it does not come in-built. But no matter what I am not able to do it.

I have already shared the code in my previous email. Please go through it and let me know if you can help me somehow.

Thank you

Anonymous Patel

unread,
Apr 21, 2020, 9:06:20 AM4/21/20
to django...@googlegroups.com
https://youtu.be/QDk3rI_H3ks
Checkout this video from errormania 
They explained about signal.
If that doesn't help leave comment there they provide you with a video in a day

Raj Patel

sahil khan

unread,
Apr 21, 2020, 1:04:16 PM4/21/20
to django...@googlegroups.com
Hello i am from google group plz see this video chennel and solve your problem
https://youtu.be/QDk3rI_H3ks like comment and subscribe and share so that another people get help this channel 

Amitesh Sahay

unread,
Apr 22, 2020, 11:56:23 AM4/22/20
to django...@googlegroups.com
Hello Sahil,

Thank you for the youtube link. The video has done the exactly same thing that I am doing. However, I understand that the user registration is created through default "User" model, and UserCreationForm. However, I am adding a custom field "city", and its not working for me. 

Except the city, all other default is saved into the database.(Username, first_name, last_name, email, password)

I have already shared the code snippet here in my previous emails. If possible go through it and let me know .

Regards,
Amitesh


Jorge Gimeno

unread,
Apr 22, 2020, 3:01:18 PM4/22/20
to django...@googlegroups.com
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2071597264.669239.1587556506575%40mail.yahoo.com.

After seeing the replies you've gotten so far, I think I understand that you're trying to save a field on the default User model.  I believe that what is happening is that the attribute User.profile does not exist, so when the signal is called you get an exception.

What I would try is to add a customer user model to the project.  A good writeup to follow is here:  https://learndjango.com/tutorials/django-custom-user-model

You may need to delete and rerun your migrations if you have run any.  There are a lot of internals that depend on the User model being defined.  As an aside, creating a custom user model is considered a best practice anyway:  https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project

Let us know if this helps!

-Jorge

sahil khan

unread,
Apr 23, 2020, 2:47:35 PM4/23/20
to django...@googlegroups.com


Here is the Link for your Problem.

if you like the solutions please like share and subscribe errormania. in your groups and join our telegram channel: @errormania
And share in your groups and with other developer friends
 

thank you

Reply all
Reply to author
Forward
0 new messages