For example, here is some lines of code in my JS code embedded in the HTML file:
document.getElementById("enter").onclick = e => {
e.preventDefault();
var field1 = document.getElementById("field1").value;
var field2 = document.getElementById("field2").value;
var localStorageField = localStorage.getItem("field3");
window.location.href = "{{ url_for("content", ???) }}"
\\ or something else? I think this line would most likely not work, because the url_for is filled in when the page is loaded, rather than when it is called.
}
How do I make the page get redirected to the content() function, where it receives field1, field2 and localStorageField as arguments?
Edit: When I used Tobin's answer, an error occurs:
Traceback (most recent call last):
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask_socketio/__init__.py", line 46, in __call__
start_response)
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/engineio/middleware.py", line 74, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/scythia/Desktop/Flask_LocalStorage/venv/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
TypeError: content() missing 3 required positional arguments: 'field1', 'field2' and 'local'
flask function:
app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY")
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT'] = False
jsg = JSGlue(app)
#app.route("/")
def content(field1,field2,local):
return render_template("index.html", field1 = field1, field2 = field2, local = local)
I suggest you use Flask-JSGlue: it allows you to properly connect your Flask application to the front end.
INSTALLATION:
$ pip install Flask-JSGlue
USAGE:
Back-end:
from flask import Flask
from flask_jsglue import JSGlue
app = Flask(__name__)
jsglue = JSGlue(app)
Front-end:
In <head>
{{ JSGlue.include() }}
In your JS code:
document.getElementById("enter").onclick = e => {
e.preventDefault();
var field1 = document.getElementById("field1").value;
var field2 = document.getElementById("field2").value;
var localStorageField = localStorage.getItem("field3");
location.href = Flask.url_for("content", {param1: field1, param2: field2, param3: localStorageField});
}
FLASK ROUTE:
from flask import request
#app.route('/', methods=['GET', 'POST'])
def content():
field1 = request.args.get('param1')
field2 = request.args.get('param2')
local = request.args.get('param3')
return render_template("index.html", field1=field1, field2=field2, local=local)
Related
I want to create web app using STT model by python flask.
when user record the voice and send it server, trans it to text on web.
there is my javascript part:
<html>
<head>
<title>STT</title>
</head>
<div style="text-align: center;">
<h2>STT</h2>
<p>
<button type="button" id="record">record</button>
<button type="button" id="stopRecord" disabled>stop</button>
<input type="button" id="sendRecord" value="trans to text">
</p>
<p>
<audio id=recordedAudio></audio>
</p>
</div>
</html>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
let recordBlob;
navigator.mediaDevices.getUserMedia({audio:true})
.then(stream => {handlerFunction(stream)})
function handlerFunction(stream) {
rec = new MediaRecorder(stream);
rec.ondataavailable = e => {
audioChunks.push(e.data);
if (rec.state == "inactive") {
recordBlob = new Blob(audioChunks, {type:'audio/wav; codecs=MS_PCM'});
recordedAudio.src = URL.createObjectURL(blob);
recordedAudio.controls=true;
recordedAudio.autoplay=true;
}
}
}
record.onclick = e => {
record.disabled = true;
record.style.backgroundColor = "blue"
stopRecord.disabled=false;
audioChunks = [];
rec.start();
}
stopRecord.onclick = e => {
record.disabled = false;
stop.disabled=true;
record.style.backgroundColor = "red"
rec.stop();
}
sendRecord.onclick = e => {
let formData = new FormData();
formData.append('data', recordBlob);
console.log('blob', recordBlob);
$.ajax({
type: 'POST',
url: '/result',
data: formData,
contentType: false,
processData: false,
success: function(result) {
console.log('success', result);
$("#chatbox").append(`<p class ="userText"><audio style="background-color:white;" controls> <source src="${Url}" type="audio/wav"></audio></p>`);
$("#chatbox").append(`<p class ="botText"><span>${result.emotion}</span></p>`);
$("#textInput").val("")
},
error: function(result) {
alert('sorry an error occured');
}
});
}
</script>
and there is flask part:
from flask import Flask, render_template, request
import requests, json
import soundfile
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
UPLOAD_FOLDER = "./"
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
#app.route('/')
def index():
return render_template('index.html')
#app.route('/result', methods=['POST'])
def result():
url = "https://kakaoi-newtone-openapi.kakao.com/v1/recognize"
key = 'REST API KEY'
headers = {
"Content-Type": "application/octet-stream",
"Transfer-Encoding":"chunked",
"Authorization": "KakaoAK " + key,
}
blobData = request.files['data']
filename = secure_filename(blobData.filename)
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
blobData.save(filepath)
app.logger.info('blob data : ', blobData)
data, samplerate = soundfile.read(blobData)
soundfile.write('new.wav', data, samplerate, subtype='PCM_16')
with open("new.wav", 'rb') as fp:
audio = fp.read()
res = requests.post(url, headers=headers, data=audio)
return res.text
if __name__=='__main__':
app.debug=True
app.run('0.0.0.0', port=5001)
it comes out error
[2022-02-25 19:27:51,895] ERROR in app: Exception on /result [POST]
Traceback (most recent call last):
File "C:\users\ljh\appdata\local\programs\python\python39\lib\site-packages\flask\app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "C:\users\ljh\appdata\local\programs\python\python39\lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\users\ljh\appdata\local\programs\python\python39\lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\users\ljh\appdata\local\programs\python\python39\lib\site-packages\flask\app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\LJH\Documents\코드스테이츠\개인프로젝트\webapp\flaskapp2\app.py", line 31, in result
data, samplerate = soundfile.read(blobData)
File "C:\users\ljh\appdata\local\programs\python\python39\lib\site-packages\soundfile.py", line 372, in read
with SoundFile(file, 'r', samplerate, channels,
File "C:\users\ljh\appdata\local\programs\python\python39\lib\site-packages\soundfile.py", line 740, in __init__
self._file = self._open(file, mode_int, closefd)
File "C:\users\ljh\appdata\local\programs\python\python39\lib\site-packages\soundfile.py", line 1264, in _open
_error_check(_snd.sf_error(file_ptr),
File "C:\users\ljh\appdata\local\programs\python\python39\lib\site-packages\soundfile.py", line 1455, in _error_check
raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
RuntimeError: Error opening <FileStorage: 'blob' ('audio/wav; codecs=ms_pcm')>: File contains data in an unknown format.
127.0.0.1 - - [25/Feb/2022 19:27:51] "POST /result HTTP/1.1" 500 -
I don't know why blob didn't convert to wav...how can I fix it?
probably there are many no necessary parts on my javascript code.. I don't know about javascript. I'm sorry for that.
You write the data in a file, the position within the file moves to the end of it. If you then re-read the file using soundfile, you must first jump back to the beginning of the file.
import io
#app.route('/result', methods=['POST'])
def result():
if 'data' in request.files:
file = request.files['data']
# Write the data to a file.
filename = secure_filename(file.filename)
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(filepath)
# Jump back to the beginning of the file.
file.seek(0)
# Read the audio data again.
data, samplerate = soundfile.read(file)
with io.BytesIO() as fio:
soundfile.write(
fio,
data,
samplerate=samplerate,
subtype='PCM_16',
format='wav'
)
data = fio.getvalue()
# ...
return '', 400
Here is part of my python code using Flask:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
base_city = db.Column(db.String(120), nullable=False)
about_me = db.Column(db.String(1000), nullable=False, default='comedy!')
mic_submit = db.relationship('Mic', backref='initiator', lazy=True)
mic_checkin = db.relationship('Checkins', backref='signee', lazy=True)
def __init__(self, username, email, password, base_city, about_me, mic_submit, mic_checkin):
self.username = username
self.email = email
self.password = password
self.base_city = base_city
self.about_me = about_me
self.mic_submit = mic_submit
self.mic_checkin=mic_checkin
def __repr__(self):
return f"User('{self.username}','{self.email}', '{self.password}', '{self.base_city}', '{self.about_me}', '{self.mic_submit}','{self.mic_checkin}')"
class RegisterSchema(ma.Schema):
class Meta:
fields = ('id', 'username', 'email', 'password', 'base_city', 'about_me')
register_schema = RegisterSchema()
registers_schema = RegisterSchema(many=True)
the mic_submit and mic_checkin are there because i want the id to be a foreign key in a couple other tables
here is the route in question:
#app.route("/register", methods=['POST'])
def register():
username = request.json['username']
email = request.json['email']
password = request.json['password']
base_city = request.json['base_city']
about_me = request.json['about_me']
hashed_password = bcrypt.generate_password_hash(password)
user = User(username=username, email=email, password=hashed_password, base_city=base_city, about_me=about_me)
db.session.add(user)
db.session.commit()
My problem is when someone registers on the website I want them to just submit the username, email, password, base city, and about_me but the error on the backend is:
Traceback (most recent call last):
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/pm/ionic_apps/pobblebonk/venv/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/pm/ionic_apps/pobblebonk/backend/app.py", line 138, in register
user = User(username=username, email=email, password=hashed_password, base_city=base_city, about_me=about_me)
TypeError: __init__() missing 2 required positional arguments: 'mic_submit' and 'mic_checkin'
But I'm not going to ask them to submit mic_submit and mic_checkin because those columns are just for me to make sure that the table has a relationship with the other two tables. What am I supposed to do?
Here is the javascript APIService file for the front end:
export default class APIService {
static RegisterUser(username, email, password, base_city, about_me) {
console.log('i am here')
return fetch(`http://localhost:5000/register`, {
'method':'POST',
mode: 'cors',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify(username, email, password)
})
.then(resp => window.location.href = "login")
.catch(error => console.log(error, "Not In the APIService"))
}
You don't have to define the init method. Flask-SQLAlchemy generates it for you. This is the User class for your needs:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
base_city = db.Column(db.String(120), nullable=False)
about_me = db.Column(db.String(1000), nullable=False, default='comedy!')
mic_submit = db.relationship('Mic', backref='initiator', lazy=True)
mic_checkin = db.relationship('Checkins', backref='signee', lazy=True)
def __repr__(self):
return f"User('{self.username}','{self.email}', '{self.password}', '{self.base_city}', '{self.about_me}', '{self.mic_submit}','{self.mic_checkin}')"
I'm trying to add data to the POS's order and send that data to the 'pos.order' model based on the site https://odoo-development.readthedocs.io/en/latest/dev/pos/load-data-to-pos.html. To make my case more generic I'm creating a new odoo model named 'custom.model', I'm creating a relation with the 'pos.config' to help me with the model domain in javascritp latter with the following code:
# -*- coding: utf-8 -*-
from odoo import models, fields
class custom_model(models.Model):
_name = 'custom.model'
name = fields.Char(string='name')
class myPosConfig(models.Model):
_inherit = 'pos.config'
custom_model_id = fields.Many2one('custom.model', string='My custom model')
Then I add the relation of my interest in the 'pos.order' model with the following python code:
# -*- coding: utf-8 -*-
from odoo import models, fields, api
class myPosOrder(models.Model):
_inherit = 'pos.order'
custom_model_id = fields.Many2one('custom.model', string='My model')
Then I add my custom model in the frontend with a javascript file with the following code:
odoo.define('kyohei_pos_computerized_billing.billing_dosage', function (require) {
"use strict";
var models = require('point_of_sale.models');
var _super_order_model = models.Order.prototype;
models.load_models([{
model: 'custom.model',
label: 'custom_model',
fields: ['name'],
// Domain to recover the custom.model record related to my pos.config
domain: function(self){ return [['id', '=', self.config.custom_model_id[0]]];},
loaded: function(self, dosage){self.dosage = dosage[0]},
}]);
});
Then I add the following code to the same javascript file, so the record is stored in the browser and when needed to send the data to the backend:
models.Order = models.Order.extend({
initialize: function(){
_super_order_model.initialize.apply(this,arguments);
if (this.custom_model){
this.custom_model = this.pos.custom_model;
}
},
export_as_JSON: function () {
var data = _super_order_model.export_as_JSON.apply(this, arguments);
data.custom_model = this.custom_model;
return data
},
init_from_JSON: function (json) {
this.custom_model = json.custom_model;
_super_order_model.init_from_JSON.call(this. json);
},
export_for_printing: function() {
var json = _super_order_model.export_for_printing.apply(this,arguments);
json.custom_model = this.custom_model;
return json;
},
});
and finally added the following method to the 'pos.order' model so it stores what the frontend sends:
#api.model
def _order_fields(self, ui_order):
fields = super(MyPosOrder, self)._order_fields(ui_order)
fields.update({
'custom_model': ui_order('custom_model.id')
})
return fields
But the field still isn't being filled with my custom_model's registry id, and I get the following error:
Odoo Server Error
Traceback (most recent call last):
File "/opt/odoo/odoo13/odoo/http.py", line 619, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/opt/odoo/odoo13/odoo/http.py", line 309, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
File "/opt/odoo/odoo13/odoo/tools/pycompat.py", line 14, in reraise
raise value
File "/opt/odoo/odoo13/odoo/http.py", line 664, in dispatch
result = self._call_function(**self.params)
File "/opt/odoo/odoo13/odoo/http.py", line 345, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/opt/odoo/odoo13/odoo/service/model.py", line 93, in wrapper
return f(dbname, *args, **kwargs)
File "/opt/odoo/odoo13/odoo/http.py", line 338, in checked_call
result = self.endpoint(*a, **kw)
File "/opt/odoo/odoo13/odoo/http.py", line 910, in __call__
return self.method(*args, **kw)
File "/opt/odoo/odoo13/odoo/http.py", line 510, in response_wrap
response = f(*args, **kw)
File "/opt/odoo/odoo13/addons/web/controllers/main.py", line 1320, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/opt/odoo/odoo13/addons/web/controllers/main.py", line 1312, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/opt/odoo/odoo13/odoo/api.py", line 383, in call_kw
result = _call_kw_model(method, model, args, kwargs)
File "/opt/odoo/odoo13/odoo/api.py", line 356, in _call_kw_model
result = method(recs, *args, **kwargs)
File "/opt/odoo/odoo13/addons/point_of_sale/models/pos_order.py", line 440, in create_from_ui
order_ids.append(self._process_order(order, draft, existing_order))
File "/opt/odoo/odoo13/addons/point_of_sale/models/pos_order.py", line 122, in _process_order
pos_order = self.create(self._order_fields(order))
File "/opt/odoo/odoo13/kyohei_addons/kyohei_pos_computerized_billing/models/pos_order.py", line 27, in _order_fields
'test_string': ui_order('dosage.id'),
TypeError: 'dict' object is not callable
This error due to of the argument mismatch on the method, just check on the odoo-13 this method _process_order
In your code, you were using the older version method and from the odoo13 version, it is changed.
You have to update the field in this method, where the data came from the export_as_JSON function.
#api.model
def _order_fields(self, ui_order):
pos_order = super(KyoheiComputerizedPosOrder, self)._order_fields(ui_order)
# Get the data from ui_order
return pos_order
Thanks
I want to thank #Dipen Shah, finally got the code working. The python file should look like the following:
# -*- coding: utf-8 -*-
from odoo import models, fields, api
class MyPosOrder(models.Model):
_inherit = 'pos.order'
test_string = fields.Char(string='test_string')
#api.model
def _order_fields(self, ui_order):
order_fields = super(MyPosOrder, self)._order_fields(ui_order)
order_fields['test_string'] = ui_order.get('test_string')
return order_fields
The file that could help to understand this issue is the pos_restaurant's pos_order.py
I am trying to send image files from React to my Django Rest Framework but Django Rest doesn't seem to be picking up my data.
It works fine when I am making a POST request directly from my Django REST Framework http://127.0.0.1:8001/api/paintings/photos but when I try to do it through react it throws a POST 500 error.
I am not sure if it has something to do with my content-type or it's something else.
This is my function in React
createPainting = (data) => {
console.log(data)
console.log(JSON.stringify(data))
const endpoint = "/api/paintings/photos"; //notice the endpoint is going to a relative request, (relative to where the final javascript built code will be)
const csrfToken = cookie.load("csrftoken");
if (csrfToken !== undefined) {
// this goes into the options argument in fetch(url, options)
let lookupOptions = {
method: "POST",
headers: {
"Content-Type": "multipart/form-data; boundary=63c5979328c44e2c869349443a94200e",
"Process-Data": "false",
"Accept": "multipart/form-data, application/json",
"X-CSRFToken": csrfToken
},
body: JSON.stringify(data),
credentials: "include"
};
fetch(endpoint, lookupOptions)
.then(response => {
return response.json();
})
this.clearForm()
.catch(error => {
console.log("error", error);
alert("An error occured, please try again later.");
});
}
};
The data that comes in looks like this:
{srcs: "yacht3.jpeg", title_id: "109"}
When I stringify it looks like this:
{"srcs":"yacht3.jpeg","title_id":"109"}
This is the full error message
Traceback (most recent call last):
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.NotNullViolation: null value in column "title_id" violates not-null constraint
DETAIL: Failing row contains (99, default.jpg, null, 1).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/rest_framework/generics.py", line 244, in post
return self.create(request, *args, **kwargs)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/rest_framework/mixins.py", line 21, in create
self.perform_create(serializer)
File "/home/hzren/dev/t_and_b_website/src/paintings/views.py", line 132, in perform_create
serializer.save(user=self.request.user)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 940, in create
instance = ModelClass.objects.create(**validated_data)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create
obj.save(force_insert=True, using=self.db)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/models/base.py", line 880, in _do_insert
using=using, raw=raw)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1285, in execute_sql
cursor.execute(sql, params)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: null value in column "title_id" violates not-null constraint
DETAIL: Failing row contains (99, default.jpg, null, 1).
It doesn't seem to be picking up my data inputs.
Here are the the related code in my paintings/views
class PaintingPhotosListCreateAPIView(generics.ListCreateAPIView):
queryset = PaintingPhoto.objects.all()
serializer_class = PaintingPhotoSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
pagination_class = PaintingPhotosPageNumberPagination
def perform_create(self, serializer):
serializer.save(user=self.request.user)
def get_queryset(self):
# filter the queryset based on the filters applied
queryList = PaintingPhoto.objects.all()
title = self.request.query_params.get('title', None)
src = self.request.query_params.get('src', None)
return queryList
class PaintingPhotosTitleListCreateAPIView(generics.ListCreateAPIView):
queryset = PaintingPhoto.objects.all()
serializer_class = PaintingPhotoSerializer
lookup_field = 'title_id'
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save(user=self.request.user)
def get_queryset(self):
title_id = self.kwargs['title_id']
return PaintingPhoto.objects.filter(title_id=title_id)
class PaintingPhotosSpecificDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
queryset = PaintingPhoto.objects.all()
serializer_class = PaintingPhotoSerializer
lookup_field = 'id'
permission_classes = [IsOwnerOrReadOnly]
Here is the related code in paintings/serializers.py
class PaintingPhotoSerializer(serializers.ModelSerializer):
title_name = serializers.CharField(source='title', read_only=True)
photo_title_url = serializers.HyperlinkedIdentityField(
view_name='paintings-api:photos-title-list',
read_only=True,
lookup_field='title_id'
)
photo_specific_url = serializers.HyperlinkedIdentityField(
view_name='paintings-api:photos-specific-detail',
read_only=True,
lookup_field='id'
)
owner = serializers.SerializerMethodField(read_only=True)
class Meta:
model = PaintingPhoto
fields =[
'title_id',
'src',
'title_name',
'photo_title_url',
'photo_specific_url',
'owner',
]
def get_owner(self, obj):
request = self.context['request']
if request.user.is_authenticated:
if obj.user == request.user:
return True
return False
Thanks so much in advance!
I followed this Tutorial
http://www.tangowithdjango.com/book17/chapters/ajax.html#add-a-like-button
but my like count is not incrementing after clicking it.
Here's my code
views.py
def like_post(request):
post_id = None
if request.method == 'GET':
post_id = request.GET['post.pk']
likes = 0
if post_id:
post = Post.objects.get(id=int(post_id))
if post:
likes = post.likes + 1
post.likes = likes
post.save()
return HttpResponse(likes)
urls.py
url(r'like_post/$', views.like_post, name='like_post'),
Models.py
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True,null=True)
likes = models.IntegerField(default=0)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
post_deatil.html
<strong id="like_count">{{ post.likes }}</strong> people like this category
{% if user.is_authenticated %}
<button id="likes" data-post_id="{{post.id}}" class="btn btn-primary" type="button">
<span class="glyphicon glyphicon-thumbs-up"></span>
Like
</button>
{% endif %}
blog-ajax.js
$('#likes').click(function(){
var postid;
catid = $(this).attr("data-post_id");
$.get('/blog/like_post/', {post_id: postid}, function(data){
$('#like_count').html(data);
$('#likes').hide();
});
});
Console message
Internal Server Error: /blog/like_post/
Traceback (most recent call last):
File "/home/bharat/.local/lib/python3.5/site-packages/django/utils/datastructures.py", line 83, in __getitem__
list_ = super(MultiValueDict, self).__getitem__(key)
KeyError: 'post.pk'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/bharat/.local/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/bharat/Desktop/DiggingIntoDjango-TreasuregramSampleApp-master/my-first-blog-master/blog/views.py", line 103, in like_post
post_id = request.GET['post.pk']
File "/home/bharat/.local/lib/python3.5/site-packages/django/utils/datastructures.py", line 85, in __getitem__
raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'post.pk'"
Internal Server Error: /blog/like_post/
Traceback (most recent call last):
File "/home/bharat/.local/lib/python3.5/site-packages/django/utils/datastructures.py", line 83, in __getitem__
list_ = super(MultiValueDict, self).__getitem__(key)
KeyError: 'post.pk'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/bharat/.local/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/bharat/Desktop/DiggingIntoDjango-TreasuregramSampleApp-master/my-first-blog-master/blog/views.py", line 103, in like_post
post_id = request.GET['post.pk']
File "/home/bharat/.local/lib/python3.5/site-packages/django/utils/datastructures.py", line 85, in __getitem__
raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'post.pk'"
[19/Apr/2017 13:03:36] "GET /blog/like_post/ HTTP/1.1" 500 16637
[19/Apr/2017 13:03:36] "GET /blog/like_post/ HTTP/1.1" 500 16637
This is how i get, but after clicking on like nothing happens
Thank You
In views.py use:
post_id = None
if request.method == 'GET':
post_id = request.GET['post_id']
instead of:
post_id = None
if request.method == 'GET':
post_id = request.GET['post.pk']
This is because in your blog-ajax.js you make a GET-call with parameter 'post_id' and not 'post.pk'