I have my requestaccess view below, which will write to my database if I remove the if request.method == 'POST', but if i keep it in. The request is never written. I'm trying to understand why the POST isn't occurring and how to make it happen?
def requestaccess(request):
owner = User.objects.get (formattedusername=request.user.formattedusername)
reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc')
reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True)
checkedlist = request.GET.getlist('report_id')
reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)
coid = User.objects.filter(coid = request.user.coid).filter(formattedusername=request.user.formattedusername)
facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid , active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
selectedaccesslevel = '7'
if request.method == 'POST':
selectedaccesslevel = request.POST.get('accesslevelid')
print(selectedaccesslevel)
selectedphi = '0'
if request.method == 'POST':
selectedphi = request.POST.get('phi')
print(selectedphi)
if request.method == 'POST':
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi, access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00')
requestsave.save()
args = {'retreivecheckbox': reportlist, 'cfo7':facilitycfo, 'cfo5':divisioncfo, 'checkedlist':checkedlist }
return render(request,'accounts/requestaccess.html', args)
# return render(request, 'accounts/requestaccess.html', args)
My request.method == 'POST' statements never return the correct value only the hard coded one for a test.
My template requestaccess.html can be found below. I can see the POST request for the ajax function being updated as i change the select options and when I click on the button.
{% extends 'base.html' %}
{% block head %}
<title> Access Request Form </title>
{% endblock %}
{% block body %}
<div class="container">
<div class="row">
<div class="col">
<h2>{{ user.username }}</h2></br>
<ul>
<li>Employee First Name: {{ user.first_name }}</li>
<li>Employee Last Name: {{ user.last_name }}</li>
<li>Coid: {{ user.coid }}</li>
<li>Facility: {{ user.facility }}</li>
<li>Title: {{user.title}}</li>
</ul>
</div>
<div class="col">
<form action = "{% url 'requestaccess' %}" form method = "POST">
{% csrf_token %}
<h2>Applications:</h3></br>
{% for app in retreivecheckbox %}
<li><input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }}
</li>
{% endfor %}
</div>
</div>
<div class="row">
<div class="col">
<label for="accesslevel"><h3>Access Level</h3></label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
<option value=""> Please select your access level </option>
<option value="7"> Facility </option>
<option value="5"> Division </option>
<option value = "3"> Corporate </option>
<option value = "6"> Market </option>
<option value = "4"> Group </option>
</select>
</div>
<div class="col">
<label for="phi"><h3>PHI</h3></label>
<select class="form-control my_select" id="phi" title = "phi" >
<option value = ""> Please select if you need access to PHI data </option>
<option value = "0"> No </option>
<option value = "1"> Yes </option>
</select>
</div>
</div>
<div class="row">
<div class="container">
<div class="row">
<div class="col">
</br> </br>
<button href="{% url 'submitted' %}" class="btn btn-primary my_select" type = "submit"> Submit </button>
<script>
$(document).ready(function () {
$('.my_select').on('change', function () {
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid ').val();
$.ajax({ url: "{% url 'requestaccess' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
;
},
});
});
});
</script>
</div>
</form>
{% endblock %}
Below is the console which shows the POST:
[07/Dec/2017 13:21:14] "GET /account/requestaccess/?report_id=84&report_id=87&report_id=88 HTTP/1.
3
[07/Dec/2017 13:21:22] "POST /account/requestaccess/ HTTP/1.1" 200 3928
3
1
After I click the submit button it gives me the following:
[07/Dec/2017 13:33:59] "POST /account/requestaccess/ HTTP/1.1" 200 3776
None
None
Edit:
Changing the javascript to on('click' instead of on('change' produces the same value of None.
checkedlist = request.GET.getlist('report_id') is the culprit. You're populating that from the GET request, and when you POST, those aren't carried over in any way.
As a result, checkedlist is None and the save statement never fires.
Related
In http://127.0.0.1:5000/:
If defaults are "0", message in each field: "This field is required".
There are the message "csrf_token CSRF Token" above "compute0" and "compute1".
Only compute0 works.
click on compute0 shows the resulted.
click on compute1 showns nothing.
form and form1 have 3 inputs.
compute0 and compute1 call (math.sin(r))* t + u.
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import TextField, BooleanField, PasswordField, TextAreaField, validators
from compute import compute
from model import InputForm, InputForm1
app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisisasecret'
#app.route('/', methods=['GET', 'POST'])
def index():
form = InputForm(request.form)
form1 = InputForm1(request.form)
if form.validate_on_submit():
if request.method == 'POST':
r = form.r.data
t = form.t.data
u = form.u.data
s = compute(r,t,u)
else:
s = None
return render_template("view.html", form=form, form1=form1, s=s)
if form1.validate_on_submit():
if request.method == 'POST':
r1 = form1.r1.data
t1 = form1.t1.data
u1 = form1.u1.data
s1 = compute(r1,t1,u1)
else:
s1 = None
return render_template("view.html", form=form, form1=form1, s1=s1)
return render_template("view.html",form=form, form1=form1)
if __name__ == '__main__':
app.run(debug=True)
from flask_wtf import FlaskForm
from wtforms import validators, StringField, PasswordField,FloatField, validators
class InputForm(FlaskForm):
r = FloatField(label='var_r',default=0,validators=[validators.DataRequired()])
t = FloatField(label='var_t',default=0,validators=[validators.DataRequired()])
u = FloatField(label='var_u',default=0,validators=[validators.DataRequired()])
class InputForm1(FlaskForm):
r1 = FloatField(label='var_r1',default=0,validators=[validators.DataRequired()])
t1 = FloatField(label='var_t1',default=0,validators=[validators.DataRequired()])
u1 = FloatField(label='var_u1',default=0,validators=[validators.DataRequired()])
import math
def compute(r,t,u):
return (math.sin(r))* t + u
<form method="post" action="">
{{ form.csrf_token }}
{% for field in form %}
<dt>{{ field.name }}
<dd>{{ field|safe }} {{field.label }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}</ul>
{% endif %}</dd>
{% endfor %}
<p><input type=submit value=Compute0></form></p>
<h5> Valor: </h5>
<p>
{% if s != None %}
{{ s }}
{% endif %}
</p>
<form method="post" action="">
{{ form.csrf_token }}
{% for field in form1 %}
<dt>{{ field.name }}
<dd>{{ field|safe }} {{field.label }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}</ul>
{% endif %}</dd>
{% endfor %}
<p><input type=submit value=Compute1></form></p>
<h5> Valor: </h5>
<p>
{% if s1 != None %}
{{ s1 }}
{% endif %}
</p>
if i understand your description, you have 2 independent forms on the same page that both send POST requests to the same view function to process.
you want to update the placeholder below of each form depending on which form is already submitted, here i think you need to perform an ajax call since (based on your code above) there's no way to keep or persist the data of the other form (database for e.g)
so to do:
update the code of the Form InputForm
since the 2 forms have the same fields you need just one for this use case and then adapt and extend the logic for other forms with different set of fields
from flask_wtf import FlaskForm
from wtforms.fields import FloatField, SubmitField
from wtforms.validators import DataRequired
class InputForm(FlaskForm):
r = FloatField('r', validators=[DataRequired()])
t = FloatField('t', validators=[DataRequired()])
u = FloatField('u', validators=[DataRequired()])
submit = SubmitField('Submit')
update the template
<!-- the first form -->
<form class="form" id="form-1" method="POST" novalidate>
{{ form_1.csrf_token }}
<div class="row">
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_1.r.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_1.r(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_1.t.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_1.t(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_1.u.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_1.u(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
</div>
<div class="form-group row d-flex justify-content-between border bg-light p-3">
{{ form_1.submit(class="btn btn-sm btn-primary rounded-0 shadow-none") }}
<span class="placeholder">sin(r) * t + u = 0.00</span>
</div>
</form>
<!-- the second form -->
<form class="form" id="form-2" method="POST" novalidate>
{{ form_2.csrf_token }}
<div class="row">
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_2.r.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_2.r(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_2.t.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_2.t(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<div class="col-sm-3">
{{ form_2.u.label(class="col-form-label") }} <span class="text-danger">*</span>
</div>
<div class="col-sm-9">
{{ form_2.u(class="form-control rounded-0 shadow-none", **{"placeholder":"0"}) }}
<div class="invalid-feedback"></div>
</div>
</div>
</div>
</div>
<div class="form-group row d-flex justify-content-between border bg-light p-3">
{{ form_2.submit(class="btn btn-sm btn-primary rounded-0 shadow-none") }}
<span class="placeholder">sin(r) * t + u = 0.00</span>
</div>
</form>
in your view function (here i just i isolated the logic in Blueprint #bp):
from flask import Blueprint, render_template, request, jsonify
from .forms import InputForm
from .utils import compute
bp = Blueprint(
'home',
__name__,
static_folder='static',
static_url_path='/home/static',
template_folder='templates',
# url_prefix=None,
# subdomain=None,
# url_defaults=None,
# root_path=None,
# cli_group=<object object>
)
#bp.route('/', methods=['GET', 'POST'])
def index():
form_1 = InputForm()
form_2 = InputForm()
if request.method == 'POST':
# we handle the "POST" request of the submitted "form_1"
if form_1.validate_on_submit():
r = form_1.r.data
t = form_1.t.data
u = form_1.u.data
s = compute(r,t,u)
return jsonify(s=s if s else 0, errors={})
else:
return jsonify(s=0, errors=form_1.errors)
# we handle the "POST" request of the submitted "form_2"
if form_2.validate_on_submit():
r = form_2.r.data
t = form_2.t.data
u = form_2.u.data
s = compute(r,t,u)
return jsonify(s=s if s else 0, errors={})
else:
return jsonify(errors=form_2.errors)
return render_template("home/index.html", form_1=form_1, form_2=form_2)
the ajax part:
i suggest you my answer on how to take advantage of jinja2 template inheritance to insert locally a js (the same with css) blocks for particular page.
base on, i assume your are using jquery and since we want jinja2 to render this javascript line url: "{{ url_for('home.index') }}", so in your template add this code
$(document).ready(function() {
"use strict";
$('.form').submit(function(e) {
e.preventDefault();
// get the id of the form currently submitted
let id = $(this).attr('id');
$.ajax({
url: "{{ url_for('home.index') }}",
type: 'POST',
cache: false,
dataType: 'json',
data: $('#' + id).serialize(), // serialize the form
success: function(data) {
// console.log(data);
// sanitize the form before processing the submitted fields
if( ! data.errors.hasOwnProperty('r')){
$('#' + id + ' input[name=r]').removeClass('is-invalid').next(".invalid-feedback").text('');
}
if( ! data.errors.hasOwnProperty('t')){
$('#' + id + ' input[name=t]').removeClass('is-invalid').next(".invalid-feedback").text('');
}
if( ! data.errors.hasOwnProperty('u')){
$('#' + id + ' input[name=u]').removeClass('is-invalid').next(".invalid-feedback").text('');
}
// #see https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
if( ! jQuery.isEmptyObject(data.errors)) { // Errors (data.errors = {})
console.log('Errors');
if(data.errors.hasOwnProperty('r')){
$('#' + id + ' input[name=r]').addClass('is-invalid').next(".invalid-feedback").text(data.errors['r']);
}
if(data.errors.hasOwnProperty('t')){
$('#' + id + ' input[name=t]').addClass('is-invalid').next(".invalid-feedback").text(data.errors['t']);
}
if(data.errors.hasOwnProperty('u')){
$('#' + id + ' input[name=u]').addClass('is-invalid').next(".invalid-feedback").text(data.errors['u']);
}
// update placeholder with the returned value
$('#' + id + ' .placeholder').html('sin(r) * t + u = ' + data.s);
} else { // Passed
console.log('Passed');
// get the submitted fields
let r = $('#' + id + ' input[name=r]').val();
let t = $('#' + id + ' input[name=t]').val();
let u = $('#' + id + ' input[name=u]').val();
// update placeholder with the returned value
$('#' + id + ' .placeholder').html('sin(' + r + ') * ' + t + ' + ' + u + ' = ' + data.s);
// reset fields
$('#' + id + ' input[name=r]').val('');
$('#' + id + ' input[name=t]').val('');
$('#' + id + ' input[name=u]').val('');
}
}
});
});
});
and finally this a
hope this solves your issue.
i have a form that allow user to insert new record to the database using django.
the form is working as it should.
and i have dropdown list country that is pre-populated with data from the database and it works as it should.
now i want to enter the dropdown list into the form to allow the user to select from it.
how can i do it ?
models.py
class Country(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return str(self.name)
class Person(models.Model):
boolChoice = (
("M","Male"),("F","Female")
)
name = models.CharField(max_length=50)
date = models.DateField()
description = models.TextField()
gender = models.CharField(max_length = 1,choices=boolChoice)
country = models.ForeignKey("Country", on_delete = models.CASCADE)
addPerson.html
{% extends 'base.html' %}
{% block content %}
<div class="hero__content">
<form method="POST" class="form-style-9">{% csrf_token %}
{{ form.as_p }}
<ul>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<li>
{# <input type="number" name="field1" class="field-style field-split align-right" placeholder="اﻟﺴﻨﺔ" id="year"/> #}
{# <input type="date" name="field2" class="field-style field-split align-left" placeholder="اﻟﺘﺎﺭﻳﺦ" id="date" /> #}
<h2>Add Member</h2>
</li>
<li>
<input type="text" name="name" class="field-style field-split align-right" placeholder= "enter ur name " id="name"/>
</li>
<li>
<input type="date" name="date" class="field-style field-full align-none" placeholder= " your birthdate" id="birthdate" />
</li>
<li>
<input type="radio" name="gender" value="M"> Male<br>
<input type="radio" name="gender" value="F"> Female<br>
</li>
<li>
<textarea name="description" class="field-style" placeholder= "introduce yourself " id="description"></textarea>
</li>
<li>
<input type="submit" class="field-style field-full align-none" id="save" value="ADD" />
<script type="text/javascript">
$(function(){
$('#save').on('click',function(e){
e.preventDefault()
name=$('#name').val()
birthdate=$('#birthdate').val()
description=$('#description').val()
radioValue = $("input[name = 'gender']:checked").val()
if (radioValue){
alert("radioValue =", radioValue)
}
$.ajax({
url:'/addperson/',
method:'POST',
data: {
na:name,
bi:birthdate,
de:description,
ra:radioValue,
},
headers:{
'X-CSRFToken':'{{csrf_token}}'
}
}).done(function(msg) {
document.location = "/addPerson.html"
alert('ﻟﻘﺪ ﺗﻢّ ﺣﻔﻆ اﻟﻤﻌﻠﻮﻣﺎﺕ')
}).fail(function(err){
alert('ﻟﻢ ﻳﺘﻢ اﻟﺤﻔﻆ')
})
})
})
</script>
</li>
</ul>
</form>
</div>
{% endblock %}
views.py
def addPerson(request):
print("request method = " , request.method)
countries = Country.objects.all()
print (countries)
if request.method == "POST":
name = request.POST['na']
birthdate = request.POST['bi']
description=request.POST['de']
gender=request.POST['ra']
person=Person.objects.create(
name=name,
date=birthdate,
description=description,
gender = gender,
)
print("name = ", name + "birthdate = " , birthdate + "dec = ", description + "gender = " , gender)
person.save()
return render(request,'./addPerson.html',{'countries': countries})
else:
print("this is a get METHOD")
I can see you are returning the list with Response, good. You need to use the method; render_to_response('template/path', {'countries': countries,}). Then you can access 'countries' in this template and use a template for loop to render the HTML
return render_to_response(templates/path.html', {'countries': countries })
<h1>All available countries</h1>
<ul>
{% for country in countries %}
<li>{{ country.name}}</li>
{% endfor %}
</ul>
I have a form that contains two select inputs one is for categories and the other for sub categories the form should work like this user should choose an option in the categories and based on that option the sub category options should be updated with new values. but for some reason the sub category options aren't updating
template dashboard.html
{% block body %}
<form>
{% csrf_token %}
<div class="row">
<div class="input-field col s6 offset-s3">
<select id="list">
<option value="" disabled selected>Choose your Category</option>
<option value="education">University/College</option>
<option value="hospital">Hospital</option>
<option value="business">Business Organizations</option>
</select>
<label>Categories</label>
</div>
<div class="input-field col s6 offset-s3">
<select>
<option value="" disabled selected>Choose your Category</option>
{% for d in data %}
<option value="">{{ d.username }}</option>
{% endfor %}
</select>
<label>Sub Categories</label>
</div>
</div>
</form>
{% endblock %}
{% block script %}
<script type="text/javascript">
$('#list').change(function() {
$.ajax({
type: 'POST',
url: '/dashboard/',
data: {
category: $('#list').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
}
});
});
</script>
{% endblock %}
view.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
def dashboard(request):
if not request.user.is_authenticated:
return redirect('index')
else:
if request.method == 'POST':
category = request.POST['category']
#Here i am using User table because category table is empty
data = User.objects.all()
print(data)
return render(request, 'usecases/dashboard.html', {'data': data})
else:
return render(request, 'usecases/dashboard.html')
This is your subcategories where I just add an id #sub_categories
<select id='sub_categories'>
<option value="" disabled selected>Choose your Category</option>
{% for d in data %}
<option value="">{{ d.username }}</option>
{% endfor %}
</select>
<label>Sub Categories</label>
JS
$.ajax({
type: 'POST',
url: '/dashboard/',
data: {
category: $('#list').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success:function(response){
$('#sub_categories').replaceWith($("#sub_categories",response))
}
});
I have the following HTML template in Django to POST a request when the user selects the select option. The console shows the correct value based on what the user selects. My problem is when I push the submit button my POST gets posted as None on the submitted view. How can I get it to post on button click, i've aliased the button as my_select.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action = "{% url 'submitted' %}" form method = "POST">
{% csrf_token %}
<h2>Applications:</h3></br>
{% for app in retreivecheckbox %}
<li><input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }}
</li>
{% endfor %}
</div>
</div>
<div class="row">
<div class="col">
<label for="accesslevel"><h3>Access Level</h3></label>
<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
<option value=""> Please select your access level </option>
<option value="7"> Facility </option>
<option value="5"> Division </option>
<option value = "3"> Corporate </option>
<option value = "6"> Market </option>
<option value = "4"> Group </option>
</select>
</div>
<div class="col">
<label for="phi"><h3>PHI</h3></label>
<select class="form-control my_select" id="phi" title = "phi" >
<option value = ""> Please select if you need access to PHI data </option>
<option value = "0"> No </option>
<option value = "1"> Yes </option>
</select>
</div>
</div>
<div class="row">
<div class="container">
<div class="row">
<div class="col">
</br> </br>
<button href="{% url 'submitted' %}" class="btn btn-primary my_select" type = "submit"> Submit </button>
<script>
$(document).ready(function () {
$('.my_select').on('click', function () {
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid ').val();
$.ajax({ url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
;
},
});
});
});
</script>
</div>
</form>
Change your button and javascript to this:
<button class="btn btn-primary my_select" type="submit">Submit</button>
<script>
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid').val();
$.ajax({
url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
// do something with result
},
});
});
});
</script>
this is what i would normally use if you use Jquery 3.2.1
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: "POST",
data: $(this).serialize()
}).done(function(xhr) {
// do something
});
});
also update your select elements to have
<select class="form-control my_select" id="phi" name="phi">
rather than
<select class="form-control my_select" id="phi" title = "phi" >
notice i have changed the "title" attr to "name"
I have some field created by Django form and there are some other data I want to post to other form using jQuery(Ajax).
Is there any way to post them to different tables with two different ways at the same time?
form.py
class MyForm(forms.ModelForm):
class Meta:
model = models.Planning
fields = ['title','description','open','owner','upload_time']
template
<form id="myform" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.management_form }}
<div id="select_country">
<p style="display: inline;">country</p>
<select id="city">
<option selected disabled hidden>please choose</option>
{% for x in areas %}
<option value="{{x.area_country}}">{{x.area_country}}</option>
{% endfor %}
</select>
<select id="areas" name="my_areas"></select>
<br>
<div class="my_detail">
</div>
<br>
</div>
<div id="content_loi" class="col-lg-4">
<div class="col-lg-12" id="list"></div>
<div class="col-lg-12"">
<label>title:{{form.title}}</label>
<p><b>description:</b>{{form.description}}</p>
<button type="submit" class="btn btn-default" style="margin:0 auto;">submit</button>
</div>
</div>
</form>
I want to store the chosen areas and foreign key to another table with ajax
view
def make_list(request):
template = get_template('index.html')
areas = models.Area.objects.values('area_country').distinct()
max_my_id = models.RoutePlanning.objects.all().aggregate(Max('my_id'))
my_id = int(max_my_id['my_id__max']) + 1
#city = request.POST.get('my_areas')
if request.method == 'POST':
form = forms.MyForm(request.POST,initial={'owner':username,'route_id':my_id,'route_upload_time':datetime.now()})
if form.is_valid():
form.save()
return HttpResponseRedirect('/make_player')
else:
loi_form = forms.MyForm(initial={'owner':username,'route_id':my_id,'route_upload_time':datetime.now()})
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)