Populate Django username field with generated username - python

I would like the user name field for my Django registration to populate with the following function -
def generateUsername():
username = firstname[0] + middlename[0] + lastname[0] + randomStringDigits(6) + getDateTimeStr()
return username
I am currently using the UserRegisterForm model from Django and would prefer to find away to integrate into this, however if the best option is to custom my own user model then I am happy to do this also.
views.py -
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})
forms.py -
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
firstname = forms.CharField(max_length=20)
middlename = forms.CharField(max_length=20)
lastname = forms.CharField(max_length=20)
class Meta:
model = User
fields = ['email', 'firstname', 'middlename', 'lastname']

You can set this to the user object wrapped in the form:
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
data = form.cleaned_data
username = f"{data['firstname'][0]}{data['middlename'][0]}{data['lastname'][0]}{randomStringDigits(6)}"
form.instance.username = username
form.save()
messages.success(request, f'Account created for {username}')
return redirect('login')

Related

Django having problem in adding user to specific group

forms.py
class UserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username','email','password1','password2')
def save(self,commit=True):
user = super(UserForm,self).save(commit=False)
user.set_password = self.cleaned_data['password1']
user.email = self.cleaned_data['email']
if commit:
user.save()
views.py
def register_view(request):
form = UserForm()
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user = form.save()
customer_group = Group.objects.filter(name='CUSTOMER').exists()
if customer_group:
Group.objects.get(name='CUSTOMER').user_set.add(user)
else:
Group.objects.create(name='CUSTOMER')
Group.objects.get(name='CUSTOMER').user_set.add(user)
messages.success(request,'註冊成功! 請按指示登入!')
return redirect('login')
else:
messages.error(request,'註冊無效! 請再試過!')
context = {'form':form}
return render(request,'customer/register.html',context)
When I try to register a new user, the form can be successfully saved and the group CUSTOMER can be added but I have a problem if I want to add that user to the group so are there any methods in order to add the user to the group automatically after that user had registered a new account along with the User model?
As #Iain Shelvington says, the form.save() method should return the user object. But there is no need to override the save() method: the UserCreationForm already does that.
class UserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username','email')
# no save method
In the view you can simplify the logic to:
def register_view(request):
form = UserForm()
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user = form.save()
customer_group, __ = Group.objects.get_or_create(name='CUSTOMER')
customer_group.user_set.add(user)
messages.success(request,'註冊成功! 請按指示登入!')
return redirect('login')
else:
messages.error(request,'註冊無效! 請再試過!')
context = {'form':form}
return render(request,'customer/register.html',context)

Django forms is_valid() for registration, always false

I'm still learning django and I'm trying to create a register and login page.
I beleive i created the form right, and the .is_valid() looks good to me also, I have no idea what i did wrong.
every time I submit the register form, it fails and renders the else condition, same with the login function, even thought I went into admin to add a user manually.
my user model is called 'Users'
Forms:
class reg_form(forms.Form):
username = forms.CharField(label='username', max_length=64)
password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField(label="email", max_length=64)
phone = forms.CharField(label='Phone', max_length=64)
first_name = forms.CharField(label='First Name', max_length=64)
last_name = forms.CharField(label='Last Name', max_length=64)
class log_form(forms.Form):
username = forms.CharField(label='username', max_length=64)
password = forms.CharField(widget=forms.PasswordInput)
Register:
def register(request):
if request.method == 'POST':
form = reg_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
phone = form.cleaned_data['phone']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
user = Users.objects.Create(username=username, email=email, password=password, phone=phone, first_name=first_name, last_name=last_name)
Users.save(user)
login(request, user)
return render(request, 'profile.html')
else:
return render(request, 'register.html', {
'form': reg_form
})
else:
return render(request, 'register.html', {
'form': reg_form
})
login:
def log_in(request):
if request.method == 'POST':
form = log_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return render(request, 'profile.html')
else:
return render(request, 'login.html', {
'form2': log_form
})
else:
return render(request, 'login.html', {
'form2': log_form
})
else:
return render(request, 'login.html', {
'form2': log_form
})
To see the errors you should return Bound Form:
def register(request):
if request.method == 'POST':
form = reg_form(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
email = form.cleaned_data.get'email')
phone = form.cleaned_data.get('phone')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
user = Users.objects.create(
username=username, email=email,
password=password, phone=phone,
first_name=first_name, last_name=last_name
)
login(request, user)
return render(request, 'profile.html')
else:
return render(request, 'register.html', {
# If the form not valid return bound form
'form': form
})
else:
return render(request, 'register.html', {
'form': reg_form
})
And do the same in your log_in view.
I suggest you to use ModelForm.
Also see Coding style (Django Docs):
Use InitialCaps for class names (or for factory functions that return
classes).
Field names should be all lowercase, using underscores instead of
camelCase.

RelatedObjectDoesNotExist at / User has no customer

RelatedObjectDoesNotExist at / User has no customer.
I am getting this error after I register a user and attempt to sign in. I am only able to sign in with a superuser I created but not with a new user I register.
views.py
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
#saving the registered user
form.save()
username= form.cleaned_data.get('username')
messages.success(request, f'Your Account has been created! You can now log in')
return redirect('login')
else:
form = UserCreationForm() #creates an empty form
return render(request, 'store/register.html', {'form': form})
#THIS IS THE ERROR IT LEADS ME TO
def store(request):
data = cartData(request)
cartItems = data['cartItems']
products = Product.objects.all() # getting all the products
context = {
'products': products,
'cartItems': cartItems
} # allows us to use in our template
return render(request, 'store/store.html', context)
models.py
class Customer(models.Model):
user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name=models.CharField(max_length=50, null=True)
email=models.CharField(max_length=200)
def __str__(self):
return self.name #this will show on our admin panel
Change your model class user field like this:
user=models.OneToOneField(
User,
null=True,
blank=True,
on_delete=models.CASCADE,
related_name="customer"
)
and your register view:
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
#saving the registered user
user = form.save()
Customer.objects.create(
user = user,
name = user.username,
email = user.email
)
username= form.cleaned_data.get('username')
messages.success(request, f'Your Account has been created! You can now log in')
return redirect('login')
else:
form = UserCreationForm() #creates an empty form
return render(request, 'store/register.html', {'form': form})
When you create user, you should create a customer for this user, for example:
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
#saving the registered user
user = form.save()
username= form.cleaned_data.get('username')
#create customer
Customer.objects.create(user=user, name=username, email=user.email)
...

I want to make sign in & up for my site with Django but it doesn't work

form.py
class SignUpForm(forms.Form):
name = forms.CharField(max_length=50, required=True)
email = forms.EmailField(max_length=100, required=True)
password = forms.CharField(max_length=20, required=True)
class SignInForm(forms.Form):
email = forms.EmailField()
password = forms.CharField(max_length=20, min_length=8)
view.py
def Sign_Up(request.POST):
if request.method == 'POST':
form = SignUpForm(request)
if form.is_valid():
cd = form.cleaned_data
name = cd['name']
email = cd['email']
password = cd['password']
us = User..objects.get(email__exact=email, password__exact=password)
return HttpResponseRedirect('/')
else:
form = SignUpForm()
return render(request,'User Login Page.html', {'form':form})
def Sign_In(request.POST):
if request.method =='POST' :
form = SignInForm(request)
if form.is_valid():
F = form.cleaned_data
Eemail = F['email']
Epassword = F['password']
try:
user = User.objects.filter(email=Eemail)
except User.DoesNotExist:
form = SignInForm()
return render(request, "Admin Login Page.html", {'form': form})
if User.password == Epassword:
return HttpResponseRedirect("/")
form = SignInForm()
return render(request,"Admin Login Page.html",{'form':form})
I want to make a sign in & up for my site with Django but it doesn't work!
When I click on the submit button my sign up directly goes to the HttpRsponseDirect address even with empty parameters
def Sign_Up(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
name = cd['name']
email = cd['email']
password = cd['password']
user = form.save()
user.refresh_from_db()
user.save()
user = authenticate(username=email, password=password)
return HttpResponseRedirect('/')
else:
form = SignUpForm()
return render(request,'signup.html', {'form':form})
def Sign_In(request):
if request.method =='POST' :
form = SignInForm(request)
if form.is_valid():
F = form.cleaned_data
Eemail = F['email']
Epassword = F['password']
user=authenticate(username=F,password=Epassword)
if user is not None:
return HttpResponseRedirect("/")
else:
form=SignInForm()
message='login failed'
retuen render(request,'login.html',{'form':form,'message':message})
look at upside code
Unless you have multiple security experts on the job; please, please, please let someone else handle your logins like Google or Facebook. like when you go to create account it says "use google to sign in"

Edit profile in Django

What I need is an edit profile form to edit username, password and avatar. But these fields are in two models.User and allusers (OneToOne). How can I create an edit profile form by combining the fields of both?
Models.py
class allusers(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='retest/static/images/')
def __str__(self):
return str(self.user)
Use a custom form and handle it in the view.
Here's a simple example.
forms.py
class UserEditForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
avatar = forms.FileField()
views.py
def user_edit_view(request):
if request.method == "POST" and request.FILES['file']:
form = UserEditForm(request.POST, request.FILES)
if form.is_valid():
your_file = request.FILES['file']
new_username = form.cleaned_data.get('username')
new_password = form.cleaned_data.get('password')
user = User.objects.get(username=request.user.username)
all_user = allusers.objects.get(user=user)
user.username = new_username
user.set_password(new_password)
user.save()
alluser.avatar = your_file
alluser.save()
return render(.................)
return HttpResponse(......)

Categories

Resources