Monday, April 20, 2020

Re: Reg: Django signal not working

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 

On Mon, 20 Apr 2020, 4:28 pm Aditya Singh, <adityasingh222247@gmail.com> wrote:
What's the original issue please, seems like you picked things up with someone till this email.
Regards,
Aditya

On Mon, Apr 20, 2020, 3:11 PM 'Amitesh Sahay' via Django users <django-users@googlegroups.com> wrote:
-+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,
On Sun, 19 Apr 2020 at 19:42, Jorge Gimeno
Amitesh,

Where is User.profile defined?

-Jorge

On 4/18/20, Saurabh Ranjan Singh <saurmaurya@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:*
>>
>> 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
>>
>>
>>
>
> --
> 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+unsubscribe@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.

>

--
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+unsubscribe@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.

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/677369937.2215536.1587375479014%40mail.yahoo.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEPfumitZFhhXtxnfwhbSo6cwwOBqoWQ_%2BoTz5LmZ_UNLWROAw%40mail.gmail.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAM8veW_iRnsfOnWcWv50A1_kRvgXpdwXh%3DXEnC1JMt7UVz-nRA%40mail.gmail.com.

No comments:

Post a Comment