Adding data into the database with django by pressing enter - html

I do not see what I am doing wrong when trying to add data into the database. When I am pressing the button Submit, nothing is entered in the database. The same happens when pressing the key enter.
Here is my html file.
<script>
$(document).keypress(function(event) {
if (event.keyCode == 13 || event.which == 13) {
alert('enter key is pressed');
event.preventDefault();
}
});
</script>
<div class="col-md-6 col-md-offset-3">
<form method="POST" action="">
<p>
{% csrf_token %}
<input type="hidden" value="{{post.id}}" />
<div class="col-xs-16" style="margin: 0; 0;padding: 3%;">
<label for="inputsm">Oracle</label>
<input class="form-control input-md" type="text" value="{{ post }}">
<input type="submit" value="Submit" style="display: none" /> {{ form.body }}
<button type="submit" value="Submit" class="btn btn-success">Submit</button>
</p>
</div>
</form>
</div>
Here is the views.py
def post_list(request):
posts = Post.objects.all()
category = Category.objects.all()
context = {
'posts':posts,
'cat':category,
}
return render(request, 'journal/post_list.html', context)
def add_post(request):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST or None)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('post_details', pk=post.pk)
return render(request, 'journal/post_list.html', {'post': post})
else:
form = PostForm()
context = {
"form": form,
}
return render_to_response('journal/post_list.html', context)

Does the form get submitted? If not, maybe try adding some javascript to submit the form, when the key is pressed
$("form").submit();

Related

reset form method value to default when page refreshes

login.html
<form action="/login" method="post" name="login" id="login">
<input autocomplete="off" id="username" name="username" value="{{ hold }}" type="text">
<input id="password" name="password" type="password">
<button type="submit">Log In</button>
</form>
In above I have press submit button, while username is empty.
Then form submit with the post method and return render_template("login.html", xvalue=2) have executed.
After that I have refresh the login web page and I expect the request.method been assumed as default (get) and return render_template("login.html", xvalue=4) get executed.
But xvalue=2 passed, while the form method value is remained post.
#app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
if not request.form.get("username"):
return render_template("login.html", xvalue=2)
else:
return render_template("login.html", xvalue=3)
else:
return render_template("login.html", xvalue=4)
How can form method variable gets default get value, in case of page refreshed?
This is what i tried and it seemd to work
#app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
if not request.form.get("username"):
return render_template("login.html", xvalue=2)
else:
return render_template("login.html", xvalue=3)
elif request.method == "GET":
return render_template("login.html", xvalue=3)
hope this helps

Django - Multiple Select Box - Save Changes to Database

I was able to get a multiple select box working for edit mode:
<section class="container">
<div>
<select id="leftValues" size="5" multiple></select>
</div>
<div>
<input type="button" id="btnLeft" value="<<" />
<input type="button" id="btnRight" value=">>" />
</div>
<div>
<select id="rightValues" size="4" multiple>
{% for device in devices %}
<option>{{ device }}</option>
{% endfor %}
</select>
</div>
</section>
<div>
<input type="text" id="txtRight" />
</div>
</section>
<button type="submit" id="save">Save Changes</button>
<!--button type="cancel">Cancel</button-->
Maintenance Page</button>
</form>
<link rel="stylesheet" href="{% static 'css/msb.css' %}">
<script>
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected");
$("#rightValues").append(selectedItem);
});
$("#rightValues").change(function () {
var selectedItem = $("#rightValues option:selected");
$("#txtRight").val(selectedItem.text());
});
But when I select the save button, after making changes to the table, again in the template, edit_maintenance.html, it does not feed into the database.
The code in the views.py that relates to this is as follows:
def edit_maintenance(request, id):
license_key = Maintenance.objects.get(id=id)
maintenance_form = MaintenanceForm(instance=license_key)
devices = Devices.objects.filter(maintenance = id)
if request.method == 'POST':
print(request.POST)
maintenance_form = MaintenanceForm(request.POST, instance=license_key)
if maintenance_form.is_valid():
maintenance_form.save()
# return redirect('maintenance:edit_maintenance', id)
args = {
'maintenance_form' : maintenance_form,
'devices' : devices
}
return render(request, 'inventory/edit_maintenance.html', args)
I'm still fairly new to this so any tips, examples, would be great.
sadly, this was a novice's mistake. I re-ran makemigration and migrate and the functionality works just fine now ... for delete. Now I need to work on the code for adding.

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

Appear data in URL form bu using Django

I want to create a record and want to appear data in the form fields. How can I do that ? Do I need to write javascript for it. If you help me, really apprepriate it. Thanks for now.
Here is models.py;
class hesaplarim(models.Model):
hesap_id = models.AutoField(primary_key=True)
tc_no = models.IntegerField(unique=True)
name = models.CharField(max_length=55)
surname = models.CharField(max_length=55)
phone_number = models.IntegerField()
gender = models.CharField(max_length=5)
Here is views.py;
def home(request):
form = HesapForm(request.POST or None)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = HesapForm()
return render(request, 'home.html', {'form': form})
Here is forms.py;
class HesapForm(forms.ModelForm):
ERKEK = 'ERKEK'
KADIN = 'KADIN'
gender_choices = (
(ERKEK, 'ERKEK'),
(KADIN, 'KADIN')
)
tc_no = forms.IntegerField(widget=forms.NumberInput)
name = forms.CharField(widget=forms.TextInput)
surname = forms.CharField(widget=forms.TextInput)
phone_number = forms.IntegerField(widget=forms.NumberInput)
gender = forms.ChoiceField(choices=gender_choices)
class Meta:
model = hesaplarim
fields = ('tc_no', 'name', 'surname', 'phone_number',
'gender')
Here is html file;
<form method="post" class="form-horizontal" novalidate>
{% csrf_token %}
<div class="form-group">
<label for="id_tc_no">TC No:</label>
{{ form.tc_no }}
</div>
<div class="form-group">
<label for="id_name">Ad:</label>
{{ form.name }}
</div>
<div class="form-group">
<label for="id_surname">Soyad:</label>
{{ form.surname }}
</div>
<div class="form-group">
<label for="id_phone">Cep Telefonu:</label>
{{ form.phone_number }}
</div>
<div class="form-group">
<label for="id_gender">Cinsiyet:</label>
{{ form.gender }}
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Kaydet">
</div>
</form>
You need to initialize the form:
def home(request):
form = HesapForm(request.POST or None)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = HesapForm(initial={'your_field': 'your_value'})
return render(request, 'home.html', {'form': form})
Dynamic initial values you can refer about the same here.
You can also initialize it with object as well.

Passing context on an html with both POST and GET options

I have a html page with various submit buttons:
<h3>Add Address</h3>
<form method="post">
{% csrf_token %}
...
<input type="submit" value="Add" name="_add_add">
</form>
<h3> Update values </h3>
<form method="post">
{% csrf_token %}
...
<input type="submit" value="Add" name="_update">
</form>
<h3>Address</h3>
<form method="get">
...display...
My view.py is:
def property(request):
if request.method == 'POST':
if '_update' in request.POST:
...update values...
elif '_add_add' in request.POST:
...add addres....
Context = {"name_for_template":"value"}
else:
... graph default values...
Context = {"name_for_template":"value"}
return render(request, 'address.html', context)
When there isn't a POST and simply a GET (like being redirected to the page), I get an CSRF error in the context (and it asked me to use request_context). Is it possible (and how) to automatically send a default context for the GET, and send a different context for POST without incurring the CSRF error?
you can try this edit code
def property(request):
context = {}
if request.method == 'POST':
if '_update' in request.POST:
...update values...
elif '_add_add' in request.POST:
...add addres....
context["name_for_template"]= "value"
else:
... graph default values...
context["name_for_template"]= "value"
return render(request, 'address.html', context)
if it doesn't work, share your code