I am making social network website where user can post and like the post. On one of my templates, image of heart (which represents if post is liked or not) is not loading because of incorrect path: this is the incorrect one: other_profile/static/network/nolike.png. It should be: static/network/nolike.png. other_profile is the name and path of my template. Same happens in case of other API fetch calls on my website. URL should not begin with other_profile. And this happens only on other_profile HTML page.
The code:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("profile", views.profile, name="profile"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("Post/<str:post_id>", views.likes, name="likes"),
path("follows/<str:user_id>", views.follows, name="follows"),
path("following", views.following, name="following"),
path("other_profile/<str:user_id>", views.other_profile, name="other_profile")
]
views.py snippet
import json
from urllib.request import Request
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.urls import reverse
from .forms import NewPostForm, likeForm, followForm
from .models import User, Post, Likes, Follows
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from datetime import datetime
def other_profile(request, user_id):
followform = followForm(request.POST or None)
if request.method == "POST":
try:
Follows.objects.filter(following__in=[user_id]).get(following=request.user).delete()
except Follows.DoesNotExist:
if followform.is_valid():
follows = followform.save(commit=False)
follows.user = User.objects.get(id=user_id)
follows.save()
follows.following.add(request.user)
posts = Post.objects.filter(user = user_id).order_by('-date')
return render(request, "network/otherprofile.html", {
"posts":posts, "followform":followform})
otherprofile.html
{% extends "network/layout.html" %}
{% block body %}
TODO
{% if user.is_authenticated %}
<form method="POST">{% csrf_token %}
{{ followform }}
<button id="follow">Follow</button>
</form>
<div id="posts">
{% for post in posts %}
{{ post.user.username }}
<div class="name" id = "{{ post.user.id }}"><div>{{ post.date }}</div>{{ post.post }}</div>
<div id ="heart"></div>
{% endfor %}
</div>
{% endif %}
<script>
document.querySelector("#follow").addEventListener('click', () => {
var requestfollow = new Request(
`follows/${document.querySelector(".name").id}`,
{
method: 'POST',
}
);
fetch(requestfollow).then((response) => response.json()).then((data) => {
if (data.user_id == post.user.id) {
document.querySelector("#follow").innerHTML="Unfollow"
}})})
</script>
{% endblock %}
js file
document.addEventListener('DOMContentLoaded', function() {
var heart = new Image();
heart.id = "main";
heart.style.animationPlayState = 'paused';
var allButtons = document.querySelector('#posts').childElementCount;
var content = document.querySelectorAll('.name');
var button = document.querySelectorAll('#heart');
var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
for (i = 0; i < allButtons / 2 - 1; i++) {
function listen(i) {
var requestPOST = new Request(
`/Post/${content[i].id}`,
{
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
mode: 'same-origin' // Do not send CSRF token to another domain.
}
);
var requestGET = new Request(
`/Post/${content[i].id}`,
{
method: 'GET',
}
);
var heart = new Image();
heart.style.animationPlayState = 'paused';
heart.id = "main";
fetch(requestGET).then((response) => response.json()).then((data) => {
console.log(data.like)
if (data.like == true) {
heart.src = "static/network/like.png"
}
else{
heart.src = "static/network/nolike.png"
}
button[i].appendChild(heart);
})
button[i].addEventListener('click', () =>
fetch(requestPOST).then((response) => {
if (response.ok) {
response.json().then((data) => {
console.log(data.like)
if (data.like == true) {
heart.src = "static/network/like.png"
}
else{
heart.src = "static/network/nolike.png"
}
button[i].appendChild(heart);
heart.style.animationPlayState = 'running';
})}
else {
api(i)
console.log("not ok")
}}))}listen(i)}})
I also have a js file in static files. If that is needed let me know.
Help would be greatly appreciated!
the django way of handling static files is to use the static tag
{% static 'network/nolike.png' %}
but please be aware to setup static stuff in settings.py
https://docs.djangoproject.com/en/4.0/howto/static-files/
heart.src = "/static/network/like.png"
with the slash "/" at the beginning. Or better:
heart.src = "{% static 'network/like.png' %}"
Related
I recode a Tutorial on Youtube.
Django, Python, HTML an Javascript.
Everthing works fine exept the window.location.reload() function.
I try some workarounds with
windows.reload(true),
window.href = window.href
location = self.location
and some more.
I have a hunch that the reload is executed before or during the code before the reload. But I do not know.
The goal is to send the data from the input to the database and only then refresh the page.
This ist the Code from the tutorial:
index.html (shortened)
<body>
<header>
<h1>Shoppinglist</h1>
<div id="input-field">
<label for="item-input">Was möchtest du einkaufen?</label>
<input type="text" name="item" id="item-input">
</div>
<button id="btn" onclick="addItem()">+</button>
</header>
<div id="item-table">
{% for row in all_items %}
<div class="list-item">
<input type="checkbox"> {{row.name}}
</div>
{% endfor %}
</div>
<script>
function addItem(){
let itemName = document.getElementById("item-input").value;
let formData = new FormData();
let token = '{{csrf_token}}';
formData.append('itemName', itemName);
formData.append('csrfmiddlewaretoken', token);
fetch('/mylist/', {
method: 'POST',
body: formData
});
window.location.reload();
};
</script>
</body>
</html>
views.py
from django.shortcuts import render
from .models import ShoppingItem
# Create your views here.
def mylist(request):
if request.method == 'POST':
print('Received date: ', request.POST['itemName'])
ShoppingItem.objects.create(name = request.POST['itemName'])
all_items = ShoppingItem.objects.filter(done = 0)
return render(request, 'index.html', {'all_items':all_items})
models.py
from django.db import models
from datetime import date
#Create your models here.
class ShoppingItem(models.Model):
creatDate = models.DateField (default=date.today)
name = models.CharField (max_length =200)
done = models.BooleanField(default=False)
def __str__(self):
return '(' + str(self.id) +') ' +self.name
Try this:
async function addItem() {
let itemName = document.getElementById("item-input").value;
let formData = new FormData();
let token = "{{csrf_token}}";
formData.append("itemName", itemName);
formData.append("csrfmiddlewaretoken", token);
await fetch("/mylist/", {
method: "POST",
body: formData,
});
window.location.reload();
}
detail.html
{% if request.user.is_authenticated %}
<form class="like-forms d-inline" data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }}">
{% csrf_token %}
<h4>
{% if request.user in review.like_users.all %}
<button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-heart-eyes"></button>
{% else %}
<button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-angry"></button>
{% endif %}
</h4>
</form>
{% endif %}
<!-js-->
<script>
const likeForms = document.querySelectorAll('.like-forms')
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value
likeForms.forEach((form) => {
form.addEventListener('submit', function (event) {
event.preventDefault()
const reviewId = event.target.dataset.reviewId
const bookId = event.target.dataset.bookId
axios({
method: 'post',
url: `/detail/${bookId}/like/${reviewId}/`,
headers: {'X-CSRFToken': csrfToken},
})
.then(response => {
const isLiked = response.data.isLiked
const likeBtn = document.querySelector(`#btn-like-${reviewId}`)
console.log(isLiked)
if (isLiked === true) {
likeBtn.classList.add('bi-emoji-heart-eyes')
likeBtn.classList.remove('bi-emoji-angry')
} else {
likeBtn.classList.add('bi-emoji-angry')
likeBtn.classList.remove('bi-emoji-heart-eyes')
}
})
.catch(error => {
console.log(error)
})
})
})
</script>
urls.py
path("detail/<int:book_pk>", views.detail, name="detail"),
path("detail/<int:book_pk>/like/<int:review_pk>", views.like, name="like"),
.....
views.py
def detail(request, book_pk):
reviews = Review.objects.order_by("-pk")
book = Book.objects.get(pk=book_pk)
context = {
"reviews": reviews,
"book": book,
}
return render(request, "review/detail.html", context)
def like(request, book_pk, review_pk):
review = Review.objects.get(pk=review_pk)
book = Book.objects.get(pk=book_pk)
if review.like_users.filter(pk=request.user.pk).exists():
review.like_users.remove(request.user)
is_liked = False
else:
review.like_users.add(request.user)
is_liked = True
data = {
"isLiked": is_liked,
}
return JsonResponse(data)
I got a 404 not found error while writing code for a "like" async function.
data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }} in the form
I seem to get pk values for books and book reviews, but I don't know what causes the 404 error.
Console error message : POST http://localhost:8000/detail/1/like/2/ 404 (Not Found)
I am running this on localhost (http://localhost:8000/)
Thanks for reading..!
I am creating a livestreaming site using Django and I need to upload an image using an ajax post request to a model form on the django site. I am working with the following code:
Models:
from django.db import models
from django.contrib.auth.models import User
class Camera(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='camera')
image = models.ImageField(upload_to='live/', null=True, blank=True)
Views:
from .models import Camera
from .forms import CameraForm
#login_required
#csrf_exempt
def golive(request):
cameras = Camera.objects.filter(user=request.user)
camera = None
if cameras.count() == 0:
camera = Camera.objects.create(user=request.user)
camera.save()
else:
camera = cameras.first()
if request.method == 'POST':
print(request.FILES)
form = CameraForm(request.POST, request.FILES, instance=camera)
if form.is_valid():
form.save()
print("Working")
return redirect('live:live')
return render(request, 'live/golive.html', {'object': request.user.camera, 'form': CameraForm()})
#login_required
def live(request, username):
profile = get_object_or_404(Profile, user__username=username, identity_verified=True, vendor=True)
cameras = Camera.objects.filter(user=profile.user)
return render(request, 'live/live.html', {'profile': profile, 'camera': cameras.first()})
Templates:
{% extends 'base.html' %}
{% block content %}
<h1>Go live</h1>
<div id="container">
<video autoplay="true" id="video">
</video>
<canvas id="canvas" width="1028" height="728">
</canvas>
<button id="capture"></button>
</div>
{% endblock %}
{% block javascript %}
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function capture(){
ctx.drawImage(video, 0, 0, 1024, 728);
ctx.save();
canvas.toBlob(function(blob){
console.log(blob);
var fileOfBlob = new File([blob], 'camera.png');
var formData = new FormData();
formData.append('image', fileOfBlob, 'camera.png');
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (response) {
console.log("Captured image.")
},
cache: false,
contentType: false,
processData: false
});
},'image/png');
}
setInterval(capture, 10000);
function startup() {
navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then(function(stream) {
video.srcObject = stream;
video.play();
})
.catch(function(err) {
console.log("An error occurred: " + err);
});
}
startup();
{% endblock %}
Forms:
from django import forms
from .models import Camera
class CameraForm(forms.ModelForm):
class Meta:
model = Camera
fields = ('image',)
The webcam renders on the page just fine but when I try to render
{{ camera.image.url }}
I see that the image has not been uploaded. How do I upload a blob image using ajax to a django site? Is there something I am missing? This is the error I am getting:
django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None
This is sort of out of the box, but this is the solution I came up with. I wrote my own basic codec using only blobs, which uses a setInterval to collect images at a short interval and uploads them to the server every 5 seconds. I then load the images and split them, using another setInterval to display them. This is the code:
Models:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Camera(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='camera')
src = models.TextField(default="", null=True, blank=True)
last_frame = models.DateTimeField(default=timezone.now)
Views:
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from users.models import Profile
from django.contrib import messages
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
import datetime
from django.utils import timezone
from django.core.paginator import Paginator
from django.utils.decorators import method_decorator
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.decorators import user_passes_test
from feed.tests import identity_verified
from vendors.tests import is_vendor
from django.core.exceptions import PermissionDenied
from django.http import StreamingHttpResponse
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
import uuid
import imghdr
import os
from django.conf import settings
from .models import Camera
from django.core.files import File
from django.core.files.base import ContentFile
from django.core.files.temp import NamedTemporaryFile
from django import forms
import traceback
from urllib.request import urlopen
#login_required
#user_passes_test(identity_verified, login_url='/verify/', redirect_field_name='next')
#user_passes_test(is_vendor)
#csrf_exempt
def golive(request):
cameras = Camera.objects.filter(user=request.user)
camera = None
if cameras.count() == 0:
camera = Camera.objects.create(user=request.user)
camera.save()
else:
camera = cameras.first()
if request.method == 'POST':
try:
p = ''
for key, value in request.POST.items():
value = value.split('\n')
p = p + value[2] + value[3] + '*'
p = p.replace(' ', '+')
camera.last_frame = timezone.now()
camera.src = p
camera.save()
except:
print(traceback.format_exc())
return HttpResponse(status=200)
return render(request, 'live/golive.html', {'object': request.user.camera})
#login_required
#user_passes_test(identity_verified, login_url='/verify/', redirect_field_name='next')
#csrf_exempt
def live(request, username):
profile = get_object_or_404(Profile, user__username=username, identity_verified=True, vendor=True)
cameras = Camera.objects.filter(user=profile.user)
return render(request, 'live/live.html', {'profile': profile, 'camera': cameras.first()})
#login_required
#user_passes_test(identity_verified, login_url='/verify/', redirect_field_name='next')
#csrf_exempt
def last_frame(request, username):
profile = get_object_or_404(Profile, user__username=username, identity_verified=True, vendor=True)
cameras = Camera.objects.filter(user=profile.user)
return render(request, 'live/lastframe.html', {'profile': profile, 'camera': cameras.first()})
#login_required
#user_passes_test(identity_verified, login_url='/verify/', redirect_field_name='next')
#csrf_exempt
def frame(request, username):
profile = get_object_or_404(Profile, user__username=username, identity_verified=True, vendor=True)
cameras = Camera.objects.filter(user=profile.user)
return render(request, 'live/liveframe.html', {'profile': profile, 'camera': cameras.first()})
Templates:
-- The template for viewing the live feed:
{% extends 'base.html' %}
{% block content %}
<h1>#{{ profile.user.username }}'s Live Feed</h1>
<div id="lastFrame"></div>
<div id="container">
<canvas id="videoCanvas" width="512" height="364">
</canvas>
<iframe src="/chat/{{ profile.user.username }}/?hidenavbar=t" width="100%" height="500px">
</iframe>
{% endblock %}
{% block javascript %}
var canvas = document.getElementById("videoCanvas");
var lastFrame = document.getElementById("lastFrame");
if(window.innerWidth > window.innerHeight) {
canvas.width = parseInt(window.innerWidth * 0.90);
canvas.height = parseInt(canvas.width * 364/512);
} else {
canvas.width = parseInt(window.innerWidth * 0.60);
canvas.height = parseInt(canvas.width * 364/512);
}
let xhr = new XMLHttpRequest();
let xhr2 = new XMLHttpRequest();
function loadListener2(){
if (xhr2.readyState === xhr2.DONE) {
if(!xhr2.responseText.includes("Error 500")){
lastFrame.innerHTML = xhr2.responseText;
}
}
}
function loadListener(){
if (xhr.readyState === xhr.DONE) {
var data = xhr.responseText.substring(0, xhr.responseText.length)
data = data.replace(' ', '+');
data = data.replace(' ', '+');
data = data.replace('\n','');
if(!data.includes("Error 500")){
var images = data.split("*");
var count = 0;
var interval = setInterval(function(){
canvas.renderImage(images[count]);
count++;
}, {{ record_interval }});
setTimeout(function(){
clearInterval(interval);
}, 5000);
}
}
}
function render() {
xhr.addEventListener("load", loadListener);
xhr.open("POST", window.location.pathname + "frame/", true);
xhr.send(null);
xhr2.addEventListener("load", loadListener2);
xhr2.open("POST", window.location.pathname + "frame/last/", true)
xhr2.send(null);
}
setInterval(render, 5000);
HTMLCanvasElement.prototype.renderImage = function(blob){
var ctx = this.getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0, canvas.getBoundingClientRect().width, canvas.getBoundingClientRect().height);
ctx.save();
};
img.src = blob;
};
render();
{% endblock %}
-- The template for transmitting it
{% extends 'base.html' %}
{% block content %}
<h1>Go live</h1>
<div id="container">
<video autoplay="true" id="video" width="100%">
</video>
<canvas id="canvas" width="512" height="364" style="visibility: hidden;">
</canvas>
</div>
{% endblock %}
{% block javascript %}
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var image = document.getElementById('image');
var form = document.getElementById('input-form');
var ctx = canvas.getContext('2d');
var data;
function drawImage(){
ctx.drawImage(video, 0, 0, 512, 364);
ctx.save();
data = canvas.toDataURL('image/png').replace(' ', '+')
data = data.replace('\n','');
}
function capture(){
//console.log(data);
var dataArray = "";
var formData = new FormData();
var count = 0;
var recordInterval = setInterval(function(){
drawImage();
dataArray = dataArray + data + "*";
count++;
}, {{ record_interval }});
setTimeout(function(){
formData.append("image", new Blob([dataArray], {'type': 'image/png'}), "image.png");
clearInterval(recordInterval);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (response) {
console.log("Captured image.")
},
cache: false,
processData: false
});
}, 5000);
}
setInterval(capture, 5000);
function startup() {
navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then(function(stream) {
video.srcObject = stream;
video.play();
})
.catch(function(err) {
console.log("An error occurred: " + err);
});
}
startup();
{% endblock %}
I know I'm using the .replace several times, but this is because the image needs to be in URL format so I need to replace newlines with '', spaces with +, and then the blob will render correctly. Pasting a printed blob into the browser to test works well too! But for best practice, I am using the replace in multiple places to format the blob correctly.
I’m a beginner. I have tried everything in the Django E-commerce website course, but it does not work for me. I also tried documentation but I didn’t get any solution. I have this error when I go to /update_item/ and the data is not showing up in the terminal:
Expecting value: line 1 column 1 (char 0)
error screenshot
tutorial link
tutorial link
https://youtu.be/woORrr3QNh8
cart.js
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated, sending data...')
var url = '/update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
views.py
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print("Action",action)
print("Pordutcs:",productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer , complete=False)
orderitem, created = Orderitem.objects.get_or_create(order= order,product=product)
if action == 'add':
orderitem.quantity = (orderitem.quantitiy +1)
elif action == 'remove':
orderitem.quantity = (orderitem.quantity -1)
orderitem.save()
if orderitem.quantity <= 0:
orderitem.delete()
return JsonResponse("Item was added", safe=False)
store.html
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
{%for i in products %}
<!-- {{i.image.url}} -->
<div class="col-lg-4">
<!-- <img class="thumbnail" src="{{i.image.url}}" alt="sorry"> -->
<img class="thumbnail" src="static{{i.imageURL}}">
<!-- {% static 'my_app/example.jpg' %} -->
<div class="box-element product">
<h6><strong>{{i.name}}</strong></h6>
<hr>
<button data-product="{{i.id}}" data-action='add' class="btn btn-outline-secondary add-btn updatecart">Add
to Cart</button>
<a class="btn btn-outline-success" href="#">View</a>
<h4 style="display: inline-block; float:right"><strong>Rs {{i.price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
<!-- <img src="static/images/robot.jpg"> -->
</div>
{% endblock content %}
I tried making a dummy django project with the code you provided to see if I counter such error.
Following JS code I used:
function updateUserOrder(){
console.log('User is authenticated, sending data...')
var url = '/update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
},
body:JSON.stringify({'productId':5, 'action':'Add'})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
I gave dummy data to productId and action.
Then my views.py goes like this:
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print("Action",action)
print("Pordutcs:",productId)
return JsonResponse("Item was added", safe=False)
Not much with html part, it was just a click button to call the js code.
<button onclick="updateUserOrder()">Add</button>
And worked like a charm, following is the screenshot of my output in django server:
I would suggest you to try running with the same code.
If error is still there, try giving dummy data to productId and action in js code to make sure if there is a problem with the data in productId and action.
I assume you've solved this issue otherwise,...
if you're using Django version 4.0
change the url for the cart.js to update_item, cart.js should look like this
cart.js:
var updateBtns = document.getElementsByClassName('update-cart')
for (i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId:', productId, 'Action:', action)
console.log('USER:', user)
})
}
function updateUserOrder(productId, action){
console.log('User is authenticated, sending data...')
var url = 'update_item/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'productId':productId, 'action':action})
})
.then((response) => {
return response.json();
})
.then((data) => {
location.reload()
});
}
then import csrf_exempt decorator , your views should look like this
views.py(after adding "from django.views.decorators.csrf import csrf_exempt" to the top of your file)
#csrf_exempt
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
print("Action",action)
print("Pordutcs:",productId)
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer , complete=False)
orderitem, created = Orderitem.objects.get_or_create(order= order,product=product)
if action == 'add':
orderitem.quantity = (orderitem.quantitiy +1)
elif action == 'remove':
orderitem.quantity = (orderitem.quantity -1)
orderitem.save()
if orderitem.quantity <= 0:
orderitem.delete()
return JsonResponse("Item was added", safe=False)
Then Clear Your Cache and try adding the item to cart again...it should work this time
I am using https://github.com/fengyuanchen/cropper/blob/master/README.md as the cropper function. However, I want to submit field objects (in this case the title) and the cropped image. But I got an error on the admin. And of course, I have done the makemigrations and migrate before running the server
Error Picture
admin.py
from django.contrib import admin
from .models import Image
# Register your models here.
class ImageAdmin(admin.ModelAdmin):
pass
admin.site.register(Image, ImageAdmin)
models.py
from django.db import models
# Create your models here.
class Image(models.Model):
title = models.CharField(max_length=10)
image = models.ImageField(upload_to='images')
def __str__(self):
return str(self.pk)
forms.py
from django import forms
from .models import Image
class ImageForm(forms.Form):
image = forms.ImageField()
title = forms.CharField(
max_length=10,
widget=forms.TextInput(
attrs={
"class": "form-control",
"placeholder": "Title",
},
),
required=True
)
views.py
from django.shortcuts import render, redirect
from .models import Image
from .forms import ImageForm
from django.http import JsonResponse
from django.http import HttpResponseRedirect
def main_view(request):
form = ImageForm()
if request.method == "POST":
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
addimage = Image(
title=form.cleaned_data['title'],
image = form.cleaned_data['image'],
)
addimage.save()
else:
form = ImageForm()
context = {'form': form}
return render(request, 'photo_list.html', context)
photo_list.html
{% extends "base.html" %}
{% block javascript %}
<script>
console.log("Hello");
const imageBox = document.getElementById("image-box");
const confirmButton = document.getElementById("confirm-button")
const input = document.getElementById("id_image");
const csrf = document.getElementsByName("csrfmiddlewaretoken")
const imageForm = document.getElementById("image-form")
input.addEventListener("change", () => {
console.log("change")
const img_data = input.files[0]
const url = URL.createObjectURL(img_data)
imageBox.innerHTML = `<img src="${url}" id="image" width="500px">`
var $image = $('#image');
$image.cropper({
aspectRatio: 16 / 9,
crop: function (event) {
console.log(event.detail.x);
console.log(event.detail.y);
console.log(event.detail.width);
console.log(event.detail.height);
console.log(event.detail.rotate);
console.log(event.detail.scaleX);
console.log(event.detail.scaleY);
}
});
// Get the Cropper.js instance after initialized
var cropper = $image.data('cropper');
confirmButton.addEventListener('click', () => {
cropper.getCroppedCanvas().toBlob((blob) => {
const fd = new FormData()
fd.append('csrfmiddlewaretoken', csrf[0].value)
fd.append('image', blob, 'my-image.png')
console.log("append pass")
$.ajax({
type: "POST",
url: imageForm.action,
enctype: 'multipart/form-data',
data: fd,
success: function (response) {
console.log(response)
},
error: function (error) {
console.log(error)
},
cache: false,
contentType: false,
processData: false,
})
})
})
});
</script>
{% endblock %}
{% block page_content %}
<form action="/cropimage/" id="image-form" method="POST">
{% csrf_token %}
{{form}}
{% comment %} <button class="btn" id="confirm-button"> confirm </button> {% endcomment %}
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Submit" id="confirm-button">
</form>
<div id="image-box" class="mb-3"> </div>
{% endblock %}
I was following this tutorial https://www.youtube.com/watch?v=oWd7SAuCIRM
Basically, I am making an album of images recorded with title, but this time with cropperjs. Any solutions or suggestions would be appreciated :).
Ahh silly me, after a week of finding solutions, I finally realize that I did not put and after deleting some of the database cache.
fd.append('title', $("input[name='title']").val())
on the getCroppedCanvas()
For those who had the same problem, please..
Ref :
How to append more data in FormData for django?
OperationalError, no such column. Django
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append