Can anyone please help me solve this problem in my view. I have been stuck for quite a time now. Any help will be highly appreciated.
My Error
System check identified no issues (0 silenced).
December 18, 2019 - 09:28:36
Django version 2.2.8, using settings 'Timesheet.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[18/Dec/2019 09:28:42] "GET / HTTP/1.1" 200 6027
Internal Server Error: /
Traceback (most recent call last):
File "D:\Django\TimeSheetProject\morabu\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\Django\TimeSheetProject\morabu\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
"returned None instead." % (callback.__module__, view_name)
ValueError: The view morabu_timesheet.views.create_timesheet_view didn't return an HttpResponse object. It returned None instead.
[18/Dec/2019 09:29:02] "POST / HTTP/1.1" 500 65059
My views.py
And I don't know whether my method is correct or not but I want to save the data from the raw HTML form only since I have to do some front end validation using java script.
from django.shortcuts import render
from .models import TimesheetDetails
# Create your views here.
def create_timesheet_view(request):
if request.method=="POST":
if(request.POST.get('dateToday') and request.POST.get('dayToday') and request.POST.get('startTime')
and request.POST.get('endTime')and request.POST.get('breakTime')and request.POST.get('normalTime')
and request.POST.get('overTime')and request.POST.get('holidayTime')and request.POST.get('weekType')
and request.POST.get('attendance')and request.POST.get('content')):
post = TimesheetDetails()
post.date = request.POST.get('dateToday')
post.day = request.POST.get('day_today')
post.startTime = request.POST.get('startTime')
post.endTime = request.POST.get('endTime')
post.breakTime = request.POST.get('breakTime')
post.normalTime = request.POST.get('normalTime')
post.overTime = request.POST.get('overTime')
post.holidayTime = request.POST.get('holidayTime')
post.weekType = request.POST.get('weekType')
post.attendance = request.POST.get('attendance')
post.content = request.POST.get('content')
if post.is_valid():
try:
post.save()
return render(request,'timesheet/view_timesheet.html')
except :
pass
else:
return render(request,'timesheet/create_timesheet.html')
def view_timesheet(request):
return render(request,"timesheet/view_timesheet.html")
my models.py
class TimesheetDetails(models.Model):
date = models.CharField(max_length = 10)
day = models.CharField(max_length = 10)
startTime = models.CharField(max_length =10)
endTime = models.CharField(max_length =10)
breakTime = models.CharField(max_length=3)
normalTime = models.CharField(max_length=10)
overTime = models.CharField(max_length = 10)
holidayTime = models.CharField(max_length = 10)
weekType = models.CharField( max_length = 10)
attendance = models.CharField( max_length = 10)
content = models.TextField( max_length = 300)
And Lastly my HTML page
<form action="" method="post" autocomplete="off">
{% csrf_token %}
<h3 id="date_Today"></h3>
<p id="dayToday" name="dayToday" class="hideMe"></p>
<p id="dateToday" name="dateToday" class="hideMe"></p>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="startTime">開始時間</label>
<input type="text" class="form-control" name="startTime" id="startTime" placeholder="(HH:mm)フォーマットに入力して下さい">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="endTime">終業時間</label>
<input type="text" class="form-control" name="endTime" id="endTime" placeholder="(HH:mm)フォーマットに入力して下さい">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="breakTime">休憩時間</label>
<input type="text" class="form-control" name="breakTime" id="breakTime" >
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="normalTime">時間内時間</label>
<input type="text" class="form-control" name="breakTime" id="normalTime" >
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="extraTime">時間外時間</label>
<input type="text" class="form-control" name="extraTime" id="extraTime">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="holidayTime">休日時間</label>
<input type="text" class="form-control" name="holidayTime" id="holidayTime" >
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="weekType">区分は間違えないでしょうか?</label>
<select class="form-control" name="weekType" id="weekType">
<option value="平日">平日</option>
<option value="休日">休日</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="reason">勤怠を選んでください!</label>
<select class="form-control" name="attendance" id="attendance">
<option value="欠勤">欠勤</option>
<option value="有給休暇">有給休暇</option>
<option value="振替休日">振替休日</option>
<option value="特別休暇">特別休暇</option>
<option value="残業">残業</option>
<option value="早退">早退</option>
<option value="遅刻">遅刻</option>
<option value="直行">直行</option>
<option value="直帰">直帰</option>
<option value="その他">その他</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="workContent">恐れ入りますが、仕事の内容を書いていただきませんでしょうか?</label>
<textarea class="form-control" name="workContent" id="workContent" rows="3"></textarea>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-success btn-block"><i class="fas fa-database"></i> 保存</button>
</form>
Welcome to SO :)
You're not returning a HttpResponse when post.is_valid() returns False.
from django.shortcuts import render
from .models import TimesheetDetails
# Create your views here.
def create_timesheet_view(request):
if request.method=="POST":
if(request.POST.get('dateToday') and request.POST.get('dayToday') and request.POST.get('startTime')
and request.POST.get('endTime')and request.POST.get('breakTime')and request.POST.get('normalTime')
and request.POST.get('overTime')and request.POST.get('holidayTime')and request.POST.get('weekType')
and request.POST.get('attendance')and request.POST.get('content')):
post = TimesheetDetails()
post.date = request.POST.get('dateToday')
post.day = request.POST.get('day_today')
post.startTime = request.POST.get('startTime')
post.endTime = request.POST.get('endTime')
post.breakTime = request.POST.get('breakTime')
post.normalTime = request.POST.get('normalTime')
post.overTime = request.POST.get('overTime')
post.holidayTime = request.POST.get('holidayTime')
post.weekType = request.POST.get('weekType')
post.attendance = request.POST.get('attendance')
post.content = request.POST.get('content')
if post.is_valid():
try:
post.save()
return render(request,'timesheet/view_timesheet.html')
except :
pass
else:
return render(request,'timesheet/create_timesheet.html') #Adding this line
else:
return render(request,'timesheet/create_timesheet.html')
def view_timesheet(request):
return render(request,"timesheet/view_timesheet.html")
Related
I am working on a Django project .In front-end I want to add user data through input tags but I do not know how to save data through input tags
My models.py file is::
class User(AbstractBaseUser):
full_name = models.CharField(max_length=255, blank=True, null=True)
sur_name = models.CharField(max_length=255, blank=True, null=True)
email = models.EmailField(max_length=255 ,unique=True)
choose_subject = models.CharField(choices=SUBJECT_CHOICES , max_length=100)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
time_stamp = models.DateTimeField(auto_now_add=True)
father_name = models.CharField(max_length=255)
father_sur_name = models.CharField(max_length=255)
mobile_phone_number = models.IntegerField(blank=True,null=True)
father_email = models.EmailField(max_length=255, unique=True)
fiscal_code = models.CharField(max_length=20)
address = models.CharField(max_length=200 )
A part of my register.html file is:
<div class="card-body">
<h2 class="title">Registration Form</h2>
<form method="POST">{% csrf_token %}
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Full name</label>
<input class="input--style-4" type="text" name="first_name"{{form.full_name}}>
</div>
</div>
<div class="col-2">
<div class="input-group">
<label class="label">Sur name</label>
<input class="input--style-4" type="text" name="last_name"{{form.sur_name}}>
</div>
</div>
</div>
I just want the Django model field to be working in input tags
You must create in the views.py file a method in which the templates and the logic of it, an example can be the following
views.py
#csrf_exempt
def register(request):
if request.method == 'POST':
var1 = request.POST.get('var1')
var2 = request.POST.get('var2')
var3 = request.POST.get('var3')
#Save to the database here
return render_to_response(
'home.html',
{'message': 'Update Success', }
)
else:
#elif request.method == "GET":
obj = table.objects.all()
if obj:
ctx['data'] = obj
return render(request, template_name, ctx)
and in your template add a form tag
<form method="POST">
{ % csrf_token % }
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Full name</label>
<input class="input--style-4" type="text" value={{data.full_name}}>
</div>
</div>
<div class="col-2">
<div class="input-group">
<label class="label">Sur name</label>
<input class="input--style-4" type="text" value={{data.sur_name}}>
</div>
</div>
</div>
<input type="submit" value="OK">
</form>
refer this tutorial
I am trying to grab some data from the template, perform some arithmetic and display it to the end-users, I noticed that I am getting the wrong answers after manually calculating the result, so I tried to print the values which I have grabbed from my templates on the console and I get the right answer but the final calculation is having some errors in it.
I don't know how to grab the "NET_COST", "PROFIT" and "ROI" to the message, that's why I have used a static "$100". I know little how "f strings" and "formats" but I don't know how to apply it here.
These are the values I am entering in the form:
views.py
def Profitcalculator(request):
if request.method == 'POST':
SP = request.POST.get("sp")
fees_on_sp = request.POST.get("fees-on-sp")
transport = request.POST.get("transport")
extra_cost = request.POST.get("extra-cost")
product_cost = request.POST.get("product-cost")
ADS = request.POST.get("ads")
GIVEAWAY = request.POST.get("giveaway")
NET_COST = (fees_on_sp + transport + extra_cost + product_cost + ADS + GIVEAWAY)
PROFIT = (int(SP) - int(NET_COST))
ROI = (int(PROFIT)/int(NET_COST)) * 100
print(SP, ADS, GIVEAWAY)
print(NET_COST, PROFIT, ROI)
messages.info(request, "Your NET_COST is $100")
return render(request, 'core/profit-calculator.html')
console
600 2 7
510425027 -510424427 -99.99988245090498
profit-calculator.html
<form method="post">
{% csrf_token %}
<div class="row form-group">
<div class="col-md-4">
<input class="m-t-10 au-input au-input--full" type="number" name="sp" placeholder="Selling Price" required>
</div>
<div class="col-md-4">
<input class="m-t-10 au-input au-input--full" type="number" name="fees-on-sp" placeholder="Estimated Fees on selling platform(per unit)" required>
</div>
<div class="col-md-4">
<input class="m-t-10 au-input au-input--full" type="number" name="transport" placeholder="Total transport Cost(per unit)" required>
</div>
</div>
<div class="row form-group">
<div class="col-md-3">
<input class="m-t-10 au-input au-input--full" type="number" name="extra-cost" placeholder="Any extra cost(per unit)" required>
</div>
<div class="col-md-3">
<input class="m-t-10 au-input au-input--full" type="number" name="product-cost" placeholder="Product Cost" required>
</div>
<div class="col-md-3">
<input class="m-t-10 au-input au-input--full" type="number" name="ads" placeholder="Ads(per unit)" required>
</div>
<div class="col-md-3">
<input class="m-t-10 au-input au-input--full" type="number" name="giveaway" placeholder="Total Cost per promotional giveaway" required>
</div>
</div>
<button class="au-btn au-btn--block au-btn--green m-b-20" type="submit">Calculate Net Cost, Profit and ROI Percentage</button>
</form>
You need to convert all your POST values to int. And then you can do your calculations.
def Profitcalculator(request):
if request.method == 'POST':
query = request.POST
SP = int(query.get("sp") or 0)
fees_on_sp = int(query.get("fees-on-sp") or 0)
transport = int(query.get("transport") or 0)
extra_cost = int(query.get("extra-cost") or 0)
product_cost = int(query.get("product-cost") or 0)
ADS = int(query.get("ads") or 0)
GIVEAWAY = int(query.get("giveaway") or 0)
NET_COST = fees_on_sp + transport + extra_cost + product_cost + ADS + GIVEAWAY
PROFIT = SP - NET_COST
ROI = (PROFIT/NET_COST) * 100
print(SP, ADS, GIVEAWAY)
print(NET_COST, PROFIT, ROI)
messages.info(request, f"Your Net Cost is ${NET_COST}")
return render(request, 'core/profit-calculator.html')
Suppose I want to give user 2 option in html select tag.
i want help to, full MVC implementation in Python.
i dont want to use django form.
Sample html code:
<form method="POST">
<div class="form-row">
<div class="name">Name</div>
<div class="value">
<div class="input-group">
<input class="input--style-5" type="text" name="name" required>
</div>
</div>
</div>
<div class="form-row">
<div class="name">Applying In</div>
<div class="value">
<div class="input-group">
<div class="rs-select2 js-select-simple select--no-search">
<select name="subject" required>
<option disabled="disabled" selected="selected"> Applying Department</option>
<option>Backend</option>
<option>Mobile</option>
</select>
<div class="select-dropdown"></div>
</div>
</div>
</div>
</div>
Use option = request.GET['subject'] in a view.py which will be invoked on form submission. You will get only one option because you are selecting single option in template.
suppose we have a model like this:
from django.db import models
from django import forms
class Foo(models.Model):
CHOICES= (
('choice_one', 'choice one'),
('choice_two', 'choice two'),
)
user_choices= models.CharField(max_length=10, choices=CHOICES)
class FooForm(forms.ModelForm):
class Meta:
model = Foo
fields = ['user_choices']
views:
from django.shortcuts import redirect, render
from . import models
def user_choices(request):
url = request.META.get('HTTP_REFERER') # get last url
if request.method == 'POST':
form = models.FooForm(request.POST)
if form.is_valid():
data = models.Foo()
data.user_choices= request.GET.get('user_choices')
data.save()
return redirect(url)
return render(request, 'user_choices.html', context)
then in the template:
<form action="{% url 'app_name:user_choices' %}" method="POST"> # url to above function
<select name ='user_choices'>
<option name="user_choices" value="choice_one">choice one</option>
<option name="user_choices" value="choice_two">choice two</option>
</select>
<button type="submit">submit</button>
</form>
I am trying to send the data from the database to the Html form, but I'm getting an error like this
TypeError: 'ImmutableMultiDict' objects are immutable
this is the flask code for editing the data
#app.route('/edit-project/<string:id>', methods = ['GET', 'POST'])
def edit_project(id):
project = Project.query.get(id)
request.form['title'] = project.title
request.form['link'] = project.link
request.form['description'] = project.description
if request.method == 'POST':
title = request.form['title']
link = request.form['link']
description = request.form['description']
image = request.files['image']
image.save(os.path.join(app.config["IMAGE_UPLOADS"], 'project/'+ project.image))
return render_template('project/edit_project.html')
The Html template 'edit_project.html' is shown below
<div class="container">
<form method="POST" id="project-form" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" class="form-control" id="title" placeholder="Title">
</div>
<div class="form-group">
<input type="text" name="link" class="form-control" id="title" placeholder="Project Link">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Description</label>
<textarea id = project-form name="description" class="form-control" id="description" rows="3"></textarea>
</div>
<div class="input-group" style="width: 30%;">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="image" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" for="inputGroupFile01">Upload image</label>
</div>
</div>
<div class="form-group" style="padding-top: 2rem;">
<button type="submit" class="btn btn-primary">Publish</button>
</div>
</form>
</div>
Is there is any way to display the data in the form without using WTForms or do I've to use WTForms instead?
Thanks in advance.
Can you use jinja templating?
render_template() takes data argument. You can pass the data from your DB to that call and use jinja templates in HTML to render it. Setting the values of your input will do.
For example:
Your data is data = {title:"apple"}
And, return render_template("project/edit_project.html", data=data) will provide you data object in HTML file.
There, you can use jinja like this:
<div class="form-group">
<input type="text" name="title" class="form-control" id="title" placeholder="Title" value={{data.text}}>
</div>
Hope it helps!
I am inserting new records in a model using a function-based view, but the problem is that some fields aren't being saved.
I get all fields through request.POST.get(field_name) and assign them to a variable before saving them to the corresponding field of a model.
views.py
import datetime
from django.shortcuts import render, redirect
def CreateExam(request):
if request.method == "POST":
st_exam = exam()
topic = request.POST.get("topic")
auth = request.POST.get("author")
date_now = request.POST.get("date_now")
st_exam.topic = request.POST.get("topic")
st_exam.auth = request.POST.get("author")
st_exam.date = date_now
st_exam.total_grade = request.POST.get("total_grade")
st_exam.semester_id = request.POST.get("semester")
st_exam.exam_id = auth[0:2] + topic[0:2] + date_now
# st_exam.course = request.POST.get("course")
y = datetime.now()
st_exam.semester_id = str(y.year) +'-'+request.POST.get("semester")
st_exam.save()
return redirect('/teacher/')
else:
return render(request, '500.html', {"error": "Ooops Illegal access"})
models.py
from django.db import models
class exam(models.Model):
exam_id = models.CharField(max_length=40,null=True)
date = models.CharField(max_length=40,null=True)
total_grade = models.FloatField(null=True)
author= models.CharField(max_length=40,null=True)
topic = models.CharField(max_length=40,null=True)
course = models.CharField(max_length=40,null=True)
semester_id = models.CharField(max_length=40,null=True)
template.html
<form method="post" action="/teacher/create/exam/">
{% csrf_token %}
<div class="form-group col-md-8">
<label for="topic">Topic</label>
<input type="text" name="topic" class="form-control" id="topic"/>
</div>
<div class="form-group col-md-8">
<label for="grade">Author</label>
<input type="text" name="author" class="form-control" id="author"/>
</div>
<div class="form-group col-md-8">
<label for="date">Date</label>
<input type="date" name="date_now" class="form-control" id="date"/>
</div>
<div class="form-group col-md-8">
<label for="grade">Course</label>
<input type="text" name="course" class="form-control" id="grade"/>
</div>
<div class="form-group col-md-8">
<label for="grade">grade</label>
<input type="number" name="total_grade" class="form-control" id="grade"/>
</div>
<div class="form-group col-md-8">
<label for="cat">Semester </label>
<select name="semester" class="form-control">
<option value="1"> Semester 1</option>
<option value="2"> Semester 2</option>
</select>
</div>
<button type="submit"
class="btn btn-primary m-t-15 waves-effect">Save
</button>
</form>
I expect all fields to be saved but the author field doesn't get saved