'AnonymousUser' object has no attribute 'company' - python

Greeting,
I am trying to add to User form a new CharField named company but even when the field is filled the data are not saved... I tried the following with no success as I got the error in the title.
views.py
def register(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user_frm = form.save(commit = False)
user_frm.company = request.user.company
user_frm.save()
username = form.cleaned_data.get('username')
messages.success(request, f"Registration Complete! User: {username}")
username = form.cleaned_data.get('username')
login(request, user_frm)
return redirect("main:homepage")
else:
for msg in form.error_messages:
messages.error(request, f"{msg}:{form.error_messages[msg]}")
return render(request = request,
template_name = "main/register.html",
context={"form":form})
form = NewUserForm
return render(request,
"main/register.html",
context={"form":form})
forms.py
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
company = forms.CharField( max_length= 500)
class Meta:
model = User
fields = ("username", "email", "company", "password1", "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
user.company = self.cleaned_data["company"]
if commit:
user.save()
return user

Try this:
models.py
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
nickname = models.CharField("昵称", max_length=20, null=True, blank=True)
company = models.CharField(max_length=200, null=True, blank=True)
class Meta:
verbose_name = verbose_name_plural = "个人信息"
def __str__(self):
return self.nickname or self.user.username
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_profile(sender, instance, created, **kwargs):
"""创建user的同时自动创建profile并与之关联"""
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def save_user_profile(sender, instance, **kwargs):
"""保存user的同时也保存对应的profile"""
instance.profile.save()
views.py
def register(request):
form_class = NewUserForm
if request.method == "POST":
form = form_class(request.POST)
if form.is_valid():
user = form.save()
messages.success(request, f"Registration Complete! User: {user.username}")
login(request, user)
return redirect("main:homepage")
else:
form = form_class()
return render(request, "main/register.html", {"form":form})
forms.py
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
company = forms.CharField(max_length= 500)
def save(self, commit=True):
if not commit:
return super().save(commit=commit)
company = self.cleaned_data.pop("company", None)
user = super().save()
user.profile.company = company
user.profile.save()
return user
class Meta:
model = User
fields = ("username", "email", "company", "password1", "password2")

SOLVED using the following:
def update_user_data(user):
Profile_Reg.objects.update_or_create(user=user, defaults={'company': user.company,})
def register(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.company = form.cleaned_data.get('company')
update_user_data(user)
user.save()
raw_password = form.cleaned_data.get('password1')
username = form.cleaned_data.get('username')
messages.success(request, f"Registration Complete! User: {username}")
#breakpoint()
#user = authenticate(username=user.username, password=raw_password)
#breakpoint()
login(request, user)
return redirect("main:homepage")
else:
for msg in form.error_messages:
messages.error(request, f"{msg}:{form.error_messages[msg]}")
return render(request = request,
template_name = "main/register.html",
context={"form":form})
form = NewUserForm
return render(request,
"main/register.html",
context={"form":form})
where Profile_Reg is a model:
class Profile_Reg(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
company = models.CharField(max_length=5000)
def __str__(self):
return str(self.user)

Related

Django login problems

I can register new user. But after logout, I cannot login again .It shows user does not exist. But when I checked admin panel I get hashed password.....
forms.py
class UserLoginForm(forms.Form):
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
email = self.cleaned_data.get("email")
password = self.cleaned_data.get("password")
if email and password:
user = authenticate(email=email, password=password)
if not user:
raise forms.ValidationError("User Does Not Exist.")
if not user.check_password(password):
raise forms.ValidationError("Password Does not Match.")
if not user.is_active:
raise forms.ValidationError("User is not Active.")
return super(UserLoginForm, self).clean(*args, **kwargs)
views.py
def login_view(request): # users will login with their Email & Password
if request.user.is_authenticated:
return redirect("/")
else:
title = "Login"
form = UserLoginForm(request.POST or None)
if form.is_valid():
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
# authenticates with Email & Password
user = authenticate(email=email, password=password)
login(request, user)
return redirect("/")
context = {"form": form,
"title": title
}
return render(request, "accounts/login.html", context)
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.CharField(max_length=500, null=True)
about = models.CharField(max_length=1000, null=True)
slogan = models.CharField(max_length=500, null=True)
def __str__(self):
return self.user.username
class Gig(models.Model):
CATEGORY_CHOICES = (
("GD", "Graphics & Design"),
("DM", "Digital & Marketing"),
("VA", "Video & Animation"),
("MA", "Music & Audio"),
("PT", "Programming & Tech")
)
title = models.CharField(max_length=500)
category = models.CharField(max_length=2, choices=CATEGORY_CHOICES)
description = models.CharField(max_length=1000)
price = models.IntegerField(default=6)
photo = models.FileField(upload_to='gigs')
status = models.BooleanField(default=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
create_time = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
class Purchase(models.Model):
gig = models.ForeignKey(Gig, on_delete=models.CASCADE)
buyer = models.ForeignKey(User, on_delete=models.CASCADE)
time = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.gig.title
class Review(models.Model):
gig = models.ForeignKey(Gig, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.CharField(max_length=500)
def __str__(self):
return self.content
I can register new user. But after logout, I cannot login again .It shows user does not exist. But when I checked admin panel I get hashed password.....
registration view.....
def register_view(request): # Creates a New Account & login New users
if request.user.is_authenticated:
return redirect("/")
else:
title = "Register"
form = UserRegistrationForm(request.POST or None, request.FILES or None)
if form.is_valid():
user = form.save(commit=False)
password = form.cleaned_data.get("password1")
user.set_password(password)
user.save()
prof = Profile(user=user)
prof.save()
authenticate(email=user.email, password=password)
login(request, user)
return redirect("/")
context = {"title": title, "form": form}
return render(request, "accounts/form.html", context)
def logout_view(request): # logs out the logged in users
if not request.user.is_authenticated:
return redirect("login")
else:
logout(request)
return redirect("/")

I have a confusion about creating the user profile when the user is newly registered

views.py
def register_view(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user = form.save()
## login(request,user)
messages.success(request,'Account created succcessfully')
return redirect('login')
else:
messages.error(request,'Invalid information! Please retry!')
else:
form = UserForm()
context = {'form':form}
return render(request,'register.html',context)
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
if user is not None:
login(request,user)
return redirect('homepage')
else:
messages.error(request,'No current user!')
else:
form = AuthenticationForm()
context = {'form':form}
return render(request,'login.html',context)
def logout_view(request):
logout(request)
return redirect('login')
#login_required
def profile(request):
Profile.objects.get_or_create(user=request.user)
if request.method == 'POST':
u_form = UserUpdateForm(request.POST,instance=request.user)
p_form = ProfileForm(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,'Profile updated successfully!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileForm(instance=request.user.profile)
context = {
## 'user':request.user,
'u_form':u_form,
'p_form':p_form,
}
return render(request,'profile.html',context)
signals.py
#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()
models.py
class Profile(models.Model):
name = models.OneToOneField(User,on_delete=models.CASCADE)
mobile = models.IntegerField(null=True)
address = models.CharField(max_length=350,null=True)
image = models.ImageField(upload_to='profile_pics', default='default.png',null=True)
def __str__(self):
return str(self.name.username)+'\'s Profile'
forms.py
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['mobile', 'address', 'image']
Error msg:
RelatedObjectDoesNotExist at /login/
User has no profile.
I am facing an issue that the user profile could not get created or updated although I used the signals for the profile model. When I login a registered user, the error message told me that User has no profile. However if I login a user that has created a profile it could show the related information so for newly registered user how to automatically create a profile for that user?
because you have a existing which does not have any profile because didn't load signal then wile creating that user if it is superuser create the new superuser from terminal delete the existing one who doesn't have profile after login in admin panel by the way i am also using signal for my web here is the code how i use it
my models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
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,)
profile_pic = models.ImageField(upload_to='profile_pics', default='default.png',)
first_name = models.CharField(max_length=50, blank=True)
last_name = models.CharField(max_length=75, blank=True)
dob = models.DateField(blank=True, null=True)
joined_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, *args, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
tell me if you still got error

Populate OneToOneField after submitting form Django

I wrote the following code which creates a new user and tries to create a profile for that user:
class RegisterForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = CustomUser
fields = ('username', 'email', 'password1', 'password2')
#login_required(login_url="/login")
def index(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
profile = Profile().save()
user = form
user.profile = profile
user.save()
return redirect('users')
else:
print(form.errors)
else:
form = RegisterForm()
user_model = get_user_model()
users = user_model.objects.all()
paginator = Paginator(users, 15)
page = request.GET.get('page')
users = paginator.get_page(page)
return render(request, 'users/index.html', {'users': users, 'form': form})
class Profile(models.Model):
has_premium_until = models.DateTimeField(null=True, blank=True)
has_premium = models.BooleanField(default=False)
has_telegram_premium_until = models.DateTimeField(null=True, blank=True)
has_telegram_premium = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
class CustomUser(AbstractUser):
email = models.EmailField(max_length=255, unique=True)
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True)
When I'm submitting the form the user as well as the profile is created but the profile is not stored in the user (the profile_id stays null).
Anyone who can help me out?
Your user is actually just a reference to the ProfileForm you constructed. You can obtain the user that has logged in with request.user. So you can update the user with:
#login_required(login_url='/login')
def index(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
profile = Profile().save()
user = request.user
user.profile = profile
user.save()
return redirect('users')
else:
print(form.errors)
else:
form = RegisterForm()
# …

Django ModelForm not retrieving field's value

I'm using two ModelForms to create na user with a Profile instance. Profile ModelForm has a single field. I'm doing form.save(commit=False), setting the required field (country) other than the one in the form and saving. I get an error saying that 'country_id' cannot be null.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
bio = models.TextField(blank=True)
avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
email_confirmed = models.BooleanField(default=False)
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
forms.py
class UserRegisterForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class ProfileRegisterForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['country']
views.py
def register(request):
if request.method == 'POST':
user_form = UserRegisterForm(request.POST)
profile_form = ProfileRegisterForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save(commit=False)
user.is_active = False
profile = profile_form.save(commit=False)
profile.user = user
user.save()
current_site = get_current_site(request)
subject = 'Activate Your Account'
message = render_to_string('account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token': account_activation_token.make_token(user)
})
user.email_user(subject, message)
return redirect('activation_email_sent')
else:
user_form = UserRegisterForm()
profile_form = ProfileRegisterForm()
return render(request, 'register.html', {'user_form': user_form, 'profile_form': profile_form})
Yeah. I removed the post_save, made country nullable and saved user and profile separately. Thanks for the help.
views.py
def register(request):
if request.method == 'POST':
user_form = UserRegisterForm(request.POST)
profile_form = ProfileRegisterForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save(commit=False)
user.is_active = False
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()

Django extended UserProfile model is not saving my extra informations

I have a UserProfile model extending contrib.auth.User, and when I try to save it, the extra information I added in the profile is not saved.
Here is Models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
related_name='profile')
cellphone = models.CharField(max_length=20, blank=True, default='')
def __str__(self):
return self.user.username
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created =
UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
And forms.py
class UserProfileForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField(required=True)
cellphone = forms.CharField(max_length=20)
class Meta:
model = User
# fields = ('cellphone', )
fields = ('username', 'cellphone', 'email', 'password', )
And finally my view.py
def register(request):
form = UserProfileForm(request.POST or None)
if form.is_valid():
user = form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.profile.cellphone = form.cleaned_data['cellphone']
user.set_password(password)
user.save()
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth_login(request, user)
return render(request, 'user/index.html', {'user': user})
else:
return render(request, 'user/register.html', {'form': form, })
I couldn't figure out why it is not saving the cellphone attribute.
Add user.profile.save() in view after user.profile.cellpone = ... line.

Categories