User Registration after mobile verification - python

I want the user to submit the registration form and then redirect to another page to verify the number he entered in the mobile number field. If the verification is successful, my user should be created otherwise an error.
Currently my Register View looks like this:
def register_view(request):
template = "accounts/register.html"
print(request.user.is_authenticated())
next = request.GET.get('next')
print next
title = "Register"
form = UserRegisterForm(request.POST or None,)
if form.is_valid():
user = form.save(commit=False)
# number = user.mobile_number
# to_check = phonenumbers.parse(number,"TR")
# if phonenumbers.is_possible_number(to_check) and phonenumbers.is_valid_number(to_check):
# formatted_number = phonenumbers.format_number(to_check, phonenumbers.PhoneNumberFormat.E164)
# params = {
# 'api_key': ' api-key',
# 'api_secret': 'api-secret',
# 'number': formatted_number,
# 'brand': 'MobileVerification',
# }
# url = 'https://api.nexmo.com/verify/json?' + urllib.urlencode(params)
# response = urllib.urlopen(url)
# resp_dict = json.loads(response.read())
# request.session["user_request_id"] = resp_dict['request_id']
# messages.success(request,"A 4 digit pin has been successfully sent to your number.")
# return HttpResponseRedirect(reverse('pin_verify'))
# else:
# messages.error(request,"Enter a valid mobile number.")
# params2 = {
# }
# url = 'https://api.nexmo.com/verify/search/json?' + urllib.urlencode(params)
password = form.cleaned_data.get('password')
user.set_password(password)
user.save()
new_user = authenticate(username=user.mobile_number, password=password)
login(request, new_user)
if next:
return redirect(next)
return redirect("/")
context = {
"form": form,
"title": title
}
return render(request, template, context)
The commented code in the view is what I tried by getting the number and then redirecting but this is not how it should be.
My Register template looks like this:
{% extends "base.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block content %}
<div class='row'>
<div class='col-sm-6 col-sm-offset-3'>
<h1>Register for free!</h1>
<form method="post" action=".">
{% csrf_token %}
{{ form|crispy }}
<input class='btn btn-block btn-primary' type="submit" value="{% trans 'Join' %}" />
</form>
</div>
</div>
<hr/>
<div class='row'>
<div class='col-sm-6 col-sm-offset-3 text-align-center'>
<p>Need to Login?</p>
</div>
</div>
{% endblock %}

Related

Form not resetting upon submission?

I have a page with a form that once it gets submitted, the form loads again for the next person. I switched from class based views to function based due to a problem I was having to render modals and I noticed that now, since I'm not redirecting to the form again, it does not clear the data that was entered previously. How can I clear the form upon submission?
views.py
def enter_exit_area(request):
form = WarehouseForm(request.POST or None)
enter_without_exit = None
exit_without_enter = None
if form.is_valid():
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in request.POST:
# Some rules to open modals/submit
message = 'You have entered %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)
elif 'leave_area' in request.POST:
# more Rules
message = 'You have exited %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)
return render(request, "operations/enter_exit_area.html", {
'form': form,
'enter_without_exit': enter_without_exit,
'exit_without_enter': exit_without_enter,
})
forms.py
class WarehouseForm(AppsModelForm):
class Meta:
model = EmployeeWorkAreaLog
widgets = {
'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
}
fields = ('employee_number', 'work_area', 'station_number', 'edited_timestamp')
enter_exit_area.html
{% extends "base.html" %}
{% load core_tags %}
{% block main %}
{% if enter_without_exit %}
<div id="auto-open-ajax-modal" data-modal="#create-update-modal" data-modal-url="{% url "operations:update_timestamp_modal" enter_without_exit.id %}" class="hidden"></div>
{% endif %}
{% if exit_without_enter %}
<div id="auto-open-ajax-modal" data-modal="#create-update-modal" data-modal-url="{% url "operations:update_timestamp_modal" exit_without_enter.id %}" class="hidden"></div>
{% endif %}
<form id="warehouseForm" action="" method="POST" class="form-horizontal" novalidate >
{% csrf_token %}
<div>
<div>
<label>Employee</label>
{{ form.employee_number }}
</div>
<div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
{% modal id="create-update-modal" title="Update Timestamp" primary_btn="Submit" default_submit=True %}
{% endblock main %}
# Form not resetting upon submission, because you are sending data to your form
form = WarehouseForm(request.POST or None)
# If you want to reset your form, you should not send data to your form
form = WarehouseForm()
For Example:-
if request.method == 'POST':
form = WarehouseForm(request.POST or None)
else:
form = WarehouseForm()
# Your views.py can be:-
views.py
def enter_exit_area(request):
enter_without_exit = None
exit_without_enter = None
if request.method == 'POST':
form = WarehouseForm(request.POST or None)
if form.is_valid():
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in request.POST:
# Some rules to open modals/submit
message = 'You have entered %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)
elif 'leave_area' in request.POST:
# more Rules
message = 'You have exited %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)
else:
form = WarehouseForm()
return render(request, "operations/enter_exit_area.html", {
'form': form,
'enter_without_exit': enter_without_exit,
'exit_without_enter': exit_without_enter,
})

how to implement search form and post create form in single class based view

I'm trying to implement both searching posts and create a post in single view.
views.py
class HomeView(TemplateView):
template_name = 'home/home.html'
def get(self, request):
post_list = None
form = HomeForm(self.request.GET or None)
form1 = CommentForm(self.request.GET or None)
posts = Post.objects.filter(user = request.user).order_by('-created')
comments = Comment.objects.all()
users = User.objects.exclude(id=request.user.id)
query = request.GET.get('q')
if query:
post_list = Post.objects.filter(
Q(post__icontains=query)
)
context = {
'posts_list': post_list, }
print(post_list)
args = {
'form': form, 'posts': posts, 'users': users, 'form1':form1,
'comments':comments,'post_list':post_list,
}
return render(request, self.template_name, args)
def post(self, request):
form1 = CommentForm()
text = ''
if request.method=='GET' and 'btn1' in request.POST:
post_list = Post.published.all()
query = request.GET.get('q')
if query:
post_list = Post.objects.filter(
Q(post__icontains=query)
)
context = {
'posts_list': posts_list,
}
return redirect('home:home')
if request.method=='POST' and 'btn' in request.POST:
form = HomeForm(request.POST,request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
text = form.cleaned_data['post']
form = HomeForm()
form1 = CommentForm()
return redirect('home:home')
html code
<form enctype="multipart/form-data" class="form-inline my-2 my-lg-0" action=".">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name='q'>
<button class="btn btn-outline-success my-2 my-sm-0" name="btn1" type="submit">Search</button>
{% block body %}
<div class="container">
<div class="col-md-8">
<h2>Home</h2>
<form method="POST" enctype="multipart/form-data" type = 'file'>
{% csrf_token %}
{{ form.post }}
{{ form.image }}
<br>
<button name="btn" type="submit">Submit</button>
</form>
<h2>{{ text }}</h2>
{% for post in posts %}
<h1>{{post.id}}.{{ post.post }}</h1>
<br>
<img src="{{ post.image.url }}" width = 240 >
<p>Posted by {{ post.user.get_full_name }} on {{ post.created }}</p>
<!-- <form action="{% url 'home:cmnt' pk=post.id %}" method="POST" enctype="multipart/form-data" type = 'file'>
{% csrf_token %}
{{ form1.content }}
<br>
<button type="submit">Submit</button>
</form> -->
{{comments.count}} comment{{comments|pluralize}}<br>
{% for comment in post.comment_set.all %}
<small><b>{{ comment.comment }}</b></small>
<p>commented by {{ comment.user.get_full_name }} on {{ comment.created }}</p>
{% endfor %}
{% endfor %}
</div>
</div>
{% endblock %}
from this code I get the query value entered by the user.
when I implement this code I need to fill both the forms post create and search form but, I need to submit only one form at a time
when I fill both the forms and submit I get URL like this
http://127.0.0.1:8000/home/?q=django+&csrfmiddlewaretoken=OsNRlkvRjSHHuNYMxhZS9MFushCzCTZtjFvgEb5qFFybovBhWI3X0uufvd8bO8WS&post=asdsad&image=7653_1792089421024273_590924154993413545_n.jpg&btn=
I need a code which implements:
when submitted post create form create the post and return
when submitted search form load the respective results from database

Django Forms: Cannot show Validation Error

I have a Django Form where I allow the user to submit a value only if his password matches a predefined password set by me : Pass_matcher
Validation works fine, such that if passwords match, value is entered and stored and if not, nothing happens.
However I want that if passwords do not match, I show a simple custom warning message. I looked at other SO questions such as here and here, but I can't seem to get it right.
Note: If the user enters the correct password I do not want to redirect to another page.
forms.py
from django import forms
class TactForm(forms.Form):
password = forms.CharField(widget=forms.PasswordInput(
attrs = {
'class' : 'form-control mb-2 mr-sm-2 mb-sm-0',
'placeholder' : 'Enter Password:',
'id' : 'inlineFormInput',
'required' : 'true'
}
), required = True, label='Tact Password', max_length=100)
tacttime = forms.CharField(widget=forms.TextInput(
attrs = {
'class': 'form-control mb-2 mr-sm-2 mb-sm-0',
'placeholder': 'Enter Tact Time:',
'id' : 'inlineFormInput2'
}
),label='Tact Time', max_length=100)
def clean(self):
cleaned_data = super(TactForm,self).clean()
password = cleaned_data.get('password')
current_tact = cleaned_data.get('tacttime')
if password != 'Pass_matcher':
print('incorrect') #this prints to console if incorrect
raise forms.ValidationError('Incorrect Password') # this does not work
else:
print('correct') #this prints to console if correct
return cleaned_data
views.py
def details(request):
form = TactForm(request.POST or None)
if request.method == 'POST':
form = TactForm(request.POST)
if form.is_valid():
print('here1')
current_tact = form.cleaned_data['tacttime']
password = form.cleaned_data['password']
else:
form = TactForm()
return render(request, 'linedetails/index.html',{'form':form})
template
<div class="user_in" style="text-align:center;">
<form class="form-inline" method="POST" action="{% u$
{% csrf_token %}
{{ form.password }}
{{ form.tacttime }}
<br>
<button type="submit" class="btn btn-outline>
</form>
</div>
The below code is experimental
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
I cannot understand why the raise forms.ValidationError('Incorrect Password')
is not shown if the statement above it is correctly printed to terminal.
I am thinking that I have something missing in else statement of the views.py script.
Thanks for any suggestions.
You redefined form instance if form is not valid. just remove else block to fix it:
def details(request):
form = TactForm(request.POST or None)
if request.method == 'POST':
form = TactForm(request.POST)
if form.is_valid():
print('here1')
current_tact = form.cleaned_data['tacttime']
password = form.cleaned_data['password']
return render(request, 'linedetails/index.html',{'form':form})
Also you actually dont need if request.method == 'POST' validation since form will be populated with post data automatically here form = TactForm(request.POST or None). So you can simply rewrite your view to this:
def details(request):
form = TactForm(request.POST or None)
if form.is_valid():
print('here1')
current_tact = form.cleaned_data['tacttime']
password = form.cleaned_data['password']
return render(request, 'linedetails/index.html',{'form':form})

Showing error messages in template in DefaultUserCreationForm - django

I am having a problem in displaying an error message in the HTML page. I am using Django's default UserCreationForm for signup page. It has two password fields - one original and one for confirmation. When the user enters different passwords, I am getting at /signup/ whereas I want the error message to be displayed in the HTML page saying that the passwords didn't match. I have gone through the docs and I have added some related lines in my code, I don't know where I'm going wrong.
Here is my views.py:
def adduser(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
print(request.POST)
if(form.is_valid):
try:
user = employees.objects.get(emp_id=request.POST['username'] )
except employees.DoesNotExist:
user = None
print(user)
if( user != None ):
if request.POST['username'] in employees.objects.values_list('manager_id__emp_id',flat=True):
g = Group.objects.get(name='Managers')
newuser = form.save()
newuser.groups.add(g)
else:
g = Group.objects.get(name='Employees')
newuser = form.save()
newuser.groups.add(g)
return render(request,'login.html',{'form': form})
else:
form = UserCreationForm()
return render(request,'signup.html', {'form': form, 'msg': 'Enter valid employee id'})
else:
form = UserCreationForm()
return render(request,'signup.html', {'form': form})
and here is my signup.html:
<body>
<div class="container">
<div class="page-header">
<h1>Sign-up Here</h1>
</div>
{% block body %}
<form method="post">
{% csrf_token %}
<font color="orange" size="5px"><p> * Enter your Employee id, as username * </p></font>
{{ form.as_p }}
<font color="red"> {{ msg }} </font><br>
<font color="red"> {{ form.password1.errors }} </font><br>
<font color="red"> {{ form.password2.errors }} </font><br>
<br>
<button class="btn btn-success" type="submit"> Go! </button>
</form>
{% endblock %}
</div>
</body>
The problem is in this line :
if(form.is_valid):
This is not the correct way of testing form validation,
instead use:
if form.is_valid():
Also you dont need to declare form multiple times,it can be done single time.
Like this :
def adduser(request):
form = UserCreationForm(request.POST or None)
if request.method == 'POST':
print(request.POST)
if form.is_valid():
try:
user = employees.objects.get(emp_id=request.POST['username'] )
except employees.DoesNotExist:
user = None
print(user)
if( user != None ):
if request.POST['username'] in employees.objects.values_list('manager_id__emp_id',flat=True):
g = Group.objects.get(name='Managers')
newuser = form.save()
newuser.groups.add(g)
else:
g = Group.objects.get(name='Employees')
newuser = form.save()
newuser.groups.add(g)
return render(request,'login.html',{'form': form})
else:
form = UserCreationForm()
return render(request,'signup.html', {'form': form, 'msg': 'Enter valid employee id'})
return render(request,'signup.html', {'form': form})
And there can be diffrenmt type of erros, field and non_field_errors, so use someting like this :
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}

User got saved in django regardless of other two forms with it are valid or not

UserForm got saved no matter if other two forms (StudentOrFacultyForm and UserIdForm) are valid or not. User should not be created if other two forms are invalid. Please help!
models.py
class StudentOrFaculty(models.Model):
STUDENT = 'S'
FACULTY = 'F'
PROFILE_CHOICES = (
(STUDENT, 'Student'),
(FACULTY, 'Faculty'),
)
# Links to a User model instance
user = models.OneToOneField(User, related_name='fors')
# The Additional attributes
st_or_faculty = models.CharField(max_length=1, choices=PROFILE_CHOICES)
def __str__(self):
if(self.st_or_faculty == 'S'):
fullname = 'Student'
elif(self.st_or_faculty == 'F'):
fullname = 'Faculty'
else:
fullname = 'Unknown'
return str(self.user) + " is " + fullname
class UserActivation(models.Model):
user = models.OneToOneField(User)
activation_key = models.CharField(max_length=255, blank=True)
key_expires = models.DateTimeField(default=(timezone.now() + timedelta(days=1)))
def __str__(self):
return self.user.username
class Meta:
verbose_name_plural=u'Activation'
class UserIdCard(models.Model):
user = models.OneToOneField(User)
id_card = models.ImageField(upload_to='id_cards')
forms.py
FORS_CHOICES = (('F','Faculty'),('S','Student'))
class UserForm(forms.ModelForm):
first_name = forms.CharField(help_text="Frist Name")
last_name = forms.CharField(help_text="Last Name")
username = forms.CharField(help_text="Username")
email = forms.CharField(help_text="Email")
password = forms.CharField(widget=forms.PasswordInput(),
help_text="Password")
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email',
'password')
def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')
if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError(u'this Email is already registered.')
return email
class StudentOrFacultyForm(forms.ModelForm):
"""
Studentorfaculty option
"""
st_or_faculty = forms.ChoiceField(
label="Student Or Faculty",
required=True,
choices=FORS_CHOICES,
widget=forms.RadioSelect,
help_text="Student Or Faculty")
class Meta:
model = StudentOrFaculty
fields = ('st_or_faculty',)
class UserIdCardForm(forms.ModelForm):
id_card = forms.ImageField(label="College Id Card")
class Meta:
model = UserIdCard
fields = ('id_card',)
def clean_id_card(self):
image = self.cleaned_data.get('id_card',False)
if image:
if hasattr(image,'_size'):
if image._size > 4*1024*1024:
raise ValidationError("Image file too large (should be < 4mb )")
return image
else:
raise ValidationError("Couldn't read uploaded image")
views.py
def user_signup(request):
# get the request's context
context = RequestContext(request)
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('notices:index'))
# A boolean value for telling the template whether the signup was successfull
# Set to flase initially. Code changes value to True when registration
#successfull
registered = False
# If it's a HTTP POST, we're interested in processing form data
if request.method == 'POST':
# Attempt to grab information
# We make use of UserForrm and UserProfileForm
user_form = UserForm(data=request.POST)
student_or_faculty_form = StudentOrFacultyForm(data=request.POST)
user_id_card_form = UserIdCardForm(data=request.POST, files=request.FILES)
# If the two foms are valid
if user_form.is_valid() and student_or_faculty_form.is_valid() and\
user_id_card_form.is_valid():
# Save the user's form data to the database.
user = user_form.save()
# Now we hash the password with set_password method.
# One hashed, we can update the user object.
user.set_password(user.password)
user.is_active = False
user.save()
uid = user_id_card_form.save(commit=False)
uid.user = user
uid.save()
fors = student_or_faculty_form.save(commit=False)
fors.user = user
fors.save()
username = user_form.cleaned_data['username']
email = user_form.cleaned_data['email']
tmp = random.random()
tmp = str(tmp)
tmp = tmp.encode('utf-8')
salt = hashlib.sha1(tmp).hexdigest()[:5]
salt = salt.encode('utf-8')
email_en = email.encode('utf-8')
activation_key = hashlib.sha1(salt+email_en).hexdigest()
key_expires = datetime.datetime.today() + datetime.timedelta(2)
email = user_form.cleaned_data['email']
#Get user by username
user=User.objects.get(username=username)
new_profile = UserActivation(user=user, activation_key=activation_key,
key_expires=key_expires)
new_profile.save()
# Send email with activation key
email_subject = 'Account confirmation'
email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \
48hours http://www.socialboard.in/accounts/confirm/%s" % (username, activation_key)
send_mail(email_subject, email_body, 'support#socialboard.in',
[email], fail_silently=False)
# log in the user
user_name = request.POST['username']
'''new_user = authenticate(username=request.POST['username'],
password=request.POST['password'])
login(request, new_user)'''
# Update the variable to tell the registration was successful
registered = True
return HttpResponseRedirect(reverse('accounts:aftersignup', kwargs={'user_name':user_name}))
# Invalid forms
# Print problems to the terminal.
# they will also be show to the user
else:
print( user_form.errors, student_or_faculty_form.errors, user_id_card_form.errors )
# Not a HTTP POST, so we render our form using two instance
# These forms will be blank, ready for the user input.
else:
user_form = UserForm()
student_or_faculty_form = StudentOrFacultyForm()
user_id_card_form = UserIdCardForm()
# Render the template depending on the context.
return render_to_response(
'accounts/signup.html',
{ 'user_form': user_form, 'student_or_faculty_form': student_or_faculty_form,
'user_id_card_form': user_id_card_form,
'registered': registered},
context)
signup.html
<form class="form-horizontal" role="form" id="user_form" method="post" action="{% url 'accounts:signup' %}"
enctype="multipart/form-data">
{% csrf_token %}
{% for field in user_form.visible_fields %}
<div class="form-group has-feedback">
<div class="col-sm-12"><input type="{{ field.field.widget.input_type }}" class="form-control" name="{{ field.name }}" placeholder="{{ field.label}}" value="{% if field.value %}{{field.value}}{% endif %}"></div>
{% if field.errors %} <div class="col-sm-10 text-danger"> {{ field.errors }} </div> {% endif %}
</div>
{% endfor %}
{% for fieldi in student_or_faculty_form.visible_fields %}
<div class="from-group has-feedback">
<!--<label class="col-sm-2 control-label">I am </label>-->
{% for value,text in fieldi.field.choices %}
<label class="radio-inline">
<input type="radio" name="{{ fieldi.name }}" id="" value="{{ value }}"><b> {{ text }}</b>
</label>
{% endfor %}
{% if fieldi.errors %} <div class="col-sm-10 text-danger "> {{ fieldi.errors }} </div> {% endif %}
</div>
{% endfor %}
<br>
{% for field in user_id_card_form.visible_fields %}
<div class="form-group has-feedback">
<div class="col-sm-12"><b>{{field.field.label}} :</b></div>
<div class="col-sm-12"><input type="{{ field.field.widget.input_type }}" class="form-control" name="{{ field.name }}"
placeholder="{{ field.label}}" value="{% if field.value %}{{field.value}}{% endif %}"></div>
{% if field.errors %} <div class="col-sm-10 text-danger"> {{ field.errors }} </div> {% endif %}
</div>
{% endfor %}
<!-- Provide a button to click to submit the form -->
<div class="form-group">
<div class="col-sm-offset-0 col-sm-10">
<button type="submit" class="btn btn-warning"><b>Sign Up</b></button><br><br>
<div>or have an account? <span class="btn btn-xs btn-default">Log In</span></div>
</div>
</div>
</form>

Categories

Resources