Password is NoneType? - flask

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

Related

RuntimeError at /signup: Change your form to point to 127.0.0.1:8000/signup/ , or set APPEND_SLASH=False in your Django settings

RuntimeError at /signup
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/signup/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
I got this problem while using forms. Please help
I have used bootstrap for styling
<form action="/signup/" method = "post" >
{% csrf_token %}
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">#</span>
<input type="text" class="form-control" placeholder="Username" name = "username" aria-label="Username" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Firstname" name="fname" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Lastname" name="lname" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="email" class="form-control" placeholder="Recipient's email" name="email" aria-describedby="basic-addon2">
<span class="input-group-text" id="basic-addon2">#gmail.com</span>
</div>
<div class="input-group mb-3">
<input type="password" placeholder="password" name = "password" class="form-control">
</div>
<div class="input-group mb-3">
<input type="password" placeholder="confirm password" name = "con_password" class="form-control">
</div>
<div class="input-group mb-3">
<button type="submit" class="btn btn-primary">Signup</buttpn>
</div>
</form>
</div>
Views.py
def signup(request):
if (request.method == "POST"):
username = request.POST.get("username")
fname = request.POST.get("fname")
lname = request.POST.get("lname")
email = request.POST.get("email")
password = request.POST.get("password")
con_password = request.POST.get("con_password")
User.objects.create_user(username=username, first_name=fname, last_name=lname, email=email, password=password)
User.save()
messages.success(request, "Account created successfully")
return redirect("login")
Should Redirect to login Page
Either add APPEND_SLASH=False in settings.py. Or change form action="/signup/" to form action="/signup"

Authenticating Registrationn form in django

I have this html form that I want to use for signup of customers.
<form id='registration-form'>
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control input-upper" id="fullname" placeholder="John Doe" name="fullname" ><br>
<input type="text" class="form-control input-upper" id="username" placeholder="Username" name="username"><br>
<input type="email" class="form-control input-upper" id="email" placeholder="Email" name="email"><br>
<input type="text" class="form-control input-upper" id="organization" placeholder="Organization" name="organization"><br>
<input type="password" class="form-control input-upper" id="password" placeholder="Password" name="password"><br>
<input type="password" class="form-control input-upper" id="password" placeholder="Confirm Password" name="password"><br>
<small>By registering you agree to our terms and conditions</small>
<button type="button" class="btn btn-primary btn-block btn-signup-form">SIGN UP</button>
<button type="button" class="btn btn-primary btn-block btn-sign-linkedin" href="{% url 'social:begin' 'linkedin-oauth2' %}?next={{ next }}">Sign up with LinkedIn</button>
<p class="text-already">Already have an account? LOGIN</p>
</div>
</form>
How do I make an validation of the data filled i.e the email and password and I want customers to be able to log in after signing up
I'm not sure what you mean by validating data but If i got you correctly you should go for Django built in functionality for user creation. Django comes with Auth module which can reduce your lot's of effort and takes care of most of the painful parts. Just have a look on this post https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html
If you want simple validations you can use clean methods of Django Form. write one form class with the same fields as you mentioned.
EX.
Class SignupForm2(forms.ModelForm ):
class Meta:
model = User
def clean(self):
self.cleaned_data = super(SignupForm2, self).clean()
if 'captcha' in self._errors and self._errors['captcha'] != ["This field is required."]:
self._errors['captcha'] = ["Please enter a correct value"]
return self.cleaned_data

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

Password not saving to auth_user table in 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).

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! :)