Password not saving to auth_user table in Django - django

Below is the code for the user registration. The password value is not saving to the auth_users table. I am using MySQL as my database.
Any help is highly appreciated TIA
form.py
class MyRegistrationForm(UserCreationForm):
email=forms.EmailField(required=True)
class Meta:
model=User
fields = ('username','email','password1','password2')
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email=self.cleaned_data["email"]
if commit:
user.save()
return user
view.py
def register_user(request):
if request.method =='POST':
print request.POST['username']
print request.POST['password1']
print request.POST['password2']
form=MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/register-success/')
args={}
args.update(csrf(request))
args['form']=MyRegistrationForm()
return render_to_response("register.html",args,
context_instance=RequestContext(request))
HTML
<form method="post" class="form-signin" action="/register/">{% csrf_token %}
<h2 class="form-signin-heading">Please sign in</h2>
<label for="users" class="sr-only">UserName</label>
<input name="username" type="text" id="users" class="form-control" placeholder="Username" required autofocus>
<label for="inputEmail" class="sr-only">Email address</label>
<input name="email" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input name="password1" type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<label for="inputPassword1" class="sr-only">Password</label>
<input name="password2" type="password" id="inputPassword1" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>

You are calling super() incorrectly. You need to use the form class MyRegistrationForm, so that the save method of UserCreationForm is called and sets the password.
user = super(MyRegistrationForm, self).save(commit=False)

I'd like to point out that your def regiseter_user(request): view function has a superfluous "e" (regisEter).

Related

Password is NoneType?

I am trying to do a log in and register system for a project. My code is the following:
app.py:
#app.route("/register", methods=["POST", "GET"])
def register():
if flask.request.method == "POST":
username = flask.request.form.get('username')
email = flask.request.form.get('email')
pwd = flask.request.form.get('password')
return f'{pwd}'
else:
return flask.render_template("register.html")
register.html:
<form action="http://localhost:5000/register" method="POST">
<label id="username">
<input type="text" id="username" placeholder="Username" required>
</label>
<label id="email">
<input type="email" id="email" placeholder="E-mail" required>
</label>
<label id="password">
<input type="password" id="password" placeholder="Password" required>
</label>
<button class="register_btn">Sign up!</button>
</form>
I am expecting to see the password I typed inside the password field, however, I am surprised with None. I also tried with return pwd, which returns a 500 (console log TypeError: The view function for 'register' did not return a valid response. The function either returned None or ended without a return statement.)

Django OperationalError no such table

I'm making a sign up page.
html
{{message}}
<form action="{% url 'signup' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input class="form-control" autofocus type="text" name="username" placeholder="Username">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="Email Address">
</div>
<div class="form-group">
<input class="form-control" type="password" name="password" placeholder="Password">
</div>
<div class="form-group">
<input class="form-control" type="password" name="confirmation" placeholder="Confirm Password">
</div>
<input class="btn btn-primary" type="submit" value="Register">
</form>
django
def signup(request):
if request.method == 'POST':
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
confirmation = request.POST['confirmation']
if password != confirmation:
return render(request, 'lms/signup.html', {
'message': 'Passwords must match.'
})
else:
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, 'lms/signup.html', {
'message': 'Username already taken.'
})
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'lms/signup.html')
When I submit the form, I get this error:
OperationalError at /signup
no such table: lms_user
I've already done the migrations command. I also deleted tried deleting migrations and pycache folder's content and db.sqlite3 file and did the migrations again but that didn't help either.

Trying to link my HTML form to a view function in Django

I've been trying to create a user registration page and have gotten the form itself and the render for the form set up. I have also gotten the form to save user input as POST, but haven't been able to send that info to a view function I have created to save that info to a database.
Here is my html/css template form:(userinfo.html)
<div>
{% block content %}
<form action="register" method="post" name="Userinfo" id="Userinfo">
<label for="fname">First Name</label>
{% csrf_token %}
<input type="text" id="fname" name="firstname" placeholder="Your first name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
<label for="DOB">Date Of Birth</label>
<input type="text" id="DOB" name="DOB" placeholder="The Date you were born">
<label for="Email">Email Address</label>
<input type="text" id="Email" name="Email" placeholder="Your email address">
<input type="submit" value="Submit">
</form>
{% endblock %}
</div>
The name of my view function is register and here it is:(views.py)
def register(request):
if request.method == 'POST':
first_name = request.POST['first_name'],
last_name = request.POST['last_name'],
date_of_birth = request.POST['DOB'],
email = request.POST['email']
newuser= User.objects.create_user(first_name=first_name,last_name=last_name, email=email)
newuser.save()
print('user created')
return redirect('/home')
else:
return render(request,'register.html')
This is supposed to save the user input into Django's user database table.
How would I go about linking the form to the view I have set up?
Assuming the name of your register view is also register, i.e.,
# urls.py
urlpatterns = [
...
path('register', views.register, name='register'),
...
]
then you can just change the form tag as follows:
<form action="{% url 'register' %}" method="post" name="Userinfo" id="Userinfo">
<label for="fname">First Name</label>
{% csrf_token %}
<input type="text" id="fname" name="first_name" placeholder="Your first name..">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="last_name" placeholder="Your last name..">
...
</form>
Note the change in the name for the inputs to first_name and last_name so the match your request.POST['first_name'] and request.POST['last_name']
The {% url 'register' %} tells Django to look for a url path that has a view with the name register.
Notice, that firstname from form is not the same as first_name you seek in views. You have to fetch exactly the same data, as you place in html. You can always
print(request.POST)
to see what the POST dictionary has :)
With that fixed it should work for now.

Flask form post call - request.form is an empty dict

Form login.html:
<form method="POST">
<input type="text" placeholder="username" required>
<input type="password" placeholder="password" required>
<button type="submit">Sign in</button>
</form>
app.py:
#app.route("/", methods=["GET", "POST"])
def login():
if request.method == "POST":
print(request.form) # prints empty dict
return render_template("login.html")
The name parameter of inputs in the form is needed in any html form for it to be POSTed, otherwise they are left unprocessed.
So the right html would be login.html:
<form method="POST">
<input type="text" placeholder="username" name="username" required>
<input type="password" placeholder="password" name="password" required>
<button type="submit">Sign in</button>
</form>
Now flask should be able to dict up the input elements by name and value.
It returns empty dict because you don't specify the name of the object you requested.You should specify name from the html :
<input type="text" placeholder="username" name="username" required>
and in Python use something like :
request.form['username']
or
request.form.get('username')
instead of : (request.form)
Also a topic to have a look at :
How to get data received in Flask request

Return to the requested page after successfull #login_required

Suppose this is the url after #login_required(login_url='/account/required_login/'):
http://ngoksy.com/accounts/login_required/?next=/article/
View for the login_require:
def required_login(request):
return render(request, 'required_login.html')
I tried adding 'next', like it here. But it didn't help.:
def required_login(request):
c = {'next' : request.GET.get('next', '/')}
return render(request, 'login_required.html', c)
I have different template for login and another template for anonymous user which is redirected by #login_required.
required_login.html:
<h2>Login required! You must login to view the content.</h2>
<form action="/accounts/auth/" method="post">
{%csrf_token%}
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="">
<input type="submit" value="LOGIN">
</form>
I want to pass the next variable after successful login of login_required(), and land into Articles page after that. How do I do that?
I ended up with this.
views for required_login:
def required_login(request):
c = {'next' : request.GET.get('next', '/')}
return render(request, 'required_login.html', c)
In the template (notice the hidden input for next):
<form action="/accounts/auth/" method="post">
{%csrf_token%}
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="">
<input type="hidden" name="next" value="{{ next }}"/>
<input type="submit" value="LOGIN">
</form>
And then in the views for auth_view:
def auth_view(request):
username = request.POST.get('username','')
password = request.POST.get('password','')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
if request.POST.get('next') != '':
return HttpResponseRedirect(request.POST.get('next'))
else:
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/accounts/invalid_login')
I hope this will help any other noob like me! :)