Authenticating Registrationn form in django - 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

Related

Data inside request.data not visible in Django Rest Framework

I am using DRF for CRUD operations. In my Project, I have function-based view taking request as parameter. I am aware of the fact that request.data is only applicable for DRF-Specific requests. I am also aware of the fact that it is a QueryDict.
I am taking input from HTML form as name, roll and city of a Student. But when I print the request.data (aka QueryDict), I only get csrfmiddlewaretoken and its value and found that other key-value pairs are missing. Where is my other data (i.e roll, name and city)
e.g {"csrfmiddlewaretoken": "JSACyyvAPqNcCPXNZQsNzPcca7ah3N7arkhFM9CuqpNammk6f43wQ4GyGg5QwU6w"}
forms.html (Template):
<form class="form" action="/save-data/" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" class="form-control" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="roll">Roll:</label>
<input type="number" id="roll" class="form-control" placeholder="Enter your Roll Number">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" id="city" class="form-control" placeholder="Enter your City">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Views.py
#api_view(['POST', 'GET'])
def save_data(request):
requested_data = request.data
print(requested_data)
return HttpResponse("Success", content_type='application/json')
It was supposed to contain other data fields as well!

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"

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

How to provide validation for the users model in views itself in django(not the custom user model)?

I am having user model in the models.py and the every user even the repeated user emails and usernames are being stored in the database but I need the validation of email and password upto 8 characters in the views.py
My models.py is
class users(models.Model):
email=models.CharField(max_length=50,default='0000000')
password=models.CharField(max_length=50,default='0000000')
room = models.ForeignKey(rooms,on_delete=models.CASCADE)
goal = models.ManyToManyField(goals)
style = models.ManyToManyField(designs)
My views.py
def user_register(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
room = request.POST['room']
g=goal=request.POST['goal']
g = g.split(',')
s=style=request.POST['style']
s=s.split(',')
user = users(password=password,email=email)
user.room=rooms.objects.get(pk=room)
goal = goals.objects.filter(pk__in=g)
style = designs.objects.filter(pk__in=s)
user.save()
user.goal.add(*goal)
user.style.add(*style)
return render(request,'home.html')
My template is:
<div class="card-body">
<form action="{% url 'car:user_register' %}" method="POST" >
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" required>
</div>
<div class="form-group">
<input type="hidden" name="room" id="name" value=" ">
</div>
<div class="form-group" >
<input type="hidden" name="goal" id="goal" value=" ">
</div>
<div class="form-group" >
<input type="hidden" name="style" id="style" value=" ">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<input type="submit" value="Register" class="btn btn-secondary btn-block">
</form>
</div>
</div>
</div>

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