Reputation: 12445
I am making django registration form
At first this code works well
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["username","email", "password1", "password2"]
def register(response):
if response.method == "POST":
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
return redirect("/login")
However now I want to make email as username, so my idea is like this
class RegisterForm(UserCreationForm): email = forms.EmailField()
class Meta:
model = User
fields = ["email", "password1", "password2"] #delete username from home.
def register(response):
if response.method == "POST":
if not response.POST._mutable:
response.POST._mutable = True
response.POST['username'] = random.randrange(1000000) # force change username
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
However after this username is not registered.
What is wrong??
Upvotes: 1
Views: 1271
Reputation: 477200
However after this username is not registered.
It is not registered, since the form does not contain a field named username
, and thus the form will ignore this.
You can set a username with:
form = RegisterForm(response.POST)
if form.is_valid():
form.instance.username = f'{random.randrange(10000000)}'
form.save()
That being said, it might be better to implement a custom user model, and set email
as the USERNAME_FIELD
. In that case your user model, does not have a username
field.
Upvotes: 2