Django:Error trying to add data in postgres database - python

I get an error(The view crud.views.insertEmp didn't return an HttpResponse object. It returned None instead.) whenever I try to insert data to my database through the insert.html template. I;m using postgres as my database. Any assistance in identifying the bug will be highly appreciated.
models.py
from django.db import models
class Employee(models.Model):
emp_name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
occupation = models.CharField(max_length=100)
salary = models.IntegerField()
gender = models.CharField(max_length=1)
class Meta:
db_table = 'employee'
views.py
from django.shortcuts import render, redirect
from crud.models import Employee
from django.contrib import messages
def showEmp(request):
employee = Employee.objects.all()
context = {"data": employee}
return render(request, "index.html", context)
def insertEmp(request):
if request.method == "POST":
if request.POST.get('emp_name') and request.POST.get('email') and request.POST.get('occupation') and request.POST.get('salary') and request.POST.get('gender'):
saveRecord = Employee()
saveRecord.emp_name = request.POST.get('emp_name')
saveRecord.email = request.POST.get('email')
saveRecord.occupation = request.POST.get('occupation')
saveRecord.salary = request.POST.get('salary')
saveRecord.gender = request.POST.get('gender')
saveRecord.save()
messages.success(request, "Employee " +
saveRecord.emp_name + " is added succesfully.")
return render(request, "insert.html")
else:
return render(request, "insert.html")
inser.html
<center>
<h1>Insert data into Postgresql</h1>
<hr>
<form method="POST">
{% csrf_token %}
<table border="">
<tr>
<td>Employee Name</td>
<td><input type="text" placeholder=" Enter employee name.." name="emp_name""></td>
</tr>
<tr>
<td>Email</td>
<td><input type=" text" placeholder="Enter email" name="email">
</td>
</tr>
<tr>
<td>Occupaton</td>
<td>
<select name="occupation">
<option selected disabled=true>-- Select occupation --</option>
<option value="">Programmer</option>
<option value="">HR</option>
<option value="">Sales Manager</option>
<option value="">Designer</option>
</select>
</td>
</tr>
<tr>
<td>Salary</td>
<td><input type="text" placeholder="Enter salary" name="salary"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<input type="radio" name="gender" value="M">Male |
<input type="radio" name="gender" value="F">Female
</td>
</tr>
<tr>
<td><input type="submit" value="Insert"></td>
<td>
{% if messages %}
{% for message in messages %}
<b style="color:green;">{{message}}</b>
{% endfor %}
{% endif %}
</td>
</tr>
</table>
</form>
</center>

The way you structure your code may cause the return of None, try to follow this example :
from django.shortcuts import render, redirect
def insertEmp(request):
if request.method == "POST":
if request.POST.get('emp_name') and request.POST.get('email') and request.POST.get('occupation') and request.POST.get('salary') and request.POST.get('gender'):
saveRecord = Employee()
saveRecord.emp_name = request.POST.get('emp_name')
saveRecord.email = request.POST.get('email')
saveRecord.occupation = request.POST.get('occupation')
saveRecord.salary = request.POST.get('salary')
saveRecord.gender = request.POST.get('gender')
saveRecord.save()
messages.success(request, "Employee " +
saveRecord.emp_name + " is added succesfully.")
# Redirect to the same page (you can change the page to fit your needs)
return redirect('.')
else:
# Not all required fields are present
messages.error(request, "Please fill all the fields")
# Also redirect the user to the same page
return redirect('.')
else:
return render(request, "insert.html")

Related

Django error value error: The view sub_categories.views.insert_sub_categories didn't return an HttpResponse object. It returned None instead

I am tasked with making a shopping crud project with models Products,categories,sub_categories,size,colors. Categories and subcategories are connected via foreign keys and I am using SERAILIZERS.the problem is that when I try to insert the data into sub Categories it doesnt come in both the database and the webpage
I also tried value = "{{c.category_name}}" as well in select dropdown as well
below are the models
class Categories(models.Model):
category_name = models.CharField(max_length=10)
category_description = models.CharField(max_length=10)
isactive = models.BooleanField(default=True)
class SUBCategories(models.Model):
category_name = models.ForeignKey(Categories,on_delete=models.CASCADE)
sub_categories_name = models.CharField(max_length=20)
sub_categories_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
show and insert function of sub_categories
def show_sub_categories(request):
showsubcategories = SUBCategories.objects.filter(isactive=True)
#print(showsubcategories)
serializer = SUBCategoriesSerializer(showsubcategories,many=True)
print(serializer.data)
return render(request,'polls/show_sub_categories.html',{"data":serializer.data})
def insert_sub_categories(request):
if request.method == "POST":
insertsubcategories = {}
insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name')
insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description')
form = SUBCategoriesSerializer(data=insertsubcategories)
if form.is_valid():
form.save()
print("hkjk",form.data)
messages.success(request,'Record Updated Successfully...!:)')
print(form.errors)
return redirect('sub_categories:show_sub_categories')
else:
print(form.errors)
else:
insertsubcategories = {}
form = SUBCategoriesSerializer(data=insertsubcategories)
category_dict = Categories.objects.filter(isactive=True)
category = CategoriesSerializer(category_dict,many=True)
hm = {'context': category.data}
if form.is_valid():
print(form.errors)
return render(request,'polls/insert_sub_categories.html',hm)
html of the insert page and show page respectively
<td>category name</td>
<td>
<select name="category_name" id="">
{% for c in context %}
<option value="{{c.id}}">{{c.category_name}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>sub categories Name</td>
<td>
<input type="text" name="sub_categories_name" placeholder="sub categories ">
</td>
</tr>
<tr>
<td>Sub categories Description</td>
<td>
<textarea name="sub_categories_description" id="" cols="30" rows="10">
</textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Insert" />
</td>
<td>
{% if messages %}
{% for mess in messages %}
<b style="color:green;">{{mess}}</b>
{% endfor %}
{% endif %}
</td>
<tbody>
<tr>
<td><b>{{result.sub_categories_name}}</b></td>
<td><b>{{result.sub_categories_description}}</b></td>
<td style="position: relative;left:50px;">
<a href="sub_categories/edit_sub_categories/{{result.id}}">
<button class="btn btn-primary">
<i class="fa-solid fa-pen-to-square">EDIT</i>
</button>
</a>
</td>
<td>
<a href="{% url 'sub_categories:delete_sub_categories' result.id %}" onclick="return confirm('Are You Sure you want to delete?')">
<button class="btn btn-danger">
<i class="fa-solid fa-trash">DELETE</i>
</button>
</a>
</td>
</tr>
</tbody>
categories and sub categories serializer
class CategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = Categories
fields = "__all__"
extra_kwargs = {'category_name': {'required': False}}
class SUBCategoriesSerializer(serializers.ModelSerializer):
class Meta:
model = SUBCategories
fields = "__all__"
where am I going wrong in the code?
Try this out and let me know, a few changes you'd require
def insert_sub_categories(request):
if request.method == "POST":
form = SUBCategoriesSerializer(data=request.POST)
if form.is_valid():
form.save()
messages.success(request, "Record Updated Successfully...!:)")
return redirect("sub_categories:show_sub_categories")
category_dict = Categories.objects.filter(isactive=True)
category = CategoriesSerializer(category_dict, many=True)
hm = {"context": category.data}
return render(request, "polls/insert_sub_categories.html", hm)
Form part
<form method="POST">
{% csrf_token %}
<table>
<thead>
<tr>
<td>category name</td>
<td>
<select name="category_name" id="">
{% for c in context %}
<option value="{{c.id}}">{{c.category_name}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>sub categories Name</td>
<td>
<input type="text" name="sub_categories_name" placeholder="sub categories ">
</td>
</tr>
<tr>
<td>Sub categories Description</td>
<td>
<textarea name="sub_categories_description" id="" cols="30" rows="10">
</textarea>
</td>
</tr>
<tr>
<td>Active</td>
<td>
<input type="checkbox" name="isactive" value="true" checked>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Insert" />
</td>
<td>
{% if messages %}
{% for mess in messages %}
<b style="color:green;">{{mess}}</b>
{% endfor %}
{% endif %}
</td>
</tr>
</thead>
</table>
<button class="btn btn-success">Go To Home</button>
</form>
model
class SUBCategories(models.Model):
category_name = models.ForeignKey(Categories, on_delete=models.CASCADE)
sub_categories_name = models.CharField(max_length=20)
sub_categories_description = models.CharField(max_length=20)
isactive = models.BooleanField(default=True)
def __str__(self):
return self.category_name.category_name
This error occurs because there is a chance in your function view, that it does not return proper Response or Redirect object. If you send POST request, but the form is not valid, then it will not return anything.
def insert_sub_categories(request):
if request.method == "POST":
...
if form.is_valid():
...
return redirect('sub_categories:show_sub_categories')
else:
print(form.errors)
# HERE YOU MISS REDIRECT/RENDER
else:
...
return render(request,'polls/insert_sub_categories.html',hm)
Also you don't pass SUBCategories.category_name to your serializer. It's required field, so it will never be valid without it. You may try form = SUBCategoriesSerializer(request.POST) instead of adding values one by one.

Django: How to put submitted data back in the form (update functionality)

I have been trying to make an 'update function' in my table so that my data can be changed by a user.
So here is my html with the form where i want my data to go back in to, so when the user presses submit again it saves that value to the database:
<h3>Add a location </h3></br></br>
<div class="addition">
<form method="POST" action="" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col">
<input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Location name" name="name" autocomplete="off">
</div>
<div class="col">
<input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Description" name="desc" autocomplete="off">
</div>
<div class="col">
<button type="submit" class="btn btn-primary">Submit</button>
</div></br></br>
</form> </br></br>
<h3>Overview locations</h3>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for item in all_locations %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ item.name }}</td>
<td>{{ item.desc }}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'update_location' item.id %}" >update</a></td>
</tr>
my views.py with my creation function and my update function
def location(request):
all_locations = Location.objects.all()
if request.method == "POST":
loc_form = LocationForm(request.POST or None)
if loc_form.is_valid():
loc_form.save()
return render(request, 'location.html', {"all_locations": all_locations})
else:
return render(request, 'location.html', {"all_locations": all_locations})
return render(request, 'location.html', {"all_locations": all_locations})
def updateLocation(request, pk):
all_locations = Location.objects.all()
location = Location.objects.get(id=pk)
loc_form= LocationForm(instance=location)
name = loc_form.instance.name
desc = loc_form.instance.desc
print(name)
print(desc)
return render(request, 'location.html', {"all_locations": all_locations, "name": name, "desc": desc})
my models.py
class Location(models.Model):
creation_date = models.DateTimeField(auto_now = True)
name = models.CharField(max_length=50, default=None)
desc = models.CharField(max_length=250, default="", null=True, blank=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
and my urls.py
urlpatterns = [
path('', views.index, name="index"),
path('locations', views.location, name="location"),
path('locations/<str:pk>', views.updateLocation, name="update_location"),
]
So basically i'm stuck at putting the old data back into the html input.
I've tried with a different view as well but i had basically the same issue.
Any suggestions? Thanks a lot!
I figured it out whilest doing something else:
add value="{{ name }}" to the html file on the input line. Do the similar thing for description

Django: how to get an object of manager on admin page

I am new to Django and I am working on a project. In my project an admin will have the power to assign the project to a manager. So I want to render the name of all the managers from the database so that it will be displayed to the admin.
here is my .html file where I want to render the name of the manager in:
<div class="body table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>S No.</th>
<th>COMPANY NAME</th>
<th>TEAM MEMBER</th>
<th>EMAIL</th>
<th>ASSIGN TEAM</th>
</tr>
</thead>
<tbody>
{%for team in object%}
<tr>
<form id="form_id" method="POST" action = "{% url 'accept' %}">
{% csrf_token %}
<th scope="row"> {{ forloop.counter }}</th>
<td>{{team.company_name}}</td>
<td>{{team.team_member}}</td>
<td>{{team.email}}</td>
<td>
<select name="manager">
{% for manager in managers %}
<option value ="{{manager.id}}">{{manager.name}}</option>
{% endfor %}
</select>
<!-- </div> -->
</td>
</tr>
{% endfor %}
</tbody>
</table>
Here is my model for manager:
class manager(models.Model):
name = models.CharField(max_length= 500)
designation = models.CharField(max_length= 500)
class Meta:
permissions = [
("edit_task", "can edit the task"),
]
def __str__(self):
return self.name
Here is my views.py;
def accept(request):
obj= Create_Team.objects.filter(status='Accept')
if request.method == 'POST':
acc = manager()
manager_id = int(request.POST.get('manager', 1))
acc.manager = manager.objects.get(pk=manager_id)
return render(request, "admin/accept.html", {"object": obj})
In the admins page, I want to display all the names of the managers. I have added the image of the admin page.
I think you forgot to include the managers queryset in the context variable
def accept(request):
obj= Create_Team.objects.filter(status='Accept')
managers = manager.objects.all()
if request.method == 'POST':
acc = manager()
manager_id = int(request.POST.get('manager', 1))
acc.manager = manager.objects.get(pk=manager_id)
return render(request, "admin/accept.html", {"object": obj, "managers": managers})

Django fields editable in create but not in edit

I am creating a small application where I am able to add / modify / delete / view a member.
def member_edit(request,member_id):
MemberForm = modelform_factory(Member, fields=('employee_id', 'employee_name'))
if request.method == 'POST':
member = MemberForm(request.POST)
if member.is_valid():
member.save()
return HttpResponseRedirect(reverse("members:member_view"))
else:
member = get_object_or_404(Member, pk=member_id)
return render(request, 'members/member_edit.html', {'member': member})
I notice that instead of being able to edit all the fields become in display mode.
<form action="" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<table>
<tr>
<th> <label for="{{ member.employee_id.id_for_label }}">Employee id:</label> </th>
<td> <input type="text" value = {{ member.employee_id }} /> </td>
<td> {{ member.employee_id.errors }} </td>
</tr>
<tr>
<th> <label for="{{ member.employee_name.id_for_label }}">Employee Name:</label> </th>
<td> <input type="text" value = {{member.employee_name }} /></td>
<td> {{ member.employee_name.errors }} </td>
</tr>
</table>
<input type="submit" value="Update">
If I change the member_edit function to this, it works but I don't have any data to change(obviously) :
def member_edit(request,member_id):
MemberForm = modelform_factory(Member, fields=('employee_id', 'employee_name'))
if request.method == 'POST':
member = MemberForm(request.POST)
if member.is_valid():
member.save()
return HttpResponseRedirect(reverse("members:member_view"))
else:
member = MemberForm() # change made only here
return render(request, 'members/member_edit.html', {'member': member})
What am I missing here ?
I think you need to pass the member instance to the form.
from django.shortcuts import get_object_or_404
def member_edit(request, member_id):
MemberForm = modelform_factory(Member, fields=('employee_id', 'employee_name'))
if request.method == 'POST':
instance = get_object_or_404(Member, id=member_id)
member = MemberForm(request.POST, instance=instance)
if member.is_valid():
member.save()
return HttpResponseRedirect(reverse("members:member_view"))
else:
member = MemberForm() # change made only here
return render(request, 'members/member_edit.html', {'member': member})

how to show value in table form since now only showing heading of table

Timesheet.html is basically a form to fill in details. I have created a list_timesheet.html to list out all the timesheet being filled. But i have no idea when i run it only heading being showed like this :
{ % for item in query_results % } { % end for % }
Student ID Student Name Start Date End Date
list_timesheet.html
<form method="POST" class="display" cellspacing="0" width="100%">
{% csrf_token %}
<table>
<tr>
<th> Student ID </th>
<th> Student Name </th>
<th> Start Date </th>
<th> End Date </th>
</tr>
{ % for item in query_results % }
<tr>
<td>{{item.studentID}}</td>
<td>{{item.studentName}}</td>
<td>{{item.startDate}}</td>
<td>{{item.endDate}}</td>
</tr>
{ % end for % }
</table>
</form>
timesheet.html
<form method="POST" onsubmit="return validation()">
{% csrf_token %}
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Student ID: {{timesheet.studentID}}</p>
<input id="sid" type="field" name="studentid">
</div>
</div>
<div class="sub-content">
<div>
<p>Student Name: {{timesheet.studentName}}</p>
<input id="sname" type="field" name="studentname">
</div>
</div>
<div class="sub-content">
<div>
<p>Start Date: {{timesheet.startDate}}</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date: {{timesheet.endDate}}</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>
<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements to continue receiving my scholarship
allowance.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" class="button" name="submit" value="submit" >
</div>
</div>
</div>
</form>
models.py
class Timesheet(models.Model):
studentID = models.CharField("Student ID", max_length=8, primary_key=True, default="")
studentName = models.CharField("Student Name", max_length=500, default="")
startDate = models.DateField("Start Date", max_length=8)
endDate = models.DateField("End Date", max_length=8)
def __str__(self):
return self.studentID
#consists of all the details of the timesheet under 'View Timesheets'
class LTimesheet(models.Model):
timesheet = models.ForeignKey(Timesheet, on_delete=models.CASCADE)
status = models.CharField("Status", max_length=100)
views.py
def timesheet(request):
if request.method == "POST":
if 'submit' in request.POST:
form = TimesheetForm(request.POST)
if form.is_valid():
timesheet = form.save(commit=False)
timesheet.save()
return HttpResponseRedirect(reverse('hrfinance/timesheet.html'))
#if the form is not valid, redirect the student to the same page
else:
form = TimesheetForm()
return render(request, 'hrfinance/timesheet.html', {'form': form})
else:
form = TimesheetForm()
return render(request, 'hrfinance/timesheet.html', {'form': form})
def ltimesheet(request):
query_results = LTimesheet.objects.all()
data={query_results:query_results}
return render(request, 'hrfinance/list_timesheet.html', data)
class TimesheetForm(forms.ModelForm):
class Meta:
model = Timesheet
fields = '__all__'
def timesheet(request):
if request.method == "POST":
if 'submit' in request.POST:
form = TimesheetForm(request.POST)
if form.is_valid():
timesheet = form.save(commit=False)
timesheet.save()
return HttpResponseRedirect(reverse('hrfinance/timesheet.html'))
#if the form is not valid, redirect the student to the same page
else:
form = TimesheetForm()
return render(request, 'hrfinance/timesheet.html', {'form': form})
else:
form = TimesheetForm()
return render(request, 'hrfinance/timesheet.html', {'form': form})
change your view to this
in your template after querying in the view.py
{% for item in query_results %}
<tr>
<td>{{item.studentName }}</td>
<td>{{item.put_field_you_have_in_model }}</td>
</tr>
{% endfor %}
and in list_timesheet.html
{% for item in query_results %}
<tr>
<td>{{item.studentID}}</td>
<td>{{item.studentName}}</td>
<td>{{item.startDate}}</td>
<td>{{item.endDate}}</td>
</tr>
{% endfor %}

Categories

Resources