User has no profile.RelatedObjectDoesNotExist - python

I am trying to create a user based app. A profile image is associated with every user. But whenever I am trying to login it is showing the above mentioned error and highlighting the instance.profile.save() in signals.py. I am new to django.
error:
Request Method: POST
Request URL: http://127.0.0.1:8000/login/
Django Version: 2.2.5
Exception Type: RelatedObjectDoesNotExist
Exception Value: User has no profile.
users/Signals.py:
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import profile
#receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
if created:
profile.objects.create(user=instance)
#receiver(post_save,sender=User)
def save_profile(sender,instance,**kwargs):
instance.profile.save()
users/Models.py:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
# Create your models here.
class profile(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
image=models.ImageField(default='default.png',upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} profile'
def save(self,*args,**kwargs):
super( profile, self ).save(*args,**kwargs)
img=Image.open(self.image.path)
if img.height>300 or img.width>300:
output_size=(300,300)
img.thumbnail(output_size)
img.save(self.image.path)
users/views.py:
from django.shortcuts import render,redirect
from django.contrib import messages
from .forms import UserRegisterForm,UserUpdateForm,ProfileUpdateForm
from django.contrib.auth.decorators import login_required
from .models import profile
# Create your views here.
def register(request):
if request.method=="POST":
form=UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username=form.cleaned_data.get('username')
messages.success(request,f'Account created for {username}!')
return redirect('login')
else:
form=UserRegisterForm()
return render(request,'users/register.html',{'form':form})
#login_required
def profile(request):
if request.method=='POST':
u_form = UserUpdateForm( request.POST,instance=request.user )
profile = profile.objects.get( user=request.user )
Profile_form = ProfileForm( request.POST, instance=profile )
p_form = ProfileUpdateForm(request.POST,request.FILES, instance=request.user.profile )
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success( request, f'Your Account is updated !' )
return redirect( 'profile' )
else:
u_form=UserUpdateForm(instance=request.user)
p_form=ProfileUpdateForm(instance=request.user.profile)
context={
'u_form':u_form,'p_form':p_form
}
return render(request,'users/profile.html',context)
app2/models.py:
from django.contrib.auth.models import User
from django.db import models
class resume( models.Model ):
user = models.OneToOneField( User, on_delete=models.CASCADE,primary_key=True )
username=models.CharField(max_length=150)
email=models.EmailField(max_length=150)
phone=models.BigIntegerField()
def __str__(self):
return str(self.user.username)+str(self.country)

This code
profile.objects.create(user=instance)
already saves the profile and doesn't need save() to be called separately in save_profile method.
Also please consider naming classes starting with uppercase. 'profile' -> 'Profile'

Related

How can I save a django form

So I want to save a Biographie for each new created User. The user can enter his Bio and it will the it to his Profile.
For this I created a model with OneToOneField
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 Profile(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, null=True, blank=True)
bio = models.CharField(max_length=30)
To create the form I did the following in forms.py:
class BioForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('bio',)
Then I created in the views.py the saving, so the bio will be saved to the specific user:
from .forms import LoginForm, RegisterForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth import get_user_model
def test_view(request):
form = BioForm(request.POST)
user = get_user_model
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.phone_number = request.phone_number
profile.save()
return render(request, 'test.html', {'form': form})
There is something big wrong in the views.py but I don't get it.
I can submit the form and the form will be saved (sometimes) but without the user who wrote it + I get this error:
ValueError at /test/
Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000253B7140D00>>": "Profile.user" must be a "User" instance
Try to assign the user id instead
from .forms import LoginForm, RegisterForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth import get_user_model
def test_view(request):
form = BioForm(request.POST)
user = get_user_model
if form.is_valid():
profile = form.save(commit=False)
profile.user_id = request.user.id
profile.phone_number = request.phone_number
profile.save()
return render(request, 'test.html', {'form': form})
Your problem is that the user you try to save with, is not an authenticated user that exists in the database. Only authenticated (logged in) users exist in the database and can be used in a relational field

django user creation using UserCreationForm issue

As per youtube tutorial the user is created with exactly same method but mine doesn't work. Why?
views.py
from django.shortcuts import render,redirect
from .forms import CreateUserForm
def registerView(request):
form=CreateUserForm()
if request.method=="POST":
form=CreateUserForm(request.POST)
if form.is_valid():
form.save()
user=form.cleaned_data.get('username')
messages.success(request,'Account was successfully created for '+ user)
return redirect('login')
context={'form':form}
return render(request,"accounts/register.html", context)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2']
Why is a user not created?

IntegrityError at /signup-login/ duplicate key value violates unique constraint sts

i am getting this "duplicate key value violates unique constraint "myblog_profile_email_3f46e9ef_uniq"
DETAIL: Key (email)=() already exists." error every time when i submit my signup form even with new email address.values save inside User table but it not redirect it on home page.
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
# Create your models here.
class Profile(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
first_name=models.CharField(max_length=50,blank=True)
last_name=models.CharField(max_length=50,blank=True)
email=models.EmailField(max_length=120)
bio=models.TextField(blank=True)
gender_choices=(('M','Male'),('F','Female'),('S','Special'))
gender=models.CharField(max_length=1,choices=gender_choices,default='M')
age=models.PositiveIntegerField(default=12)
def __str__(self):
msg = "Name : {0} {1}|| Email : {2} || gender : {3}".format(self.first_name,self.last_name,self.email,self.gender)
return msg
#receiver(post_save, sender=User)
def ensure_profile_exists(sender, **kwargs):
if kwargs.get('created', False):
Profile.objects.get_or_create(user=kwargs.get('instance'))
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
# first_name=forms.CharField(max_length=40,help_text="first Name")
# last_name=forms.CharField(max_length=40,help_text="first Name")
email=forms.EmailField(max_length=120)
class Meta:
model=User
fields=('username','email','password1','password2')
views.py
from django.shortcuts import render
from .forms import SignUpForm
from django.shortcuts import redirect
from django.contrib.auth import login,authenticate
from .models import Profile
# Create your views here.
def index(request):
return render(request,'myblog/home.html')
def signUp(request):
form=SignUpForm(request.POST)
if form.is_valid():
user=form.save()
user.refresh_from_db()
# user.profile.first_name=form.cleaned_data.get('first_name')
# user.profile.lastname=form.cleaned_data.get('last_name')
user.profile.email=form.cleaned_data.get('email')
user.save()
username=form.cleaned_data.get('username')
password=form.cleaned_data.get('password1')
user=authenticate(username=username,password=password)
login(request,user)
return redirect('http://127.0.0.1:8000/')
else:
print('form not submitted successfully \n')
form=SignUpForm()
return render(request,'myblog/signup.html',{'form':form})
i am new please also help me to explain why thanks in advance

UNIQUE constraint failed: new__users_profile.user_id. Python Django

django.db.utils.IntegrityError UNIQUE constraint failed
sqlite3.IntegrityError: UNIQUE constraint failed: new__users_profile.user_id
The above exception was the direct cause of the following exception:
new__users_profile.user_id
Error occurs when I'm trying to register new user, login to an existing user and when I am trying to migrate. I've tried to delete all migrations and migrate once again but it didn't help
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
class Media(models.Model):
image_name = models.CharField(max_length=50)
image_description = models.CharField(max_length=80)
image_image = models.ImageField(upload_to='media', default='default.jpg')
views
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .forms import UserRegisterForm, MediaForm
from .models import Media
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
#login_required
def profile(request):
if request.method == 'GET':
media_images = Media.objects.all()
context = {
'media_images':media_images,
}
return render(request, 'users/profile.html', context)
#login_required
def add_media(request):
if request.method == 'POST':
form = MediaForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('http://127.0.0.1:8000/')
else:
form = MediaForm()
return render(request, 'users/add_media.html', {'form':form})
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import *
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class MediaForm(forms.ModelForm):
class Meta:
model = Media
fields = ['image_name', 'image_description', 'image_image']
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
I think you need primary_key=True,
class Profile(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, null=True)
In class profile, add primary_key=True and remove null=True
user = models.OneToOneField(User,primary_key=True, on_delete=models.CASCADE)
I hope it will work!

ImportError: cannot import name 'UserUpdateForm' from 'register.forms'

i am beginner to the django and i am getting this error while loading server.So please help
This is my register/views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'register/register.html', {'form': form})
#login_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'register/profile.html', context)
This is my register/signal.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
This is my forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
This is register/apps.py
from django.apps import AppConfig
class RegisterConfig(AppConfig):
name = 'register'
def ready(self):
import register.signals
The error its showing is from here = from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
Please have a look what i am doing wrong..
Your forms.py only has a UserRegisterForm. The error complains about the fact that it can not import the UserUpdateForm (and likely if you remove that, it will complain about the ProfileUpdateForm, since that is not defined either). You can fix the problem with the UserUpdateForm by importing it from the django.contrib.auth.forms module, and re-export it. For ProfileUpdateForm, you will need to implement additional forms:
# register/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserUpdateForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
exclude = ['user']

Categories

Resources