How I save data on database table from django? - html

I made a django website where doctor and patient both can signup. Patient mark their problem and it will send to those doctor whom he/she want, like question asking on Quora. And I also want to save data in db
But my webpage when patient insert data it does not save in database.
Models.py
class patients(models.Model):
fever=models.BooleanField()
others=models.TextField()
Views.py
from django.shortcuts import render, redirect
from .models import patients
def patient(request):
if request.method == 'POST':
fever=request.POST['fever']
others=request.POST['others']
patient_details=patients(fever= fever,others = others)
patient_details.save()
return render(request, "patient")
else:
return render(request, "patient.html")
Patient.html
<form action="patient">
<label for="exampleFormControlTextarea1"><u>Mark Your Problems</u></label><br>
<!-- FEVER -->
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1">
<label class="form-check-label" name="fever" for="inlineCheckbox1">Fever </label>
</div>
<!--Others-->
<h6 style="text-align:left;"><u>Others</u></h5>
<div class="form-group">
<textarea class="form-control" name="others" id="exampleFormControlTextarea1" rows="1"></textarea>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit"> SUBMIT </button>
</h6>
</form>
How I store these data on database ?

try this line
patient_details=patients.objects.create(Fever= fever, others = others)
instead of :
patient_details=patients(Fever= fever, others = others)

Related

Upload 2 files from 2 inputs with Flask

I need to have 2 buttons for uploading 2 different files by using Flask, but I cannot find the way to do that.
The answer that I found several times was to add "multiple" in parameters, but this is not what I want because I need to have a button for each file.
In my form I need the onchange="form.submit() parameter, and I want to have others entries.
The files I have tu upload are excel files
upload.html :
<form method="POST" enctype="multipart/form-data">
<div class="input-field">
<input type="text" name="other_input" onchange="form.submit()" id="other_input">
<label>Other Input</label>
</div>
<div class="div_files">
<label class="Button"> Select File 1</label>
<input name="1st_file" type="file" onchange="form.submit()" value="1st_file">
<label class="Button"> Select File 2</label>
<input name="2nd_file" type="file" onchange="form.submit()" value="2nd_file">
</div>
<input type="submit" value="Show result" action="other" id="btns">
</form>
app.py :
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/index, methods=['POST', 'GET'])')
def index():
file1 = request.files["1st_file"]
file2 = request.files["2nd_file"]
return render_template('other_page.html', variable1=file1, variable2=file2)
I tried to use 2 different forms to get what I want, but it didn't work either
Thank you for your help :)

Using pure HTML forms in Django views

SO I'm tryng to create a Django site using HTML forms.The form takes in vendor choice and amount, which is then needed to be passed into views. The employee table's balance needs to be updated, with the amount paid deducted from the balance of the current logged in user, and an entry needs to be added to the transaction table stating the details, with credit = 0, rest info taken from form. How can this be done?
Given below are my files:
html:
<form method="POST" action="/profiles/updatingBalance">
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" value="1" id="defaultUnchecked" name="defaultRadios">
<label class="custom-control-label" for="defaultUnchecked">Vendor 1</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" value="2" id="defaultUnchecked" name="defaultRadios">
<label class="custom-control-label" for="defaultUnchecked">Vendor 2</label>
</div>
<input type="" class="form-control" id="amount1" name="amt" aria-describedby="emailHelp" placeholder="Enter amount">
<br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Models.py:
from django.db import models
from django.contrib.auth.models import User
import django
import datetime
# Create your models here.
class vendor(models.Model):
id = models.CharField(max_length=20, on_delete=models.CASCADE, primary_key=True)
name = models.CharField(maxlength=30, on_delete=models.CASCADE)
class employee(models.Model):
name = models.OneToOneField(User, on_delete=models.CASCADE)
id = models.CharField(max_length=20, on_delete=models.CASCADE, primary_key=True)
balance = models.IntegerField(default=0)
class transaction(models.Model):
vendor_id = models.ForeignKey(vendor, on_delete=models.CASCADE)
emp_id = models.ForeignKey(employee, on_delete=models.CASCADE)
debit = models.IntegerField()
credit = models.IntegerField()
timestamp = models.DateField(_("Date"), default=datetime.date.today)
Here's the views.py I tried. I got till updating emplyee table's balance(not sure if it's correct):
def updatingBalance(request):
if request.method=="POST":
ven_id = request.POST["defaultRadios"]
amount = request.POST["amt"]
x = employee.objects.filter(id = request.User.id)
x.balance = x.balance - amount
p = transaction(vendor_id =ven_id.value, emp_id = request.User.id, debit=amount, credit=0)
p.save()
return render(request, 'profiles/userLogin.html', employee)
return HttpResponseRedirect(request.META.get('profiles/userLogin.html'))
I am confused as to how data can be taken from pure html forms( I'm a beginner), and how that info can be used to get my desired results. Any help would be greatly appreciated.
to get the data from form you should pass the view that will process the information in the action attribute of the form, then with request.POST dictionary you can extract the data that you want.
html:
<form method="POST" action="/Yourapp/theview/">
your html
</form>
views:
def theview(request):
amount=request.POST["amt"]

flask multiple submit button

I am using flask and jinja2 to create a simple web app to serve up a simple sklearn algorithm for predictions.
In my html I need to get 4 variables: client id, textid, textid1, textid2
It currently works when I have it all connected to one submit button. But I would like to have two submit buttons to have the client id submit at the top of the page and the textid stuff at the bottom of the page. When I try to have two submit buttons it causes the page to refresh and I not able to connect the client id to the 3 textid vars.
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST">
<input name="text", id='text', placeholder="Client ID #", value="{{ client_id|round|int }}" >
<br>
<label>Enter 3 suggestions</label>
<br>
<input name="textid", placeholder="Suggested Model ID #", value="{{ request.form['textid'] }}"/>
<input name="textid1", placeholder="Suggested Model ID #", value="{{ request.form['textid1'] }}"/>
<input name="textid2", placeholder="Suggested Model ID #", value="{{ request.form['textid2'] }}"/>
<input type="submit" >
</form>
</div>
I'm simply grabbing it in flask like this:
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
try:
client_id=request.form['text']
except:
#custom function when client id is not entered to get random one
client_id = recommender.random_client_id()
try:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
#other functional code after this
How can I break up the html to get two submit buttons? Thanks!!
Now that you have updated your code, all you need to do is add hidden inputs to identify where the click was originated from. Also Remove the leading slash from your url_for like I did below
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="hidden" name="btn_identifier" value="client_id_identifier" />
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="hidden" name="btn_identifier" value="text_id_identifier" />
<input type="submit" value="Submit">
</form>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
if request.methods == 'POST':
if request.form['btn_identifier'] == 'client_id_btn':
try:
client_id=request.form['text']
except:
# I think this would go in the second elif statement
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
elif request.form['btn_identifer'] == 'text_id_btn':
# run some code to handle a click that was originated from the second button
return render_template('index.html')
if __name__ == '__main__':
app.run()
I made some changes to your code.
index.html
<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="submit" value="Submit">
</form>
</div>
main.py
from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)
#app.route('/suggestion', methods=['GET', 'POST'])
def suggestion():
if request.method == 'POST':
try:
client_id=request.form['text']
except:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
return render_template('index.html')
if __name__ == '__main__':
app.run()
Note: Values are store in the variable, print to see
I have simplified the process of fetching the info from multiple buttons. Do note that you require the python flask framework for the "request" method.
home.html
<div class="container mt-5">
<div class="row col-4">
<form method="POST" class="form-register">
<input type="submit" name="submit_button" value="Add Email">
<input type="submit" name="submit_button" value="Clear Recipients">
</form>
</div>
</div>
run.py
if request.method == 'POST':
if request.form['submit_button'] == 'Add Email':
print("add email")
elif request.form['submit_button'] == 'Clear Recipients':
print("clear recipients")
you may refer to the link provided for more example
https://www.codegrepper.com/code-examples/python/checking+if+button+pressed+flask

creating forms in django - error in output

I have the following code in various places to attempt to produce a form in Django that takes data and writes it to the database
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .forms import TeacherSignup
"""def teachers(request):
return render(request,'teachers/teachers.html')
"""
def teachers(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = TeacherSignup(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = TeacherSignup()
return render(request, 'teachers/teachers.html', {'form': form})
teachers.html (this is the html page that contains the form)
<form action="/teachers/" method="post" style="border:1px solid #ccc">
{% csrf_token %}
{{ form }}
<div class="container">
<label><b>Email</b></label>
<input id="email" input type="text" placeholder="Enter Email" name="email" required>
<label><b>Centre/School Name</b></label>
<input id="school_name" input type="text" placeholder="Enter School or Centre Name" name="school_name" required>
<label><b>Password</b></label>
<input id="password" input type="password" placeholder="Enter Password" name="password" required>
<label><b>Repeat Password</b></label>
<input id="password_repeat" input type="password" placeholder="Repeat Password" name="password_repeat" required>
<input type="checkbox" checked="checked"> Remember me
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
forms.py
from django import forms
class TeacherSignup(forms.Form):
email=forms.CharField(label='email',max_length=100)
school_name=forms.CharField(label='school_name',max_length=100)
password=forms.CharField(label='password',max_length=100)
password_repeat=forms.CharField(label='password_repeat',max_length=100)
On running the server however, it produces TWO forms: The form I've created in the html and the one presumably created in the forms.py.
How do I use the form in teachers.html (which is at the end of the page) and use this created form to write data to the database, or does Django require that I created it using the forms.py?
A detailed explanation would be appreciated, with examples if possible.
In your template you can render field by field of your form
Something like this in teachers.html
<form action="/teachers/" method="post" style="border:1px solid #ccc">
{% csrf_token %}
<div class="container">
<label><b>Email</b></label>
{{ form.email }}
<label><b>Centre/School Name</b></label>
{{ form.school_name }}
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
and do the same thing for the rest
if you want to add placeholder attribute you need to add widget param to your fields and the same if you want that your passwords fields could hide text
forms.py
from django import forms
class TeacherSignup(forms.Form):
email=forms.CharField(label='email',max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Enter Email'})
school_name=forms.CharField(label='school_name',max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Enter School or Centre Name'})
password=forms.CharField(label='password',max_length=100, widget=forms.PasswordInput)
password_repeat=forms.CharField(label='password_repeat',max_length=100, widget=forms.PasswordInput)

Form error in a Django form with Bootstrap tagsinput plugin

I am using Bootstrap/Tagsinput for adding tags in a Django input form.
Problem
The first field is where I want the tags added and the second field is a simple text field. I am able to add the tags in the first field and a normal text in the second field. But, when I submit the form the input values get removed and am returned to the original form. The django form.errors indicates that the second field is empty with a This field is required message even though I had entered a text! What am I missing?
form.errors
Is returning
<ul class="errorlist"><li>experiments<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Here are the related files
tags_add.html
I am using a custom html rather than the django's forms.as_table. All required css and min.js have been added in the html file.
<form id="defaultForm" method="post" action="" class="form-horizontal">{% csrf_token %}
<div class="form-group">
<label class="col-lg-3 control-label">Tags:</label>
<div class="col-lg-5">
<input type="text" name="tags" id="aa" class="form-control" value="" data-role="tagsinput" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Experiments:</label>
<div class="col-lg-5">
<input type="text" name="tags" id="exp_id" class="form-control" value="" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
forms.py
class TagsForm(ModelForm):
tags = forms.CharField( widget=forms.TextInput(attrs={'size':'20', 'placeholder':'add tags'}), required=True )
experiments = forms.CharField( widget=forms.TextInput(attrs={'size':'20', 'placeholder':'expid'}), required=True )
def __init__(self, *args, **kwargs):
super(TagsForm, self).__init__(*args, **kwargs)
class Meta:
model = Tags
fields = '__all__'
views.py
def view_tags(request,formtype):
form_type = formtype
if request.method == "POST":
form = form_type(request.POST or None)#, extra=extra_additives)
if form.is_valid():
instances = form.save(commit=False)
temp_str= str(instances)
print temp_str
experiment_tags = temp_str
return HttpResponse(experiment_tags)
else:
print "from view_tags {0}".format(form.errors)
return HttpResponse(form.errors)
else:
form = TagsForm()
return render(request, 'tags_add.html', {'form': form})
models.py
class Tags(models.Model):
tags = models.CharField(max_length=1000)
experiments = models.CharField(max_length=1000)
def __str__(self):
return ':'.join([self.tags, self.experiments])
I got it working by adding the following to a scripts tag in the html file:
$("input[name='tags']").tagsinput({
confirmKeys:[13] //-- Only enter
});