Form post request not sending data to Django views.py - python-3.x

I am passing data from edisplay.html to views.py class name called EmailManagement but after inserting data data goes blank even I type it and I fell auto submitted when I type first form because myform appear only first form validation.
views.py
#csrf_exempt
def EmailManagement(request):
if request.method == "POST":
code = request.POST.get('scode_no', '')
if code:
userlogin = EmailDb.objects.all().filter(scode = code)
scode = ''
for i in userlogin:
scode += i.scode
# print(scode)
if code == scode:
sem = EmailDb.objects.all().filter(scode = code)
idv = ''
for i in sem:
idv += str(i.id)
print(idv)
idv = int(idv)
p = EmailDb.objects.get(id=idv)
if request.method == 'POST':
institution = request.POST.get('institutionf', '')
fullname = request.POST.get('fullnamef', '')
email = request.POST.get('personalef', '')
contact = request.POST.get('contactf', '')
position = request.POST.get('positionf', '')
uploaded = request.FILES.get('filef', '')
print(uploaded)
print(fullname)
p.institution = institution
p.fullname = fullname
p.contact = contact
p.email = email
p.position = position
p.uploaddata = uploaded
p.save(update_fields=['institution', 'fullname', 'contact', 'email', 'position', 'uploaddata'])
form = pForm()
return render(request, 'NEC/edisplay.html', {'p': p, 'form': form})
form = ResultForm()
return render(request,'NEC/emailmgt.html', {'form': form})
edisplay.html
<form hx-post="email" hx-target="body" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{p.useremail}}here
<!-- <input type="text" name="institution" id="institution" placeholder="Institution Name" class="form-control w-50 form-row" value="{{p.institution}}" required>
<input type="text" name="fullname" id="fullname" placeholder="Full Name" class="form-control w-50 form-row mt-1" value="{{p.fullname}}" required>
<input type="text" name="email" id="contact" placeholder="Personal Email " class="form-control w-50 form-row mt-1" value="{{p.email}}" required>
<input type="text" name="contact" id="contact" placeholder="Contact " class="form-control w-50 form-row mt-1" value="{{p.contact}}" required>
<input type="text" name="position" id="position" placeholder="Position " class="form-control w-50 form-row mt-1" value="{{p.position}}" required>
<input class="form-control w-50 form-row mt-1" type="file" id="formFile" name="upload" required> -->
{{form.as_p}}
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" name='checkbox' required>
<label class="form-check-label" for="invalidCheck">
Agree to terms and conditions
</label>
<br>
<input class="bg-success text-white mt-1" style="margin-top: 0px;" type="submit" />
</form>
models.py
class EmailDb(models.Model):
institution = models.CharField(max_length=300, blank=True, null=True)
fullname = models.CharField(max_length=50, blank=True, null=True)
contact = models.CharField(max_length=50,blank=True, null=True)
email = models.CharField(max_length=300, blank=True, null=True)
position = models.CharField(max_length=100, blank=True, null=True)
uploaddata = models.FileField(upload_to='appointment_letter', blank=True, null=True)
useremail = models.CharField(max_length=100, blank=True, null=True)
userpassword = models.CharField(max_length=100, blank=True, null=True)
scode = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return self.scode
pform.py
from django import forms
class pForm(forms.Form):
institutionf = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'placeholder': 'Institution Name'}))
fullnamef = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'placeholder': 'Full Name'}))
personalef = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'placeholder': 'Personal Email'}))
contactf = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'placeholder': 'Personal Email'}))
positionf = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'placeholder': 'Contact'}))
filef = forms.FileField()
I have to go though first form in order to display second form.

blank value - NULL value or empty value

Related

I am saving EmailDb filed username and userpassword to another Emails models but it is saving null data in Emails db with refresh django

Null value or empty value saved with each refresh, even click button submit duplicate value, please find the following models and views file. please look at envlope button in the image that is submit button which create another model db called Emails.
fdisply.html
{% for i in obj %}
<tr>
{% if i.id %}
<th scope="row">{{forloop.counter0|add:obj.start_index}}</th>
<td>{{i.institution}}</td>
<td>{{i.fullname}}</td>
<td>{{i.email}}</td>
<td>{{i.contact}}</td>
<td>{{i.position}}</td>
<td><img src={{i.uploaddata.url}} class="img-fluid img-thumbnail" alt={{i.fullname}} style="width:100px; height: 60px"></td>
<td>
<i class="fa-regular fa-pen-to-square"></i>
<form action="{% url 'delete' i.id %}" method="POST" class="d-inline">
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-sm">
<i class="fa-regular fa-trash-can"></i>
</button>
</form>
<!-- sent data -->
<form method="POST" class="d-inline">
{% csrf_token %}
<div class="d-none">
<input type="text" name="email" id="email" class="form-control w-50 form-row" value="{{i.useremail}}" required>
<input type="text" name="password" id="password" class="form-control w-50 form-row mt-1" value="{{i.userpassword}}" required>
</div>
<button type="submit" class="btn btn-danger btn-sm">
<i class="fa-solid fa-envelope-circle-check"></i>
</button>
</form>
</td>
</tr>
{% endif %}
{% endfor %}
models.py
class EmailDb(models.Model):
institution = models.CharField(max_length=300, blank=True, null=True)
fullname = models.CharField(max_length=50, blank=True, null=True)
contact = models.IntegerField()
email = models.CharField(max_length=300, blank=True, null=True)
position = models.CharField(max_length=100, blank=True, null=True)
uploaddata = models.FileField(upload_to='appointment_letter')
useremail = models.CharField(max_length=100, blank=True, null=True)
userpassword = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.fullname
class EmailS(models.Model):
ename = models.CharField(max_length=100, blank=True, null=True)
epassword = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return self.ename
Also added views.py where i have a business logic.
views.py
def EAdmin(request):
obj = EmailDb.objects.all().order_by('id')
# paginator
paginator = Paginator(obj, 4)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
print(page_obj.start_index)
total_page = page_obj.paginator.num_pages
#
emaild = EmailDb.objects.all()
# POST Request
email = request.POST.get('email', '')
password = request.POST.get('password', '')
data = EmailS(ename=email, epassword=password)
data.save()
#amrit
context = {'obj': page_obj, 'lastpage': total_page, 'totalPagelist': [n+1 for n in range(total_page)], 'em': emaild, 'email':email, 'password': password}
return render(request, 'NEC/fdisplay.html', context)

django form not showing in template to add data

the goal of my code is to make a school management system where the admin can log in and add teachers to their respective classes that they are leading and be able to add students to their respective classes and then take the attendance of those students present on any given day. however, I am having an issue where the form to add the student to the class isn't rendering when I click on the add student button. I have been searching but can't seem to find the error in my code, I am new to Django so any help will be appreciated. the closest I got was to make the modal show up but the fields to select the student from to add to the class wasn't showing
models
class Teacher(models.Model):
first_name = models.CharField(max_length=60, blank=False, null=False)
last_name = models.CharField(max_length=80, blank=False, null=False)
address = models.CharField(max_length=120, blank=True, null=True)
contact = models.CharField(max_length=10, blank=True, null=True)
email = models.EmailField(blank=True, null=True)
birth = models.CharField(max_length=20, blank=True, null=True)
gender = models.CharField(max_length=100, choices=[('Male', 'Male'), ('Female', 'Female')], blank=True, null=True)
comment = models.TextField(max_length=10000, blank=True, null=True)
def __str__(self):
return f"{self.first_name + ' ' + self.last_name}"
class Student(models.Model):
student_code = models.CharField(max_length=250, blank=True, null=True)
first_name = models.CharField(max_length=20, blank=False, null=False)
last_name = models.CharField(max_length=20, blank=False, null=False)
address = models.CharField(max_length=120, blank=True, null=True)
contact = models.CharField(max_length=10, blank=True, null=True)
admission = models.CharField(max_length=20, blank=True, null=True)
birth = models.CharField(max_length=20, blank=True, null=True)
parents = models.CharField(max_length=200, blank=False)
gender = models.CharField(max_length=100, choices=[('Male', 'Male'), ('Female', 'Female')], blank=True, null=True)
comment = models.TextField(max_length=10000, null=True, blank=True)
passport = models.ImageField(null=True,blank=True, default='default.png', upload_to="profile/")
def __str__(self):
return f"{self.first_name + ' ' + self.last_name}"
def save(self, *args, **kawrgs):
super().save(*args, **kawrgs)
img = Image.open(self.passport.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.passport.path)
class Room(models.Model):
form_teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
school_year = models.CharField(max_length=250)
level = models.CharField(max_length=250)
name = models.CharField(max_length=250)
def __str__(self):
return "[" + self.level + "] " + self.level + '-' + self.name
class ClassStudent(models.Model):
classIns = models.ForeignKey(Room, on_delete=models.CASCADE)
student = models.ForeignKey(Student, on_delete=models.CASCADE)
def __str__(self):
return self.student.student_code
def get_present(self):
student = self.student
_class = self.classIns
try:
present = Attendance.objects.filter(
classIns=_class, student=student, type=1).count()
return present
except:
return 0
def get_tardy(self):
student = self.student
_class = self.classIns
try:
present = Attendance.objects.filter(
classIns=_class, student=student, type=2).count()
return present
except:
return 0
def get_absent(self):
student = self.student
_class = self.classIns
try:
present = Attendance.objects.filter(classIns= _class, student=student, type = 3).count()
return present
except:
return 0
class Attendance(models.Model):
classIns = models.ForeignKey(Room, on_delete=models.CASCADE, default=' ')
student = models.ForeignKey(Student, on_delete=models.CASCADE, default=' ')
attendance_date = models.DateField(default=' ')
type = models.CharField(max_length=250, choices=[(
'1', 'Present'), ('2', 'Tardy'), ('1', 'Absent')], default=' ')
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.classIns.name + " " + self.student.student_code
views
# create a classroom
login_required()
def class_view(request):
form = ClassRoomForm()
if request.method == 'POST':
form = ClassRoomForm(request.POST)
if form.is_valid():
form.save()
name = form.cleaned_data.get('name')
messages.success(request, f'{name} was Successfully Added')
return redirect('classroom')
classes = Room.objects.all()
return render(request, 'school/class_view.html', {"form": form, 'classes': classes})
#show all the classroom created
#login_required
def class_detail(request,pk):
_class = Room.objects.filter(id=pk).first()
students = ClassStudent.objects.filter(classIns =_class).all()
print(students)
context = {
'class': _class,
'students': students
}
return render(request, "school/class_info.html", context)
#passes the form responsible for adding student to the classroom
#login_required
def save_class_student(request):
form = SaveClassStudent()
if request.method == 'POST':
form = SaveClassStudent(request.POST)
if form.is_valid():
form.save()
messages.success(request, "Student has been added successfully.")
redirect('class_detail')
return render(request, 'school/class_info.html', {'form': form})
forms
class ClassRoomForm(forms.ModelForm):
school_year = forms.CharField(max_length=250,help_text = "School Year Field is required.")
level = forms.CharField(max_length=250,help_text = "Level Field is required.")
name = forms.CharField(max_length=250,help_text = "Class Name Field is required.")
class Meta:
model = Room
fields = ('form_teacher', 'name', 'level', 'school_year')
class SaveClassStudent(forms.ModelForm):
classIns = forms.IntegerField()
student = forms.IntegerField()
class Meta:
model = ClassStudent
fields = ('classIns', 'student')
def clean_classIns(self):
cid = self.cleaned_data['classIns']
try:
classIns = Room.objects.get(id=cid)
return classIns
except:
raise forms.ValidationError("Class ID is Invalid.")
def clean_student(self):
student_id = self.cleaned_data['student']
_class = Room.objects.get(id=self.data.get('classIns'))
student = Student.objects.get(id=student_id)
try:
cs = ClassStudent.objects.get(classIns=_class, student=student)
if len(cs) > 0:
raise forms.ValidationError(
f"Student already exists in the Class List.")
except:
return student
HTML template for the form
{% extends 'school/dashboard.html' %}
{% load static %}
{% load widget_tweaks %}
{% load humanize %}
{% block title%}
<title>Class Information</title>
{% endblock %}
{% block page%}Class Info{% endblock %}
{% block card%} {%endblock%}
{% block table %}
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card card-default rounded-0 shadow ">
<div class="card-header">
<div class="d-flex w-100 align-items-center justify-content-between">
<h4 class="card-title fw-bold">Class Information</h4>
<div class="tools">
<button type="button" class="btn btn-secondary border rounded-0 bg-gradient btn-sm"
id='print_attendance_report'><i class="fa fa-print"></i> Print Attendance Report</button>
<a href="#addModal" data-bs-toggle="modal"> <button type="button" class="btn btn-primary rounded-0 bg-gradient btn-sm" id='add_new'><i
class="fa fa-plus"></i> Add Student</button></a>
</div>
</div>
</div>
<div class="card-body">
<div class="container-fluid">
<fieldset id="class-details">
<legend>Class Details</legend>
<div class="row">
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">School Year:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.school_year }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Level:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.level }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Name:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.name }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Faculty:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.form_teacher}}</p>
</div>
</div>
</div>
</div>
</fieldset>
<hr>
<fieldset>
<legend>Class Student List</legend>
<table class="table tables-bordered" id="student-list">
<colgroup>
<col width="10%">
<col width="25%">
<col width="25%">
<col width="10%">
<col width="10%">
<col width="10%">
<col width="10%">
</colgroup>
<thead>
<tr>
<th class="text-ceter">#</th>
<th class="text-ceter">Student Code</th>
<th class="text-ceter">Student Name</th>
<th class="text-ceter">Total Tardy</th>
<th class="text-ceter">Total Absent</th>
<th class="text-ceter">Total Present</th>
<th class="text-ceter">Actions</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr class="">
<td class="text-center">{{ forloop.counter }}</td>
<td>{{ student.student.student_code }}</td>
<td>{{ student.student.first_name }} {{student.student.last_name }}</td>
<td class="text-center">{{ student.get_present|intcomma }}</td>
<td class="text-center">{{ student.get_tardy|intcomma }}</td>
<td class="text-center">{{ student.get_absent|intcomma }}</td>
<td class="text-center">
<button class="btn btn-outline-danger btn-sm delete-data" type="button"
data-id="{{ student.pk }}" title="Delete">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</fieldset>
</div>
</div>
</div>
</div>
{% endblock %}
{% block content%}
<!-- Modal -->
<div class="modal fade" id="addModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Add Student To Class</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form class="row g-3" method="post">
{% csrf_token %}
<div class="col-md-6 form-group">
<label class="form-label">Student</label>
{% render_field form.student class+="form-control" %}
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary">Place</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
Here are a few recommendations. Firstly, within your forms.py you're re-creating the existing fields and that's not necessary. For example:
class ClassRoomForm(forms.ModelForm):
# school_year = forms.CharField(max_length=250,help_text = "School Year Field is required.")
# level = forms.CharField(max_length=250,help_text = "Level Field is required.")
# name = forms.CharField(max_length=250,help_text = "Class Name Field is required.")
# There's no need to re-create the above since they're in the Room model already.
class Meta:
model = Room
fields = ('form_teacher', 'name', 'level', 'school_year')
# What you need to do is to use the widget attribute on the Class Meta to set the help_text and the max_length.
widgets = {
'name': forms.TextInput(attr={'class':'form-control'}, max_length=250, help_text='Class Name Field is required.'),
'level': forms.TextInput(attr={'class':'form-control'}, max_length=250, help_text='Level Field is required.'),
'school_year': forms.TextInput(attr={'class':'form-control'}, max_length=250, help_text='School Year Field is required.'),
}
You could take that approach for the other forms you have as well.
Secondly, since you mentioned that the save_class_student method is passing the form, I'd suggest using {{ form.student }} if you want to render the form field of the form you're passing to the template.
<form class="row g-3" method="post">
{% csrf_token %}
...
<label class="form-label">Student</label>
{{ form.student }}
...
</form>
However, I think you might want to pass the form from the class_detail method since you want it to be displayed with the existing class information based on what you have in your template. With this, you could have the save_class_student method to handle the post request instead of trying to pass the form from there. For example:
#login_required
def class_detail(request,pk):
_class = Room.objects.filter(id=pk).first()
students = ClassStudent.objects.filter(classIns =_class).all()
# The classroom data: Initilizer
data = {
'classIns': _class # To set the classroom on the form since you'll be displaying on the student field.
}
form = SaveClassStudent(initial=data)
context = {
'class': _class,
'students': students,
'form': form,
}
return render(request, "school/class_info.html", context)
Then within the html file, you can have the form's action calling the url for the save_class_student method.
<form class="row g-3" method="post" action="{% url 'save_class_student url here' %}">
{% csrf_token %}
...
<label class="form-label">Student</label>
{{ form.student }}
...
</form>

How to get these gender choices to display as radio buttons

I am relatively new to Django and I have no idea how to get the gender choices in my Models to my views and then to my templates.
Below is my Models.py:
from django.db import models
from django.forms import ModelForm
from model_utils import Choices
class Country(models.Model):
''' define a table in the database called Country with several variables.'''
name = models.CharField(max_length = 50, unique = True)
officiallang = models.CharField(max_length = 50)
size = models.IntegerField()
# TODO: Find out how to defined this relationship
# representative = models.OneToOneField(UNrepresentative)
class UNrepresentative(models.Model):
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
name = models.CharField(max_length = 100, unique = True)
gender = models.CharField(max_length = 1,choices = GENDER_CHOICES,)
country = models.OneToOneField(Country, on_delete = models.CASCADE, )
class CountryForm(ModelForm):
class Meta:
model = Country
fields = ['name', 'officiallang', 'size']
class UNrepresentativeForm(ModelForm):
class Meta:
model = UNrepresentative
fields = ['name', 'gender', 'country']
Below is my Forms.py:
from django import forms
from app1.models import Country, UNrepresentative
class CountryForm(forms.Form):
name = forms.CharField(max_length = 50,)
officiallang = forms.CharField(max_length = 50)
size = forms.IntegerField()
class UNrepresentativeForm(forms.Form):
name = forms.CharField(max_length = 100,)
gender = forms.ChoiceField(
choices = UNrepresentative.GENDER_CHOICES,)
Finally, here is create_representative.html which contains the templates code:
{% extends 'base.html' %}
{% block content %}
<form method = 'POST' action = "{% url 'create_representative' %}">
{% csrf_token %}
<div class="form-row">
<div class="col-4">
<input type="text" class="form-control" placeholder="name" value = "" name = 'name'>
</div>
<div class="col-4">
<div>
<label>Male</label>
<input type="radio" placeholder="gender" value="male" name='gender'>
</div>
<div>
<label>Female</label>
<input type="radio" placeholder="gender" value="female" name='gender'>
</div>
</div>
<div class = 'col-4'>
<label for="country">Choose a country:</label>
<select name="country_id">
{% for items in all_items %}
<option value="{{items.id}}">{{items.name}}</option>
{% endfor %}
</select>
</div>
<div class = 'col'>
<button type="submit" class="btn btn-outline-secondary">Create rep</button>
</div>
</div>
</form>
{% endblock content %}
I have manually added male and female in values but ideally what I want to have is a dropdown with radio buttons to choose one of the genders. Any help will be appreciated. Thank you.

Cannot assign "''": "IncomeExpense.username" must be a "User" instance

I am working on this below code, trying the add data to the table by getting the values from the form. I have also marked where I am getting the error with #.
I have pasted views.py, models.py and createentry.html below. What might be the reason why I am getting this error and also explain me what I can change to get rid of this error.
#views.py
def create_entry_form(request):
if request.method=='POST':
entry_type=request.POST.get("expensetype")
amount=request.POST.get("amount")
details=request.POST.get("entrydetails")
capture_date=time.strftime('%Y-%m-%d')
entry_username=request.POST.get("entryusername")
entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=entry_username) #getting_error_in_this_line
entry.save()
user_balance = UserBalance.objects.filter(username=username).values_list('balance', flat=True)[0]
if entry_type=="income":
total_balance = user_balance + amount
else:
total_balance=user_balance - amount
update_balance=UserBalance.objects.get(username=username)
update_balance.value=total_balance
update_balance.save()
return render(request, "homepage.html", {'name':username, 'balance':total_balance})
else:
return redirect("www.google.com")
<!---- createentry.html ---->
<form action="{% url 'create_entry_form' %}" method="post">
{% csrf_token %}
<div class="container register-form">
<div class="form">
<div class="note">
<p>Create Entry Form</p>
</div>
<div class="form-content">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<select name="expensetype" id="expensetype" class="form-control">
<option value="expensetype">Select Expense Type</option>
<option value="income">income</option>
<option value="expense">expense</option>
</select>
</div>
<div class="form-group">
<input type="text" name="amount" id="amount" class="form-control" placeholder="Enter the Amount" value=""/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" name="entrydetails" id="entrydetails" class="form-control" placeholder="Enter the entry details" value=""/>
</div>
<div class="form-group">
<input type="text" name="entryusername" id="entryusername" class="form-control" placeholder="{{name}}" value=""/>
</div>
</div>
</div>
<button type="submit" class="btnSubmit">Submit</button>
</div>
</div>
</div>
</form>
#models.py
from django.db import models
from django.contrib.auth.models import User
class IncomeExpense(models.Model):
entry_type=models.CharField(max_length=100)
amount=models.IntegerField()
details=models.TextField()
capture_date=models.DateField()
username=models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f"{self.id}"
class UserBalance(models.Model):
balance=models.IntegerField()
username=models.ForeignKey(User, on_delete=models.CASCADE)
Also, why am I getting an error Cannot assign "''": "IncomeExpense.username" must be a "User" instance. and if I change something I get another similar one.
I tried changing the username to username__username inside this method:
entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=entry_username)
Here we use username field to save user id but you pass username.That is wrong.
def create_entry_form(request):
if request.method=='POST':
entry_type=request.POST.get("expensetype")
amount=request.POST.get("amount")
details=request.POST.get("entrydetails")
capture_date=time.strftime('%Y-%m-%d')
entry_username=request.POST.get("entryusername")
entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=request.user) #getting_error_in_this_line
entry.save()
user_balance = UserBalance.objects.filter(username=request.user).values_list('balance', flat=True)[0]
if entry_type=="income":
total_balance = user_balance + amount
else:
total_balance=user_balance - amount
update_balance=UserBalance.objects.get(username=request.user)
update_balance.balance=total_balance
update_balance.save()
return render(request, "homepage.html", {'name':request.user, 'balance':total_balance})
else:
return redirect("www.google.com")

How to use django login_required decorator for custom authentication backend

I have created an authentication backend that allows users to login using their username, password and institute id. Although the user can login but it doesn’t get access to the view with login_required decor. When I login to the site it redirects to this url: 'http://xxx.xx.xx.x:xxxx/accounts/login/?next=/accounts/rhome/'. Moreover, I cannot get {{ user.username }} in the html template. How can I set authentication restriction (or login_requied decor) on specific view in this case? Any suggestions will be greatly appreciated.
Here is what I tried.
backends.py:
class AuthBackend(object):
supports_object_permissions = True
supports_anonymous_user = False
supports_inactive_user = False
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
def authenticate(self, username=None, password=None, institute_id=None):
try:
userid = User.objects.get(username=username)
profile = Profile.objects.get(
Q(user_id=userid.id) & Q(institute_id=institute_id)
)
user = User.objects.get(id = profile.user_id)
if user.check_password(password):
return user
except ObjectDoesNotExist:
return None
View.py:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login as auth_login, logout, authenticate
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from .backends import AuthBackend
def user_login_view(request):
if request.method == 'POST':
institute_id = request.POST.get('institute_id')
username = request.POST.get('username')
password = request.POST.get('password')
user = AuthBackend.authenticate(request, username=username, password=password, institute_id=institute_id)
if user:
if user.is_active:
auth_login(request, user, backend='fileupload_project.accounts.backends.AuthBackend')
return redirect("accounts:rhome")
else:
return HttpResponse("Your account is disabled.")
else:
messages.error(request, 'Invalid login details supplied')
return HttpResponseRedirect(reverse('accounts:login'))
else:
return render(request, 'accounts/login.html', {})
#login_required
def home(request):
return render(request, 'accounts/index.html')
urls.py:
app_name = 'accounts'
urlpatterns = [
url(r'^login/$', views.user_login_view, name='login'),
url(r'^rhome/$', views.home, name='rhome'),]
Settings.py:
LOGIN_URL = '/accounts/login'
LOGIN_REDIRECT_URL = '/accounts/rhome/'
LOGOUT_REDIRECT_URL = '/accounts/logout/'
#Authentication backends
AUTHENTICATION_BACKENDS = (
'accounts.backends.AuthBackend',
'django.contrib.auth.backends.ModelBackend',)
Template/login.html:
<form id="login_form" method="post" action="{% url 'accounts:login' %}">
{% csrf_token %}
<br><br>
<div class="avatar">
<img alt="Avatar" height="180" src="{% static 'accounts/images/avatar.jpg' %}" width="180">
</div>
<h2 class="text-center">User Login</h2>
<div class="form-group">
<input id="institute_id" type="text" class="form-control" name="institute_id" placeholder="Center ID" required="required">
</div>
<div class="form-group ">
<input id="username" type="text" class="form-control" name="username" placeholder="Username" required="required">
</div>
<div class="form-group">
<input id="password" type="password" class="form-control" name="password" placeholder="Password" required="required">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button>
{% if messages %}
{% for message in messages %}
<p class="alert alert-warning" >{{ message }}</p>
{% endfor %}
{% endif %}
</div>
<div class="clearfix">
<label class="pull-left checkbox-inline"><input type="checkbox"> Remember me</label>
Forgot Password?
</div>
</form>

Resources