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()
# …
Related
first post here. Im trying to query the user so i from the form so i can save the user in my database.
This is my code
form = lageBruker(request.POST)
bruker = User.objects.create(format(request.POST['username']))
print()
if request.method == 'POST':
if form.is_valid():
fornavn = request.POST['first_name']
etternavn = request.POST['last_name']
email = request.POST['email']
kunde = Kunde.objects.create(
#bruker = bruker,
fornavn=fornavn,
etternavn=etternavn,
email=email
)
kunde.save()
context = {'form': form}
return render(request, 'ebutikk/registrer.html', context)
Kunde Model:
class Kunde(models.Model):
bruker = models.OneToOneField(
User, null=True, blank=True, on_delete=models.CASCADE)
fornavn = models.CharField(max_length=200, null=True, blank=True)
etternavn = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.etternavn
What im trying to do is, when the registration form is submittet, i want to save the registerd user as a kunde/customer. I dont have a User model, i use the default made by django with the import:
from django.contrib.auth.models import User
I make the form by importing the user creation form given by django and customizing it im my forms.py file.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class lageBruker(UserCreationForm):
class Meta:
model = User
fields = ['username',
'email',
'first_name',
'last_name',
'password1',
'password2']
Normally, you'd simply create the Kunde model like this:
class Kunde(models.Model):
bruker = models.OneToOneField(
User, null=True, blank=True, on_delete=models.CASCADE)
# more fields here, so the model makes sense
#property
def fornavn(self): return self.user.first_name
#property
def etternavn(self): return self.user.last_name
#property
def email(self): return self.user.email
Then all you need to do is:
def customer_signup_view(self, request):
if request.method == "POST":
form = lageBruker(request.POST)
# Saving the model form returns the user created
user = form.save()
# Now use that user to create a new customer
Kunde.objects.create(user=user)
return redirect("success/")
return render(request, 'ebutikk/registrer.html', {"form": lageBruker())
I want to save the values that users enter into the repository. But if the user has already entered a value, I want it to update.
It's saving the data right now. But it cannot update.
I' am use Django
forms.py
class Meta():
model = UserProfileInfo
fields = ('apikey', 'apivalue', 'apisupplier')
views.py
def user_set_api(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
current_user = request.user
user_form = UserProfileInfoForm(data=request.POST)
user_id = current_user.id
print('UserId:', user_id)
if user_form.is_valid() and user_id:
user_form.save(request.user)
print('User: ', user, 'Userformid:', UserProfileInfo(['user_id']))
else:
print(user_form)
else:
keysvalue = UserProfileInfoForm()
return render(request, 'form.html',
{'apisupplier': UserProfileInfo})
models.py
user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE)
apisupplier = models.CharField(max_length=40, blank=True, default="null")
apikey = models.CharField(max_length=40, blank=True, default="null")
apivalue = models.CharField(max_length=40, blank=True, default="null")
def __str__(self):
template = '{0.user} {0.apikey} {0.apivalue} {0.apisupplier}'
return template.format(self)```
I'm not sure why you are passing the user id to form.save(). You need to pass the user object to the form instantiation:
if request.method == 'POST':
...
user_form = UserProfileInfoForm(data=request.POST, instance=request.user)
if user_form.is_valid()
user_form.save()
...
else:
user_form = UserProfileInfoForm(instance=request.user)
return render(request, 'form.html',
{'apisupplier': UserProfileInfo, "user_form": user_form})
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 have been struggling with this for a couple of weeks now and It seems, I can't get it to work.
As you sign up on my website, you are able to create a userprofile and a company. Then, you are able to add members to your company, however the signal just fires everytime and creates empty companies. How do I stop django from doing this?
model.py
class Companyname(models.Model):
company_name = models.CharField(max_length=100, default = '', null=True, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.TextField(max_length=10000, default = '', null=True, blank=True)
def __str__(self):
return self.company_name
#receiver(post_save, sender=User)
def update_user_company(sender, instance, created, **kwargs):
if created:
Companyname.objects.create(user=instance)
if instance.companyname.company_name is '':
print("just print this")
else:
instance.companyname.save()
the company gets stored on the userprofile
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default = '', null=True, blank=True)
company = models.ForeignKey(Companyname, null=True, on_delete=models.CASCADE)
role = models.ForeignKey(Role, null=True, on_delete=models.CASCADE)
team = models.ForeignKey(Team, null=True, on_delete=models.CASCADE)
company_admin = models.BooleanField(default=False)
add_user view.py
def add_user(request):
if request.method == 'POST':
form = AddUserForm(request.POST)
if form.is_valid():
company = request.user.userprofile.company_id
form.save()
user = form.save()
user.refresh_from_db()
user.userprofile.company_id = company
user.userprofile.role = form.cleaned_data.get('role')
user.is_active = False
user.save()
register view.py
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db() # load the profile instance created by the signal
user.userprofile.description = form.cleaned_data.get('description')
user.companyname.company_name = form.cleaned_data.get('company_name')
user.userprofile.company_id = user.companyname.id
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('/account/my_product')
else:
form = RegistrationForm()
return render(request, 'accounts/reg_form.html', {'form': form})
Hope someone can help :)
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']