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'
Related
I have a JavaScript fetch to call a URL to pass data into my Django view to update a value for the user.
Error in views.py:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python310\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\rossw\Documents\Projects\Scry\apps\administration\views.py", line 47, in administration_users_page
switchData = json.load(request)['switch']
File "C:\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Error in browser:
0
PUT http://127.0.0.1:8000/administration/users/JM/ 500 (Internal Server Error)
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
JavaScript:
const changeAdminUserAction = (id,data) => {
console.log(data)
fetch(`/administration/users/${id}/`,{
method: 'PUT',
body: JSON.stringify({type: "adminUser", switch: data}),
headers: {'X-CSRFToken' : csrfToken, 'Content-Type': 'application/json'},
})
.then((response) => response.json())
.then((result) => {location.reload()})
.catch((err) => {console.log(err)})
}
views.py:
if request.method == 'PUT':
user = CustomUser.objects.get(username=kwargs.get('username'))
switchType = json.load(request)['type']
switchData = json.load(request)['switch']
print(switchType, switchData)
if switchType == 'adminUser':
user.admin_user = switchData
elif switchType == 'admindata':
user.admin_data = switchData
elif switchType == 'Status':
if user.status == COMMON.USER_ACTIVE:
user.status = COMMON.USER_SUSPENDED
else:
user.status = COMMON.USER_ACTIVE
user.failed_logins = 0
user.save()
return JsonResponse({})
This is throwing an error at switchData = json.load(request)['switch']. I don't know why it is throwing the error there as the previous line switchType = json.load(request)['type'] works as expected and returns the value that was passed to it.
data is a integer - either 1 or 0. I have tried make this value a string but it throws the same error.
I cannot explain why this happens, but its clearly related to the form how you are reading your data. It will also break at switchType = json.load(request)['type'] if you invert the lines (Seems to break while reading the second argument).
Data comes in as bytes, you can decode them into string (source) and parse into JSON, this method worked well in my testing:
if request.method == 'PUT':
decoded_bytes = request.body.decode("utf-8")
data = json.loads(decoded_bytes)
switchType = data['type']
switchData = data['switch']
print(switchType, switchData)
...
return JsonResponse({})
Shouldn't json.load(request)['switch'] be json.load(request.body)['switch']?
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}')"
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)
im very new to Javascript, Django & web development in general. Im following a cs50 web dev course by harvard and I have to design a front-end for an email client that makes API calls to send and receive emails.
Ill get mail, send mail, and update emails by using an API that is written specifically for us.
I need to send a GET request to /emails/ where is either inbox, sent, or archive, and it will return back (in JSON form) a list of all emails in that mailbox, in reverse chronological order.
How to fetch, as instructed by the course:
fetch('/emails/sent')
.then(response => response.json())
.then(emails => {
// Print emails
console.log(emails);
// ... do something else with emails ...
});
I put this exact code in my .js file and it gives me these two errors:
GET http://127.0.0.1:8000/emails/sent 500 (Internal Server Error)
load_mailbox # inbox.js:85
(anonymous) # inbox.js:24
127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in
JSON at position 0
Promise.then (async)
load_mailbox # inbox.js:87
(anonymous) # inbox.js:6
What shows at the cmd:
Is the issue at the timestamp of the model in django? I dont understand why.
Internal Server Error: /emails/sent
Traceback (most recent call last):
File "C:\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\Python38\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\AG\Desktop\cs50\mail\mail\views.py", line 96, in mailbox
return JsonResponse([email.serialize() for email in emails], safe=False)
File "C:\Users\AG\Desktop\cs50\mail\mail\views.py", line 96, in <listcomp>
return JsonResponse([email.serialize() for email in emails], safe=False)
File "C:\Users\AG\Desktop\cs50\mail\mail\models.py", line 26, in serialize
"timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"),
ValueError: Invalid format string
Code given by the course:
models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class Email(models.Model):
user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails")
sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent")
recipients = models.ManyToManyField("User", related_name="emails_received")
subject = models.CharField(max_length=255)
body = models.TextField(blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
read = models.BooleanField(default=False)
archived = models.BooleanField(default=False)
def serialize(self):
return {
"id": self.id,
"sender": self.sender.email,
"recipients": [user.email for user in self.recipients.all()],
"subject": self.subject,
"body": self.body,
"timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"),
"read": self.read,
"archived": self.archived
}
views.py, this function i believe it returns the emails from my request:
#login_required
def mailbox(request, mailbox):
# Filter emails returned based on mailbox
if mailbox == "inbox":
emails = Email.objects.filter(
user=request.user, recipients=request.user, archived=False
)
elif mailbox == "sent":
emails = Email.objects.filter(
user=request.user, sender=request.user
)
elif mailbox == "archive":
emails = Email.objects.filter(
user=request.user, recipients=request.user, archived=True
)
else:
return JsonResponse({"error": "Invalid mailbox."}, status=400)
# Return emails in reverse chronologial order
emails = emails.order_by("-timestamp").all()
return JsonResponse([email.serialize() for email in emails], safe=False)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
# API Routes
path("emails", views.compose, name="compose"),
path("emails/<int:email_id>", views.email, name="email"),
path("emails/<str:mailbox>", views.mailbox, name="mailbox"),
]
My.js code where i use fetch:
document.addEventListener('DOMContentLoaded', function () {
// Use buttons to toggle between views
document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox'));
document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent'));
document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive'));
document.querySelector('#compose').addEventListener('click', compose_email);
//code..
});
function compose_email() {
//code..
}
function load_mailbox(mailbox) {
// Show the mailbox and hide other views
document.querySelector('#emails-view').style.display = 'block';
document.querySelector('#compose-view').style.display = 'none';
// Show the mailbox name
document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
//problem:
//i will change the 'sent' string in the future
fetch('/emails/sent')
.then(response => response.json())
.then(emails => {
console.log(emails);
});
}
self.timestamp.strftime("%b %-d %Y, %-I:%M %p")
You are using Python 3, but the code you were given was written for Python 2 (or by someone who didn't know all the difference with Python 3 so you might expect other hurdles down the road). They are used for non zero-padded versions of d and I.
In Python 3, -d and -I do not make sense to the parsing engine, and I don't think there are non zero-padded versions.
You can safely remove the -.
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!