How can I save values with user.id to Database - Django - python

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})

Related

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()
# …

Why if I delete username field in django forms.ModelForm, registration fails?

I have a working example of a registration with username & email. I want to make it email only. When I start to manipulate it (ex. delete "username" in class UserForm (forms.py), I get IntegrityError at /application/register/ UNIQUE constraint failed: auth_user.username). How can I fix this?
models.py
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# additional
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to="profile_pics", blank=True)
def __str__(self):
return self.user.username
forms.py
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ("username", "email", "password")
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model = UserProfileInfo
fields = ("portfolio_site","profile_pic" )
views.py
def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if "profile_pic" in request.FILES:
profile.profile_pic = request.FILES["profile_pic"]
profile.save()
registered = True
else:
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(request, 'application/register.html', {
"user_form":user_form,
"profile_form":profile_form,
"registered":registered})

Register Form not saving to database: Django?

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']

Django - how to save my hashed password

I'm trying to save my hashed password in my database, but It keeps saving my plaintext password
Models:
class StudentRegistration(models.Model):
email = models.EmailField(max_length=50)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
password = models.CharField(max_length=100, default="", null=False)
prom_code = models.CharField(max_length=8, default="", null=False)
gender = (
("M","Male"),
("F","Female"),
)
gender = models.CharField(max_length=1, choices=gender, default="M", null=False)
prom_name = models.CharField(max_length=20, default="N/A")
prom_year = models.IntegerField(max_length=4, default=1900)
school = models.CharField(max_length=50, default="N/A")
def save(self):
try:
Myobj = Space.objects.get(prom_code = self.prom_code)
self.prom_name = Myobj.prom_name
self.prom_year = Myobj.prom_year
self.school = Myobj.school_name
super(StudentRegistration, self).save()
except Space.DoesNotExist:
print("Error")
Views:
def register_user(request):
args = {}
if request.method == 'POST':
form = MyRegistrationForm(request.POST) # create form object
if form.is_valid():
clearPassNoHash = form.cleaned_data['password']
form.password = make_password(clearPassNoHash, None, 'md5')
form.save()
form = MyRegistrationForm()
print ('se salvo')
else:
print ('Error en el form')
else:
form = MyRegistrationForm()
args['form'] = form #MyRegistrationForm()
return render(request, 'register/register.html', args)
I've printed the hashed result so I know it is hashing but not saving that.
Am I using the make_password wrong? or is there any better way to protect my passwords?
--------------------------UPDATE:(The Solution)----------------------------
Remember In settings.py:
#The Hasher you are using
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
Models.py:
#Import and add the AbstractBaseUser in your model
class StudentRegistration(AbstractBaseUser, models.Model):
Views.py:
if form.is_valid():
user = form.save(commit=False)
clearPassNoHash = form.cleaned_data['password']
varhash = make_password(clearPassNoHash, None, 'md5')
user.set_password(varhash)
user.save()
Use Django set_password in the documentation
https://docs.djangoproject.com/en/1.9/ref/contrib/auth/
You also need to get your model object from the form using form.save(commit=False)
if form.is_valid():
# get model object data from form here
user = form.save(commit=False)
# Cleaned(normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# Use set_password here
user.set_password(password)
user.save()
Save the object first, without committing to DB, then update password before a final save. Make sure your imports are all correct.
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST) # create form object
if form.is_valid():
new_object = form.save(commit=False)
new_object.password = make_password(form.cleaned_data['password'])
new_object.save()
messages.success(request, "Form saved.")
return redirect("somewhere")
else:
messages.error(request, "There was a problem with the form.")
else:
form = MyRegistrationForm()
return render(request, 'register/register.html', { 'form': form })

Django unable to encrypt user password info and unable to retrieve userprofile information

I have a web application which has user registration and update user profile. I am using password hashers.
This is my models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
def __unicode__(self):
return self.user.username
This is my forms.py
class UserForm(forms.ModelForm):
username = forms.CharField(
max_length=254,
widget=forms.TextInput(attrs={'class': "form-control input-lg",'placeholder': 'username'}),
)
email = forms.CharField(
max_length=254,
widget=forms.TextInput(attrs={'class': "form-control input-lg",'placeholder': 'email'}),
)
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': "form-control input-lg",'placeholder': 'password'}))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': "form-control input-lg",'placeholder': 'confirm password'}),label="Confirm password")
class Meta:
model = User
fields = ('username', 'email', 'password','password2')
class UserProfileForm(forms.ModelForm):
website = forms.URLField(widget=forms.TextInput(attrs={'class': "form-control input-lg",'placeholder': 'website'}))
picture=form.Imagefield
class Meta:
model = UserProfile
fields = ('website', 'picture')
This is my views.py update and register
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
profile.save()
registered = True
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request,
'Survey/register.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
#login_required
def update(request):
updated = False
user = request.user
profile=request.userprofile
# If it's a HTTP POST, we're interested in processing form data.
if request.method == 'POST':
user_form = UserForm(data=request.POST,instance=user)
profile_form = UserProfileForm(data=request.POST,instance=profile)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
u = User.objects.get(username=user.username)
u.set_password(user.password)
u.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
profile.save()
update = True
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm(instance=user)
profile_form = UserProfileForm()
return render(request,
'Survey/update_profile.html.html',
{'user_form': user_form,'profile_form': profile_form,'updated': updated} )
I have two problems with this
I am able to retrieve the user information but not user profile information
The password field I updated is stored without hashing (during registration the password is stored with hashing) so I am unable to login with the new password as authentication fails
Any help?

Categories