I can't pass values to database with Ajax and Django - javascript

i'm new in Ajax and Django i'm try sent videoP1 = 1 when percentage = 100 i'm use script tag on html to write js To get videoP1-videoP17 from database via views.py to set value in array and call it.
var videos = [
{
id: 1,
name: "1",
src: "../static/frontend/video/1.mp4",
videoP1: {{ video_db.videoP1 }},
},
{
id: 2,
name: "2",
src: "../static/frontend/video/2.mp4",
videoP2: {{ video_db.videoP2 }},
},
{
id: 17,
name: "17",
src: "../static/frontend/video/17.mp4",
videoP17: {{ video_db.videoP17 }},
},
];
var player = videojs("videoP");
function light(Cvideo) {
for (let i = 0; i < videos.length; i++) {
let video = videos[i];
if (videos[i].id === Cvideo) {
document.getElementById("nameV").innerHTML = videos[i].name;
player.src({ type: "video/mp4", src: videos[i].src });
player.play();
if (!video["videoP" + (i + 1)]) {
player.controlBar.progressControl.hide();
player.on("timeupdate", function() {
var percentage = (player.currentTime() / player.duration()) * 100;
document.getElementById("percentage").innerHTML =
Math.round(percentage) + "%";
if (percentage === 100) {
video["videoP" + (i + 1)] = 1;
var videopro = video["videoP" + (i + 1)] = 1;
$.ajax({
type: "POST",
url: "/update-video-progress/",
data: {
video_id: video.id,
videoPro: videopro,
},
success: function(response) {
console.log("Video progress updated");
},
error: function(xhr, textStatus, errorThrown) {
console.error("Failed to update video progress");
},
});
return;
}
});
} else {
player.controlBar.progressControl.show();
}
break;
}
}
}
<video id="videoP" class=" video-js vjs-fluid" controls data-setup='{}'>
<source src="../static/frontend/video/selectV.mp4" type="video/mp4">
</video>
<p id="percentage"class="hide_percent" >0</p>
1
2
17
this my views.py in my Django project to get the value and save to database and urls.py is path("save-data/", views.save_data, name="save-data"),
#csrf_exempt
def update_video_progress(request):
if request.method == "POST":
video_id = request.POST.get("video_id")
videoPro = request.POST.get("videoPro")
videoDB = VideoDB.objects.get(videoPro)
videoDB = videoPro
videoDB.save()
return JsonResponse({"message": "Video progress updated"})
def getDB(request):
video_db = VideoDB.objects.get(pk=5)
return render(request, 'User-page.html', {'video_db': video_db})
from django.db import models
class User(models.Model):
u_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
correctAnswers = models.IntegerField()
percentage = models.IntegerField(default=0)
def __str__(self):
return self.name
class VideoDB(models.Model):
u_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name='videodb')
videoP1 = models.IntegerField(default=0)
videoP2 = models.IntegerField(default=0)
videoP17 = models.IntegerField(default=0)
def __str__(self):
return str(self.u_id)
and this my models.py for create database

Related

How do I upload a webcam image using JavaScript ajax to a Django site?

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.

Adding a 'show all' to django search with js/ajax if results > 5

I have a simple django search functionality using js/ajax. I want to add functionality so that when the queryset is greater than 5 a 'Show all' href will appear in the search results and it will redirect to a page with all the queryset.
This is for the case when a queryset returns a large number of results, rather than have them in one big box.
I thought I could just add a dictionary to my queryset, e.g. data.append({'pk': <add number to querset>, 'name': 'Show all results'}) but then I think this will mess around with the js logic with the forEach loop.
I'd want each search result up to 5 to link to the detail view, but then the last one should link to a completely different view.
I'm not sure what the best option is here.
My search in views.py:
def search_results(request):
"""
Handles search logic
"""
if request.is_ajax():
res = None
quote = request.POST.get('quote')
qs = Quote.objects.filter(name__icontains=quote)
if len(qs) > 0 and len(quote) > 0:
data = []
for pos in qs:
item = {
'pk': pos.pk,
'name': pos.name,
'image': str(pos.image.url)
}
data.append(item)
res = data
else:
res = 'No quotes found...'
return JsonResponse({'data': res})
return JsonResponse({})
and main.js that handles loading the search results:
const url = window.location.href
const searchForm = document.getElementById('search-form')
const searchInput = document.getElementById('search-input')
const resultsBox = document.getElementById('results-box')
const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value
const sendSearchData = (quote) => {
$.ajax({
type: 'POST',
url: 'search/',
data: {
'csrfmiddlewaretoken': csrf,
'quote': quote,
},
success: (res)=> {
console.log(res.data)
const data = res.data
let length = data.length
console.log(length)
if (Array.isArray(data)) {
resultsBox.innerHTML = ""
data.forEach(quote=> {
resultsBox.innerHTML += `
<a href="${url}${quote.pk}" class="item">
<div class="row mt-2 mb-2">
<div class="col-2">
<img src="${quote.image}" class="quote-img">
</div>
<div class="col-10">
<h5>${quote.name}</h5>
<p class="text-muted">${quote.seller}</p>
</div>
</div>
</a>
`
})
} else {
if (searchInput.value.length > 0) {
resultsBox.innerHTML = `<b>${data}</b>`
} else {
resultsBox.classList.add('not-visible')
}
}
error: (err)=> {
console.log(err)
}
}
})
}
searchInput.addEventListener('keyup', e=>{
console.log(e.target.value)
if (resultsBox.classList.contains('not-visible')){
resultsBox.classList.remove('not-visible')
}
sendSearchData(e.target.value)
})

How to display the values of the attributes of the data queried and retrieved by Ajax call in django

I am trying to query the database based on what the user has clicked on the page and display the data retrieved by it without refreshing the page. I am using Ajax for this. Let me show you the codes
html
<label for="landacq" class="civil-label">Land Acquisation Cases</label>
<input class="civil-category" type="radio" name="civil-cat" id="landacq" value="land acquisation" hidden>
<label for="sc" class="civil-label">Supreme Court</label>
<input class="civil-court" type="radio" name="civil-court" id="sc" value="supreme court" hidden>
<label for="limitation" class="civil-label">Limitation</label>
<input class="civil-law-type" type="radio" name="civil-law-type" id="limitation" value="limitation" hidden>
js
for (i = 0; i < lawTypeInput.length; i++) {
lawTypeInput[i].addEventListener("click", (e) => {
e.preventDefault();
cat = civilCatval;
court = civilCourtval;
lawT = civillawTypeval;
console.log("this is from ajax : ", cat, court, lawT);
$.ajax({
type: "POST",
headers: { "X-CSRFToken": csrftoken },
mode: "same-origin", // Do not send CSRF token to another domain.
url: "civil",
data: {
"cat[]": civilCatval,
"court[]": civilCourtval,
"lawT[]": civillawTypeval,
},
success: function (query) {
showCivilQ(query);
// console.log(data);
},
error: function (error) {
console.log(error);
},
});
});
}
function showCivilQ(query) {
q.textContent = query;
console.log(query);
}
So here for example, if the user the click the radio button in the html, the values are grabbed by in js file and then sent to the url mentioned as a POST request. There these values are use to filter the database and return the objects like this
views.py
def civil_home(request):
if request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
return HttpResponse(query)
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
This is the result I am getting which is correct.
My Question is these objects contain attributes having some values in for eg, title, headnote etc. How can I display these attributes in the html rather than displaying the object names returned as shown in the Image like title of the citation, headnote of the citation etc
A solution could be to return a json object instead of the query resultset; because Ajax works well with json
You need a function that translates a Citation object into a dictionary (change it based on your real attributes). All elements must be translated into strings (see date example)
def citation_as_dict(item):
return {
"attribute1": item.attribute1,
"attribute2": item.attribute2,
"date1": item.date.strftime('%d/%m/%Y')
}
This dictionary must be translated into a json through import json package
def civil_home(request):
if request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
response_dict = [citation_as_dict(obj) for obj in query]
response_json = json.dumps({"data": response_dict})
return HttpResponse(response_json, content_type='application/json')
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
In your HTML page you should be able to parse the response as a normal JSON object
I figured out another way to do it, which is giving me the required results too.
Here I am filtering the values of the query, and then converting it to a list and passing it as a JsonResponse
views.py
def civil_home(request):
if request.method == "POST" and request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.values().filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
result = list(query)
return JsonResponse({"status": "success", "result": result})
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
And then I am recieving the reponse here and iterrating over it to print the attributes in the html
js
for (i = 0; i < lawTypeInput.length; i++) {
lawTypeInput[i].addEventListener("click", (e) => {
e.preventDefault();
cat = civilCatval;
court = civilCourtval;
lawT = civillawTypeval;
console.log("this is from ajax : ", cat, court, lawT);
$.ajax({
type: "POST",
headers: { "X-CSRFToken": csrftoken },
mode: "same-origin", // Do not send CSRF token to another domain.
url: "civil",
data: {
"cat[]": civilCatval,
"court[]": civilCourtval,
"lawT[]": civillawTypeval,
},
success: function (response) {
console.log(response.result);
civilData = response.result;
if ((response.status = "success")) {
$("#queryResult").empty();
for (i = 0; i < civilData.length; i++) {
$("#queryResult").append(
`
${civilData[i].title}
<p>${civilData[i].headnote}</p>
`
);
}
} else {
$("#queryResult").empty();
$("#queryResult").append(
`
<p>No Citations Found</p>
`
);
}
},
error: function (error) {
console.log(error);
},
});
});
}
A csrf_token can be mentioned at the top of the html page and then it can be passed in the header to avoid any conflict.

Chat Room in Django Channels

I have models "Project" and "Room". Every project has own chat room. I am tring to use Django Channels. Unfortunarly, I have error. What I miss and how to fix this error.
ERROR:
Traceback (most recent call last):
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\channels\handler.py", line 237, in process_exception_by_middleware
return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 176, in chat_room
room, created = Room.objects.get_or_create(project=project_code)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py", line 475, in get_or_create
return self._create_object_from_params(lookup, params)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py", line 505, in _create_object_from_params
obj = self.create(**params)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py", line 397, in create
obj = self.model(**kwargs)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\base.py", line 537, in __init__
setattr(self, field.name, rel_obj)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 211, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "'1744d0bc-e439-4562-9c29-4e7b2451f39c'": "Room.project" must be a "Project" instance.
urls.py:
url(r'^(?P<project_code>[0-9a-f-]+)/chat_room/$', chat_room, name='chat_room'),
settings.py:
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
},
"ROUTING": "chat.routing.channel_routing",
},
}
models.py:
class Room(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False)
def __str__(self):
return self.code
def get_absolute_url(self):
return reverse('project:chat_room', args=[self.project_code])
class Message(models.Model):
room = models.ForeignKey(Room, related_name='messages')
handle = models.TextField()
message = models.TextField()
timestamp = models.DateTimeField(default=timezone.now, db_index=True)
def __unicode__(self):
return '[{timestamp}] {handle}: {message}'.format(**self.as_dict())
def __str__(self):
return self.__unicode__()
#property
def formatted_timestamp(self):
return self.timestamp.strftime('%b %-d %-I:%M %p')
def as_dict(self):
return {'handle': self.handle, 'message': self.message, 'timestamp': self.formatted_timestamp}
views.py:
def chat_room(request, project_code):
# If the room with the given project_code doesn't exist, automatically create it upon first visit.
room, created = Room.objects.get_or_create(project=project_code)
# We want to show the last 50 messages, ordered most-recent-last
messages = reversed(room.messages.order_by('-timestamp')[:50])
return render(request, "project/chat/room.html", {
'room': room,
'messages': messages,
})
consumers.py:
#channel_session
def ws_connect(message):
prefix, project_code = message['path'].strip('/').strip('/').strip('/').strip('/').strip('/').strip('/')
room = Room.objects.get(project=project_code)
message.reply_channel.send({"accept": True})
Group('chat' + project_code).add(message.reply_channel)
message.channel_session['room'] = room.project
#channel_session
def ws_receive(message):
project_code = message.channel_session['room']
room = Room.objects.get(project=project_code)
data = json.loads(message['text'])
m = room.messages.create(handle=data['handle'], message=data['message'])
Group('chat' + project_code).send({'text': json.dumps(m.as_dict())})
#channel_session
def ws_disconnect(message):
project_code = message.channel_session['room']
Group('chat' + project_code).discard(message.reply_channel)
routing.py:
channel_routing = [
route("websocket.connect", ws_connect),
route("websocket.receive", ws_receive),
route("websocket.disconnect", ws_disconnect),
]
chat.js:
$(document).ready(function(){
socket = new WebSocket("ws://" + window.location.host + "/chat" + window.location.pathname);
var name = "";
swal({
title: 'Your name:',
input: 'text',
inputValidator: function (value) {
return new Promise(function (resolve, reject) {
if (value) {
resolve()
} else {
reject('You need to write something!')
}
})
}
}).then(function (result) {
name = result;
swal({
type: 'success',
html: 'Hello ' + result
})
});
socket.onopen = function(){
$('#chatform').on('submit', function(event) {
var message = {
handle: name,
message: $('#message').val(),
}
socket.send(JSON.stringify(message));
$('#message').val('');
return false;
});
}
socket.onmessage = function(message) {
var data = JSON.parse(message.data);
$('#chat').append('<tr>'
+ '<td>' + data.timestamp + '</td>'
+ '<td>' + data.handle + '</td>'
+ '<td>' + data.message + ' </td>'
+ '</tr>');
Push.create("Django Channels Example | " + room , {
body: "New Message",
icon: 'http://pa1.narvii.com/6184/91c955faf54e625b3467093bea75a6d25b813871_128.gif',
timeout: 4000,
onClick: function () {
window.focus();
this.close();
}
});
};
if (socket.readyState == WebSocket.OPEN) socket.onopen();
});

Edit in Laravel + AngularJS

I'm building a complete crud using laravel + angularjs, but I have problems in the "edit" part.
It's an internal server error, so I don't know what it means and I need help.
Error "GET localhost/crudtcc/public/api/v1/colaboradores/editar/3 500 (Internal Server Error)"
the javascript file:
app.controller('colaboradoresController', function($scope, $http, API_URL) {
$http.get(API_URL + "colaboradores")
.success(function(response) {
$scope.colaboradores = response;
});
$scope.toggle = function(modalstate, id_colaborador) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Novo colaborador";
$scope.colaborador = null;
break;
case 'edit':
$scope.form_title = "Dados do colaborador";
$scope.id_colaborador = id_colaborador;
$http.get(API_URL + 'colaboradores/editar/' + id_colaborador)
.success(function(response) {
console.log(response);
$scope.colaborador = response;
});
break;
default:
break;
}
$('#myModal').modal('show');
}
$scope.save = function(modalstate, id_colaborador) {
var url = API_URL + "colaboradores/salvar";
if (modalstate === 'edit') {
url += "/editar/" + id_colaborador;
}
$http({
method: 'POST',
url: url,
data: $.param($scope.colaborador),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('Um erro ocorreu. Check a log para mais detalhes.');
});
}
$scope.confirmDelete = function(id_colaborador) {
var isConfirmDelete = confirm('Tem certeza que deseja excluir o registro?');
if (isConfirmDelete) {
$http({
method: 'DELETE',
url: API_URL + 'colaboradores/remover/' + id_colaborador
}).
success(function(data) {
console.log(data);
location.reload();
}).
error(function(data) {
console.log(data);
alert('Falha na exclusão');
});
} else {
return false;
}
}
});
the routes file:
<?php
namespace App\Http\Controllers;
$colaborador = new Colaborador;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Usuario;
use App\Http\Controllers\Controler;
use App\Colaborador;
class Colaboradores extends Controller
{
public function index()
{
return Colaborador::orderBy('id_colaborador', 'asc')->get();
}
public function salvar(Request $request)
{
$colaborador->nome = $request->input('nome');
$colaborador->rg = $request->input('rg');
$colaborador->orgao_expedidor = $request->input('orgao_expedidor');
$colaborador->cpf = $request->input('cpf');
$colaborador->estado_civil = $request->input('estado_civil');
$colaborador->sexo = $request->input('sexo');
$colaborador->nome_pai = $request->input('nome_pai');
$colaborador->nome_mae = $request->input('nome_mae');
$colaborador->naturalidade = $request->input('naturalidade');
$colaborador->data_nascimento = $request->input('data_nascimento');
$colaborador->login = $request->input('login');
$colaborador->senha = $request->input('senha');
$colaborador->siape = $request->input('siape');
$colaborador->pis = $request->input('pis');
$colaborador->rua = $request->input('rua');
$colaborador->numero = $request->input('numero');
$colaborador->bairro = $request->input('bairro');
$colaborador->cidade = $request->input('cidade');
$colaborador->estado = $request->input('estado');
$colaborador->cep = $request->input('cep');
$colaborador->telefone_fixo = $request->input('telefone_fixo');
$colaborador->telefone_celular= $request->input('telefone_celular');
$colaborador->telefone_comercial = $request->input('telefone_comercial');
$colaborador->email = $request->input('email');
$colaborador->save();
return 'Colaborador salvo com sucesso! ID: ' . $colaborador->id_colaborador;
}
public function update(Request $request,$id_colaborador)
{
$colaborador = Colaborador::find($id_colaborador);
$colaborador->nome = $request->input('nome');
$colaborador->rg = $request->input('rg');
$colaborador->orgao_expedidor = $request->input('orgao_expedidor');
$colaborador->cpf = $request->input('cpf');
$colaborador->estado_civil = $request->input('estado_civil');
$colaborador->sexo = $request->input('sexo');
$colaborador->nome_pai = $request->input('nome_pai');
$colaborador->nome_mae = $request->input('nome_mae');
$colaborador->naturalidade = $request->input('naturalidade');
$colaborador->data_nascimento = $request->input('data_nascimento');
$colaborador->login = $request->input('login');
$colaborador->senha = $request->input('senha');
$colaborador->siape = $request->input('siape');
$colaborador->pis = $request->input('pis');
$colaborador->rua = $request->input('rua');
$colaborador->numero = $request->input('numero');
$colaborador->bairro = $request->input('bairro');
$colaborador->cidade = $request->input('cidade');
$colaborador->estado = $request->input('estado');
$colaborador->cep = $request->input('cep');
$colaborador->telefone_fixo = $request->input('telefone_fixo');
$colaborador->telefone_celular= $request->input('telefone_celular');
$colaborador->telefone_comercial = $request->input('telefone_comercial');
$colaborador->email = $request->input('email');
$colaborador->save();
return "Sucesso atualizando Colaborador #" . $colaborador->id_colaborador;
}
public function remove(Request $request, $id_colaborador)
{
$colaborador = Colaborador::where("id_colaborador", $id_colaborador);
$colaborador->delete();
return "Colaborador #". $request->input('id_colaborador'). " excluido com sucesso!";
}
public function editar($id_colaborador)
{
return Colaborador::where("id_colaborador", $id_colaborador);
}
}
?>
and the routes file...
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get("/colaboradores/gercolaboradores",
function() {
return view("/colaboradores/gerenciarcolaboradores");
});
Route::get("/api/v1/colaboradores/","Colaboradores#index");
Route::get("/api/v1/colaboradores/editar/{id_colaborador}","Colaboradores#editar");
Route::post('/api/v1/colaboradores/salvar/editar/{id_colaborador}',
'Colaboradores#update');
Route::post('/api/v1/colaboradores/salvar', 'Colaboradores#salvar');
Route::delete('/api/v1/colaboradores/remover/{id_colaborador}', 'Colaboradores#remove');
?>
You should write your request on Angular side as:
$http.post(API_URL + 'colaboradores/editar/' + id_colaborador, {YOUR_DATA})
.success(function(response) {
console.log(response);
$scope.colaborador = response;
});
and pass the parameters you want to send to backend.
Please refer to: https://docs.angularjs.org/api/ng/service/$http.
Explanation:
you're using angular GET
$http.get(API_URL + 'colaboradores/editar/' + id_colaborador)
and you defined your route in Laravel as POST
Route::post('/api/v1/colaboradores/salvar/editar/{id_colaborador}',
'Colaboradores#update');
GET is not passing any data except trough url, and you're trying to get that data as if you've sent it trough POST request.
You can find a short explanation on GET and POST requests on the following links: http://www.w3schools.com/tags/ref_httpmethods.asp and What is the difference between POST and GET?

Categories

Resources