Upon signup, I'd like to request the user for:
Full name (I want to save it as first and last name though)
Company name
Email
Password
I've read through dozens of similar situations on StackOverflow. In models.py, I extend the User model like so:
# models.py
class UserProfile(models.Model):
company = models.CharField(max_length = 50)
user = models.OneToOneField(User)
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)
Source: Extending the User model with custom fields in Django
I've also added:
# models.py
class SignupForm(UserCreationForm):
fullname = forms.CharField(label = "Full name")
company = forms.CharField(max_length = 50)
email = forms.EmailField(label = "Email")
password = forms.CharField(widget = forms.PasswordInput)
class Meta:
model = User
fields = ("fullname", "company", "email", "password")
def save(self, commit=True):
user = super(SignupForm, self).save(commit=False)
first_name, last_name = self.cleaned_data["fullname"].split()
user.first_name = first_name
user.last_name = last_name
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
And in views.py:
# views.py
#csrf_exempt
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
new_user = form.save()
first_name, last_name = request.POST['fullname'].split()
email = request.POST['email']
company = request.POST['company'],
new_user = authenticate(
username = email,
password = request.POST['password']
)
# Log the user in automatically.
login(request, new_user)
Right now, it doesn't store the company name. How do I do that?
user_profile = new_user.get_profile()
user_profile.company = company
user_profile.save()
Don't forget to configure your UserProfile class in settings so Django knows what to return on user.get_profile()
Related
I have made a form having fields of personal information and login information as one
models.py
class EmployeeModel(models.Model)
employee_id = models.CharField(max_length=300,unique=True,help_text='Employee ID should not be same')
name = models.CharField(max_length=300)
username = models.CharField(max_length=50,null=True,blank=True)
email = models.EmailField(null=True,blank=True)
password = models.CharField(max_length=20,null=True,blank=True)
password_confirm = models.CharField(max_length=20,null=True,blank=True)
forms.py
class EmployeeForm(forms.ModelForm):
class Meta:
model = employeeModel
fields = ('__all__')
views.py
User = get_user_model()
def create_view(request):
if request.method == 'POST':
form = employeeForm(request.POST or None,request.FILES or None)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
User= get_user_model()
user= User.objects.create_user(username=username,email=email,password=password)
authenticate(request,username=username,email=email,password=password)
form.save()
return redirect('emp_list')
else:
form = employeeForm()
return render(request,'create_employee.html',{'form':form})
Its not showing any error but User.objects.all() shows only superuser not the users i created though this form. Those users i have created in this form are are showing up in Employee.objects.get(username='foo')
So what to do? I cant login through those non_superusers. it throws invalid login error. How to fix this?
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.
I am adding in some functionality that allows a user to edit their personal profile page information. When the user updates their info and hit submit they are getting a NameErrorsaying that the user is not defined. Below is how I am trying to implement the editing functionality.
forms
#this is all the information that the user is allowed to edit.
class UpdateProfile(forms.ModelForm):
username = forms.CharField(required=False)
email = forms.EmailField(required=False)
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
age = forms.IntegerField(required=False)
height = forms.IntegerField(required=False)
weight = forms.IntegerField(required=False)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'age', 'height', 'weight')
def clean_email(self):
username = self.cleaned_data.get('username')
email = self.cleaned_data.get('email')
if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError('This email address is already in use. Please supply a different email address.')
return email
def save(self, commit=True):
# user = super(RegisterUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
#This is where i am trying to save the new information.
if commit:
user.save()
#This is where i am returning the user.
return user
Views
def update_profile(request):
args = {}
if request.method == 'POST':
form = UpdateProfile(request.POST, instance=request.user)
form.actual_user = request.user
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('account:profile.html'))
else:
form = UpdateProfile()
args['form'] = form
return render(request, 'account/edit_profile.html', args)
Weird issue with by registration form, not sure i am doing wrong.
I have StudentProfile Model, that I am trying to save data from StudentResistrationForm but the data is not being saved into database
ERROR: NameError at /register/ name 'StudentProfile' is not defined
Is the view logic correct? What am I missing? Ideas please
model
class Accounts(AbstractUser):
email = models.EmailField('email address', unique=True)
first_name = models.CharField('first name', max_length=30, blank=True)
last_name = models.CharField('last name', max_length=30, blank=True)
date_joined = models.DateTimeField('date joined', auto_now_add=True)
# asdd
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
class StudentProfile(models.Model):
user = models.OneToOneField('Accounts', related_name='student_profile')
# additional fields for students
AMEB_Ratings = models.PositiveIntegerField(default=0)
is_student = models.BooleanField('student status', default=False)
form
class StudentResistrationForm(forms.ModelForm):
class Meta:
model = StudentProfile
fields = (
'AMEB_Ratings',
)
def save(self, commit=True):
user = super(StudentResistrationForm, self).save(commit=False)
# user.first_name = self.cleaned_data['first_name']
# user.last_name = self.cleaned_data['last_name']
user.AMEB_Ratings = self.cleaned_data['AMEB_Ratings']
if commit:
user.save()
return user
class UserForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = ('username', 'email', 'password')
view
def registerStudent(request):
# Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
if request.method == "POST":
user_form = UserForm(request.POST)
form = StudentResistrationForm(request.POST)
if form.is_valid() and user_form.is_valid():
User = get_user_model()
username = user_form.cleaned_data['username']
email = user_form.cleaned_data['email']
password = user_form.cleaned_data['password']
new_user = User.objects.create_user(username=username, email=email, password=password)
Student_profile = StudentProfile()
Student_profile.user = new_user
Student_profile.AMEB_Ratings = request.POST['AMEB_Ratings']
# Student_profile = StudentProfile.create_user(AMEB_Ratings=AMEB_Ratings)
new_user.save()
Student_profile.save()
# form.save()
# AMEB_Ratings = form.cleaned_data['AMEB_Ratings']
return redirect('/')
else:
# Create the django default user form and send it as a dictionary in args to the reg_form.html page.
user_form = UserForm()
form = StudentResistrationForm()
# args = {'form_student': form, 'user_form': user_form }
return render(request, 'accounts/reg_form_students.html', {'form_student': form, 'user_form': user_form })
Looks like you have a few typos you currently are setting your email variable to the email data then setting it to the password data. Correct this first.
email = user_form.cleaned_data['email']
password = user_form.cleaned_data['password']
I am trying to make a webapp that includes register/login operations. The login is working fine but the registration form is frustrating.
I have a class registration form that inherits from UserCreationForm. The users are created and seen in the admin page when created but the problem I am having is not being able to see them in my UserProfile model in the admin page. It does not link the information and I could not find a way the link them.
Here is the registration form:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
city = forms.CharField(required=False)
country = forms.CharField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
username = forms.CharField(required=True)
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'country',
'city',
'email'
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
#user.first_name = self.cleaned_data['first_name']
if commit:
user.save()
return user
Here are my models:
class UserProfile(models.Model):
user = models.OneToOneField( User,
on_delete=models.CASCADE
)
username = models.TextField(max_length=30, default="")
first_name = models.TextField(max_length=30, default="")
last_name = models.TextField(max_length=30, default="")
country = models.TextField(max_length=30, default="Which country are you from?")
city = models.TextField(max_length=30, default="Which city are you from?")
class ColorChoice(models.Model):
user = models.ForeignKey(
'UserProfile',
on_delete=models.CASCADE
)
color1 = models.IntegerField()
color2 = models.IntegerField()
color3 = models.IntegerField()
color4 = models.IntegerField()
color5 = models.IntegerField()
and my view.py that does the registering:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('color')
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'account/create_new.html', args)
Your form is only creating a new objects for User. You would need to add a signal for example to create a new object for UserProfile.
Something like this:
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
signals.post_save.connect(create_user_profile, sender=User)