Django: How to add errors messages next to the form - django

Currently I have a form, but somehow no matter how I register, I always fail. My implementation doesn't show what's wrong. Can someone figure out what's might happened?
Also, how can I add error messages next to each input box?
Below are my codes
{% block content%}
<div class="container">
<form class="form-signin" method="post" action="/sign_in/" role="form">
{% csrf_token %}
<h2 class="form-signin-heading">Please sign in</h2>
{% if error%} Your registration has not been successful. {%endif%}
<input type="username" class="form-control" name="username" placeholder="Username" required>
<input type="password" class="form-control" name="password" placeholder="Password" required>
<input type="password" class="form-control" name="password2" placeholder="Password" required>
<input type="username" class="form-control" name="name" placeholder="Name" required>
<input type="username" class="form-control" name="address" placeholder="Address" required>
<input type="username" class="form-control" name="Phone" placeholder="Phone Number" required>
<input type="email" class="form-control" name="emailAddress" placeholder="Email" required>
<input type="sinOrStNo" class="form-control" name="sinOrStNo" placeholder="Username" required>
<select class="form-control" name="type">
<option value="ST">Student</option>
<option value="FA">Faculty</option>
<option value="SF">Staff</option>
</select>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
{% endblock %}
my views.py
error = False;
if request.method == 'POST':
borrower = BorrowerForm(request.POST)
if borrower.is_valid():
username = borrower.cleaned_data['username']
password = borrower.cleaned_data['password']
type = borrower.cleaned_data['type']
name = borrower.cleaned_data['name']
address = borrower.cleaned_data['address']
phone = borrower.cleaned_data['phone']
emailAddress = borrower.cleaned_data['emailAddress']
sinOrStNo = borrower.cleaned_data['sinOrStNo']
expiryDate = borrower.cleaned_data['expiryDate']
# add borrower accounts
user = User.objects.create_user(username, None, password)
user.set_password(password)
user.save()
user_type = UserProfile(username=username,type=0)
user_type.save()
# add borrower table
borrower_user = Borrower(username = username, password=password,name= name, address=address, phone=phone,emailAddress=emailAddress,sinOrStNo=sinOrStNo, expiryDate=expiryDate, type=type)
borrower_user.save()
else:
error = True;
else:
borrower = BorrowerForm()
return render(request, 'books/clerk/add_borrower.html', {'logged_in':logged_in, 'username':username, 'type':type, 'error':error, 'borrower':borrower})
My forms.py
class BorrowerForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
name = forms.CharField(max_length=30)
address = forms.CharField(max_length=30)
phone = forms.CharField(max_length=30)
emailAddress = forms.CharField(widget=forms.EmailInput())
sinOrStNo = forms.CharField(max_length=10)
expiryDate = forms.DateField()
type = forms.CharField(max_length=3)
def clean_username(self):
existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
if existing.exists():
raise forms.ValidationError(("A user with that username already exists."))
else:
return self.cleaned_data['username']
def clean(self):
if 'password' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password'] != self.cleaned_data['password2']:
raise forms.ValidationError(("The two password fields didn't match."))
return self.cleaned_data

hm you use form and write all htmls in the html file why???
why don't you use
views.py
if request.method=='POST':
borrower = BorrowerForm(request.POST)
if borrower.is_valid():
......
return HttpResponseRedirect(<success url>)
else:
#here error messages it passed along with the form
return render(request, 'books/clerk/add_borrower.html',
{'borrower':borrower})
borrower = BorrowerForm()
return render(request, 'books/clerk/add_borrower.html',
{'logged_in':logged_in, 'username':username, 'type':type,
'error':error, 'borrower':borrower})
and use it the templates. that is what the purpose of forms.py. like :
<form class="form-signin" method="post" action="/sign_in/" role="form">
{% csrf_token %}
{{borrower.as_table}}
</form>

Related

'ForwardManyToOneDescriptor' object has no attribute 'user_type'

Models.py
class UserType(models.Model):
owner=models.ForeignKey(User,on_delete=models.CASCADE,default=1)
user_type=models.CharField(max_length=20,default='admin')
Views.py
def register(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
fname = request.POST.get('firstname')
lname = request.POST.get('lastname')
email = request.POST.get('email')
newpass = make_password(password)
newuser = User.objects.create(username=username,password=newpass,first_name=fname,last_name=lname,email=email)
newuser.save()
usertype = request.POST.get('usertype')
newtype = UserType.objects.create(user_type=usertype)
newtype.save()
messages.success(request, "Registration successful")
if UserType.owner.user_type == 'Student':
return redirect('Stuproadd')
elif UserType.owner.user_type == 'Teacher':
return redirect('Teachproadd')
else:
return redirect('index')
return render(request, 'register.html')
register.html
<body>
<h1>Register</h1>
<div class="container">
<form method="post">
{% csrf_token %}
<label>Username:</label>
<input type="text" name="username" placeholder="Enter your username" required /><br><br>
<label>First Name:</label>
<input type="text" name="firstname" placeholder="Enter First Name" required /><br><br>
<label>Last Name:</label>
<input type="text" name="lastname" placeholder="Enter last name" /><br><br>
<label>Email:</label>
<input type="text" name="email" placeholder="Enter your email" required /><br><br>
<label>password</label>
<input type="password" name="password" placeholder="enter your password" required /> <br><br>
<label>confirm password</label>
<input type="password" name="password" placeholder="confirm your password" required /> <br><br>
<label>Select your Role:</label>
<input type="radio" name="usertype" value="Student">
<label>Student</label>
<input type="radio" name="usertype" value="Teacher">
<label>Teacher</label>
<button type="submit">Register</button>
Already User,Login Here
</form></div>
</body>
This is the code.I'm getting error as 'ForwardManyToOneDescriptor' object has no attribute 'user_type'
After clicking register button, I want to go to stuproadd when the user type is student and teachproadd when the user type is teacher. How is it? pls help
You should use the UserType object (that is newtype in your case) instead of UserType class.
def register(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
fname = request.POST.get('firstname')
lname = request.POST.get('lastname')
email = request.POST.get('email')
newpass = make_password(password)
newuser = User.objects.create(username=username,password=newpass,first_name=fname,last_name=lname,email=email)
newuser.save()
usertype = request.POST.get('usertype')
newtype = UserType.objects.create(user_type=usertype)
newtype.save()
messages.success(request, "Registration successful")
if newtype.owner.user_type == 'Student': # Use `newtype` instead of `UserType`
return redirect('Stuproadd')
elif newtype.owner.user_type == 'Teacher': # Use `newtype` instead of `UserType`
return redirect('Teachproadd')
else:
return redirect('index')
return render(request, 'register.html')

Django Problem with a form and making queries

I'm making an lms website. It has classes. Teachers can create new classes and students can add those classes with entering their id and password (if the class has any password). Classes have custom ids and password made by their teachers. The teacher side of the code works fine so I omitted it. But there's a problem in the student part. I have already made a class which requires a password. I enter its id and password in the form and when I submit, it renders the form with the 'message' which has the value: "Invalid id and/or password.". while the password and id match. What is the problem here?
<p style="color: red;">{{message}}</p>
{% if user.is_teacher %}
<form action="{% url 'new_class' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input class="form-control" type="text" name="class-name" placeholder="Class Name" maxlength="64" required>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="class-type" id="class-type">
<label class="form-check-label" for="class-type">
Private
</label>
</div>
<div class="form-group">
<input class="form-control" type="password" name="class-password" id="class-password" placeholder="Password" style="display: none;" maxlength="16">
</div>
<input class="btn btn-primary" type="submit" value="Create">
</form>
{% else %}
<form action="{% url 'new_class' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input class="form-control" type="text" name="class-id" placeholder="Class ID" maxlength="4" required>
</div>
<div class="form-group">
<p><sub>Leave the password field empty if the class doesn't have a password.</sub></p>
<input class="form-control" type="password" name="class-password" id="class-password" placeholder="Password" maxlength="16">
</div>
<input class="btn btn-primary" type="submit" value="Add">
</form>
{% endif %}
The view:
def new_class(request):
if request.method == 'POST':
# teacher user
if request.user.is_teacher:
# some code...
# student user
else:
class_id = request.POST['class-id']
# if user entered a password:
try:
class_password = request.POST['class-password']
# if a class with the entered id existed
try:
newclass = Class.objects.get(class_id=class_id)
# check if the class requires a password
if newclass.class_password is not None:
# if it did, compare the passwords
if newclass.class_password == class_password:
request.user.student_classes.add(newclass)
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'lms/new-class.html', {
'message': 'Invalid id and/or password.'
})
# if the class didn't have a password, let the user in
else:
request.user.student_classes.add(newclass)
return HttpResponseRedirect(reverse('index'))
except:
return render(request, 'lms/new-class.html', {
'message': 'Invalid id and/or password.'
})
# if user didn't enter any password
except:
try:
# try finding a class with the entered id
newclass = Class.objects.get(class_id=class_id)
# if the class doesn't require a password, let the user in
if newclass.class_password is None:
request.user.student_classes.add(newclass)
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'lms/new-class.html', {
'message': 'This class requires a password.'
})
except:
return render(request, 'lms/new-class.html', {
'message': 'Invalid id and/or password.'
})
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'lms/new-class.html')
Also I'm not sure what title to use for this question of mine so I'm open to suggestions.

How to save a foreignkey field while saving a HTML form in Django?

I want to save a html form data into django model but it has a foreign key field from another model. How can I save a form which has FK field??
My models:
class Dish(models.Model):
title =models.CharField(max_length=200)
description =models.TextField(blank=True)
price =models.IntegerField()
photo_main= models.ImageField(upload_to="photos/%Y%m%d/")
photo_1= models.ImageField(upload_to="photos/%Y%m%d/", blank= True)
photo_2= models.ImageField(upload_to="photos/%Y%m%d/", blank= True)
def __str__(self):
return self.title
class Order(models.Model):
dishorder= models.ForeignKey(Dish,null=True,on_delete=models.CASCADE)
name = models.CharField(max_length=200,blank=True)
email = models.CharField(max_length=100,blank=True)
phone = models.CharField(max_length=100,blank=True)
quantity =models.IntegerField(blank=True)
def __str__(self):
return self.name
My views:
def order(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
phone = request.POST['phone']
quantity = request.POST['quantity']
order= Order(
name=name,
email=email,
phone=phone,
quantity=quantity)
order.save()
messages.success(request, "Your order has been submitted.")
return render(request,"dishes/order.html")
My urls:
urlpatterns = [
path("dish",views.dish,name="dish"),
path("dish/<pk>",views.dishsingle,name="dishsingle"),
path("order",views.order,name="order"),
]
My template dishes/order.html
<form method="POST">
{% csrf_token %}
<div>
<label for="name">Name:</label>
<input type="text" name="name" class="form-control" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" name="email" class="form-control" required>
</div>
<div>
<label for="phone">Phone:</label>
<input type="number" name="phone" class="form-control" required>
</div>
<div>
<label for="quantity">Quantity:</label>
<input type="number" name="quantity" class="form-control" required>
</div>
<hr>
<input type="submit" value="MAKE AN ORDER">
</form>
While submitting this html form, I would like the foreignkey field dishorder to be saved on the backend as well. When I check the admin page, order is saved but without the name of the dish. How can I resolve this?

Django custom form registration TypeError at /accounts/register register() missing 1 required positional argument: 'username'

ImproperlyConfigured at /accounts/register
Could not create directory for saving email messages: /home/user/Desktop/emails ([Errno 13] Permission denied: '/home/user')
It points to this line "user.email_user(subject, message, html_message=message)" in views.register in account.
auth.html
<form id='registration-form' method='post' action={% url 'accounts:register' %}>
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control input-upper" id="fullname" placeholder="John Doe" name="fullname" required><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" required><br>
<input type="text" class="form-control input-upper" id="organization" placeholder="Organization" name="organization" required><br>
<input type="password" class="form-control input-upper" id="password" placeholder="Password" name="password1" required><br>
<input type="password" class="form-control input-upper" id="password" placeholder="Confirm Password" name="password2" required><br>
<small>By registering you agree to our terms and conditions</small>
<button type="submit" value='register' id='reg-submit-btn' 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? <a href="" >LOGIN</a></p>
</div>
</form>
MOdel Userprofile.py
class UserProfile(models.Model):
""" Profile for the User Model """
user = models.OneToOneField(
User, on_delete=models.CASCADE,
related_name='profile',
verbose_name='other Details',
)
phone = models.CharField(max_length=11, default='', blank=True, null=True)
organization = models.CharField(default='', max_length=300, blank=True)
referral = models.OneToOneField(
Referral, on_delete=models.CASCADE,
related_name='profile', verbose_name='profile Details',
null=True)
email_confirmed = models.BooleanField(default=False)
def __str__(self):
return self.user.username + '\'s profile'
def activate(self):
"""" Activates account after email is confirmed """
self.email_confirmed = True
self.user.is_active = True
self.save()
self.user.save()
Views.py
#transaction.atomic
def register(request):
"""Process registration of new users"""
if request.user.is_authenticated:
return JsonResponse({'status': 'loggedin'})
status = dict()
status['status'] = 'failure'
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
# Save Profile details
user = form.save()
current_site = get_current_site(request)
subject = 'DHIS2 Account Activation'
message = render_to_string(
'registration/account_activation_email.html',
{
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(
force_bytes(
user.pk)).decode(),
'token': account_activation_token.make_token(user),
},
request=request)
user.email_user(subject, message, html_message=message)
Referral.record_response(request, "REGISTERED")
#return JsonResponse({'status': 'success'})
return redirect('accounts:account_activation_sent')
status = form.errors
status['status'] = 'failure'
return JsonResponse(status)
I get a json response of status:Failure, and password1: "This field is required." and password2:"This field is required.
What could I be doing wrong? Probably the template doesn't save or something. How do i make a custom django form that makes use of the html template.
You don't have fields with names password1 and password2 in your template; you just have two fields named password. You need to give them the correct name attributes.

Authentication in Django. How can we make password verification step or compare the user ID with those in the database?

I'm trying to build a basic django web application. I am using the authentication and auth model now and my code requires username and password only. How can we make it better by adding password verification step or user id check service?
def authenticate(request):
user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
if user == None:
return HttpResponse('username or password error')
auth.login(request, user)
#I requested "request"!!!!
return HttpResponseRedirect(request.POST.get('next', '/') or '/')
def signup(request):
return render_to_response('signup_account.html', locals(), RequestContext(request))
def create(request):
#user = User.objects.create_user(username=request.POST['username'], first_name=request.POST['userfirstname'], last_name=request.POST['userlastname'],
# email=request.POST['email'],
# password=request.POST['password'])
user = User.objects.create_user(username=request.POST['username'],
password=request.POST['password'])
print 'create', user
user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
print 'authenticated', user
auth.login(request, user)
#Here what I want to do is to allow users to screen their wrong id.
#+ Password check.
subject = 'Thank you'
message = 'Welcome home /n I am so happy'
from_email = settings.EMAIL_HOST_USER
to_list = [user.email,settings.EMAIL_HOST_USER ]
send_mail(subject, 'Wow, this email sending altorithm is working.\n What a marvelous function is.', settings.EMAIL_HOST_USER,
to_list, fail_silently=False)
return HttpResponseRedirect(request.POST.get('next', '/') or '/')
The below is the login html code.
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/css/bootstrap.css">
</head>
<body>
<h1>Sign Up</h1>
<div class="container">
<form class="form" action="/accounts/create" method="post">
<input type="hidden" name="csrfmiddlewaretoken" value="{{csrf_token}}">
<input type="hidden" name="next" value="{{ request.GET.next }}">
<div class="form-group">
<label>User ID</label>
<input class="form-control" type="text" name="username">
</div>
<div class="form-group">
<label>First Name</label>
<input class="form-control" type="text" name="userfirstname">
</div>
<div class="form-group">
<label>Last Name</label>
<input class="form-control" type="text" name="userlastname">
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input class="form-control" type="password" name="password">
</div>
<input type="submit" class="btn btn-primary" value="Sign Up">
</form>
</div>
</body>
</html>
I'm a really beginner and I am even forced to think that this would be possible by inserting code into html file directly. I'm looking forward to hearing any feedback! Thank you.
You have username and password there ... So pass that into try ...
username = request.POST['username']
password = request.POST['password']
try:
user = User.objects.get(username=username)
if user.check_password(password):
username = user.username
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, "Welcome")
return HttpResponseRedirect(#your url
else:
messages.error(request, "Password not match")
return HttpResponseRedirect(#your url
except User.DoesNotExist:
pass