how to add specific comment to post in django post - python-3.x

I have posts that, user can add comments to, but i unable to add those comments to that specific posts, here is the code that I'm following:-
the code is working fine with models and the only issue is when comment added, its added to only one post, rather than specific comment to specific post
HTML Code
<div class="quote-comment-box">
<form method="POST" class="com">
{% csrf_token %}
<input placeholder="Your thought" type="text" name="quote-comment" class="comment-input" id="{{ quote.id }}" title="{{ quote.user.id }}" data="{{ request.user }}">
<button type="submit" href="{% url 'micro__blog:quote_comment' %}" class="comment-button">POST</button>
</form>
<div class="content" id="content">
</div>
</div>
js code
$('.comment-button').click(function (params) {
csrftoken()
var index = $('.comment-button').index(this)
var comment = $( ".comment-input" ).eq(index).val()
var id = $( ".content" ).eq(index).attr('id')
params.preventDefault()
$.ajax({
url:$(this).attr("href"),
data:{
'blog_id' : $( '.comment-input' ).eq(index).attr('id'),
'blog_user' : $( '.comment-input' ).eq(index).attr('title'),
'comment' : $( ".comment-input" ).eq(index).val(),
},
type:'POST',
dataType: 'json',
success: function (res, status) {
if (res['status'] == 'ok') {
$('.comment-input').eq(index).val('');
var content = $('.content').eq(index)
console.log(index, content)
const div = document.createElement('div');
div.className = "comment-added"
div.innerHTML = `
<span class="user">` + $( ".comment-input" ).eq(index).attr('data') + `</span>
<span class="text">` + comment + `</span>`;
document.getElementById('content').appendChild(div);
console.log(res.status)
} else {
console.log(res.status)
}
},
error: function (res) {
console.log(res.status);
}
})
Here is view code
def quote_comment(request):
if request.method == 'POST':
blog_id = request.POST.get('blog_id')
blog_user = request.POST.get('blog_user')
comment = request.POST.get('comment')
current_user = User.objects.get(id = request.user.id)
if blog_id and blog_user and comment and current_user:
blog_id = Quote.objects.get(id = blog_id)
blog_user = User.objects.get(id=blog_user)
try:
QuoteComment.objects.get_or_create(user=current_user,blog_id=blog_id,blog_user_id=blog_user,comment=comment)
return JsonResponse({'status':'ok'})
except User.DoesNotExist:
return JsonResponse({'status':'error'})
return JsonResponse({'status':'error'})
and url
path('quote_comment/', views.quote_comment, name="quote_comment"),
A view that renders this template
def index(request):
quotes= Quote.objects.all()
return render(request=request, template_name="dashboard.html",context={'quotes':quotes})
to render on quotes im suing for loop like this
{% for quote in quotes %}
{% endfor %}

Related

The current path, chat/room/1/, didn't match any of these

I am practicing with Django 3 and I have a chat project with the name of educa . I try to run the project by python manage.py runserver and access http://127.0.0.1:8000/chat/room/1/ . I always get the following error messages:
“Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/chat/room/1/
Using the URLconf defined in educa.urls, Django tried these URL patterns, in this order:
1.accounts/login/ [name='login']
2.accounts/logout/ [name='logout']
3.admin/
4. course/
…
** The current path, chat/room/1/, didn't match any of these.” **
I really don’t know what’s wrong. Please someone help me .Thank you.
The following are the files :
educa/ruls.py :
urlpatterns = [
path('chat/', include('chat.urls', namespace='chat')),
]
chat/urls.py:
app_name = 'chat'
urlpatterns = [
path('room/<int:course_id>/', views.course_chat_room, name='course_chat_room'),
]
chat/views.py:
#login_required
def course_chat_room(request, course_id):
...
return render(request,'chat/room.html', {'course': course})
chat/templates/chat/room.html:
{% extends "base.html" %}
{% block title %}Chat room for "{{ course.title }}"{% endblock %}
{% block content %}
….
{% endblock %}
{% block domready %}
...
{% endblock %}
educa/settings.py:
INSTALLED_APPS = [
...
'chat',
'channels',
]
try this
urlpatterns = [
path('room/<int:course_id>/', views.course_chat_room, name='course_chat_room'),
]
more about URLs https://docs.djangoproject.com/en/3.1/ref/urls/#path
I have tried:
" path('room/<int:course_id>/', views.course_chat_room, name='course_chat_room'),
but the result is all the same. I think it doesn't solve my problem.
**html that I used to render the link to the chatroom:**
{% extends "base.html" %}
{% block title %}Chat room for "{{ course.title }}"{% endblock %}
{% block content %}
<div id="chat">
</div>
<div id="chat-input">
<input id="chat-message-input" type="text">
<input id="chat-message-submit" type="submit" value="Send">
</div>
{% endblock %}
{% block domready %}
var url = 'ws://' + window.location.host +
'/ws/chat/room/' + '{{ course.id }}/';
var chatSocket = new WebSocket(url);
chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data.message;
var dateOptions = {hour: 'numeric', minute: 'numeric', hour12: true};
var datetime = new Date(data.datetime).toLocaleString('en', dateOptions);
var isMe = data.user === '{{ request.user }}';
var source = isMe ? 'me' : 'other';
var name = isMe ? 'Me' : data.user;
var $chat = $('#chat');
$chat.append('<div class="message ' + source + '">' +
'<strong>' + name + '</strong> ' +
'<span class="date">' + datetime + '</span><br>' +
message +
'</div>');
$chat.scrollTop($chat[0].scrollHeight);
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
var $input = $('#chat-message-input');
var $submit = $('#chat-message-submit');
$submit.click(function() {
var message = $input.val();
if(message) {
// send message in JSON format
chatSocket.send(JSON.stringify({'message': message}));
// clear input
$input.val('');
// return focus
$input.focus();
}
});
$input.focus();
$input.keyup(function(e) {
if (e.which === 13) {
// submit with enter / return key
$submit.click();
}
});
{% endblock %}

Django data via ajax is empty on view

I'm trying to pass a data to django view via ajax like I used to do with php but I get on print empty value but my console log show that there is a data value on javascript but on view return None
Quit the server with CONTROL-C.
None
my html file code
{% for image in images %}
<table style="width:100%;" id="tab-{{image.image_cid}}">
<tr>
<td style="width:70%;vertical-align:middle">
<img src="/medias/{{ image.image_value }}" alt="" width="100" >
</td>
<td style="width:30%;vertical-align:middle">
DELETE
</td>
</tr>
</table>
{% endfor %}
<script>
$(document).ready(function(){
$(".cl-img-del").click(function(e){
var imgID = e.target.id
console.log(imgID);
$.ajax({
headers: {'X-CSRFToken': '{{ csrf_token }}'},
url: "{% url 'delete-image-ajax' %}",
type: "POST",
data: { imageid: imgID },
contentType: false,
cache: false,
processData:false,
success: function(data){
if(data == 'done')
{
$('#tab-'+imgID).remove();
}
},
error: function(){}
});
});
});
</script>
and my view file code is
def deleteImageAjxFn(request):
if request.method == "POST":
imgid = request.POST.get('imageid')
print(imgid)
try:
image = Images.objects.filter(image_shw = int(0), image_cid=imgid).delete()
except Images.DoesNotExist:
image = None
if(image):
return HttpResponse('done')
else:
return HttpResponse('None')
use static url in ajax instead of dynamic django url tags
use this instead url: "/delete-image-ajax/"

laravel search paginate Call to undefined method links()

Hi I have implemented a search facility in laravel it returns the search query but I also get this error in my laravel log as follows:
[2014-09-14 21:06:20] production.ERROR: exception
'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method
Illuminate\Database\Eloquent\Collection::links()' in
/media/sf_Sites/tempus/app/storage/views/424d7d6280a6a7c59b31268a6d17e44a:27
Stack trace:
#0 [internal function]: Illuminate\Exception\Handler->handleShutdown()
#1 {main} [] []
My code is as follows:
Projects/Index
#extends('layouts.master')
#section("content")
<div class="container">
<div>
{{ Form::open(['method' => 'GET', 'class' => 'nav-bar-form navbar-right']) }}
<div class="form-group">
{{ Form::input('search', 'q', null,['class' => 'form-control','placeholder' => 'Search']) }}
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
<p> {{ $project->project_name }}</p>
#endforeach
#else
<h5 class="errorslist">No match found</a></h5>
#endif
#endif
</div>
<div class="container">
<ul class="pagination">
<li>{{ $projects->links() }}</li>
</ul>
</div>
{{ Form::close() }}
#stop
Repository
public function searchProjects($query){
return \Project::where('project_name', 'LIKE', "%$query%" )
->orderby('project_name', 'asc')
->get();
}
public function getAll()
{
// get all logged in users projects and paginate 9 per page
return \Auth::user()->projects()->orderBy('project_name', 'asc')->paginate(9);
}
Controller:
public function index()
{
$query = Request::get('q');
$projects = $query
? $this->project->searchProjects($query)
: $this->project->getAll();
echo View::make('projects.index', compact('projects'));
}
Routes
Route::get('projects/index', array('before' => 'auth',
"as" => "projects/index",
"uses" => "ProjectController#index"
));
I'm not sure why I'm getting an error when I perform a search query on my links method, any ideas?
You need paginate on your searchProjects method as well:
public function searchProjects($query){
return \Project::where('project_name', 'LIKE', "%$query%" )
->orderby('project_name', 'asc')
->paginate(9);
}

Geddy - create new item

I am an absolute beginner in node.js and geddy. I've followed a few tutorials and now I try to write something similar for my purposes.
When I try to create a new item, though, I get the following message:
/arithmetic_problem_types/function%20(id)%20%7B%20%20%20%20%20%20options.id%20=%20id;%20%20%20%20%20%20return%20helpersBase.urlFor.action(options);%20%20%20%20%7D not found.
I have no idea where this could come from. I've looked through the code and found nothing.
Controller:
var ArithmeticProblemTypes = function () {
this.respondsWith =[ 'html', 'json', 'xml', 'js', 'txt'];
this.index = function (req, resp, params) {
var self = this;
geddy.model.ArithmeticProblemType.all(function (err, arithmetic_problem_types) {
self.respond({
params: params, arithmetic_problem_types: arithmetic_problem_types
});
});
};
this.add = function (req, resp, params) {
this.respond({
params: params
});
};
this.create = function (req, resp, params) {
var self = this, arithmetic_problem_type = geddy.model.ArithmeticProblemType.create({
name: '1', title: 'open', numberType: '1', numberRanges: '1', operators: '1', askedFor: '1', specialProblemCategory: '1', askedForNumDenomOrBoth: '1',
reducedFractions:'1', mixedFractions: '1'
});
arithmetic_problem_type.save(function (err, data) {
if (err) {
params.errors = err;
self.transfer('add');
} else {
self.redirect({
controller: self.name
});
}
});
};
....................................................................
};
exports.ArithmeticProblemTypes = ArithmeticProblemTypes;
add.html.ejs
<div class="hero-unit">
<%= partial('_form', {params: params}); %>
</div>
index.html.ejs
<div class="hero-unit">
<h2>Arithmetic Problem Types List</h2>
<%- linkTo('Create a new Aritmetic Problem Type', addArithmeticProblemTypePath, {class: 'btn pull-right'}) %>
</div>
<% if (arithmetic_problem_types && arithmetic_problem_types.length) { %>
<% for (var i in arithmetic_problem_types) { %>
<div class="row todo-item">
<div class="span8">
<h3><%- linkTo(arithmetic_problem_types[i].title, arithmeticProblemTypePath(arithmetic_problem_types[i].id)) %></h3>
</div>
<div class="span4"><h3><i class="icon-list-alt"></i><%= arithmetic_problem_types[i].status; %></h3></div>
</div>
<% } %>
<% } %>
How can I get rid of that message and make it work?
EDIT:
This is the beginning of the _form.html.ejs file:
<%
var isUpdate = params.action == 'edit'
, formTitle = isUpdate ? 'Update this Arithmetic Problem Type' : 'Create a new Arithmetic Problem Type'
, action = isUpdate ? arithmeticProblemTypePath(params.id) + '?_method=PUT' : arithmeticProblemTypePath
, deleteAction = isUpdate ? arithmeticProblemTypePath(params.id) + '?_method=DELETE' : ''
, btnText = isUpdate ? 'Update' : 'Add'
, nameValue = isUpdate ? arithmeticProblemTypePath.name : ''
, errors = params.errors;
%>
<form id="arithmetic-problem-type-form" class="form-horizontal" action="<%= action %>" method="POST">
....
</form>
EDIT2:
Inspecting the page where I should write the name of the item and click the add button, I've found this
<div class="hero-unit">
<form id="arithmetic-problem-type-form" class="form-horizontal" action="function (id) {
options.id = id;
return helpersBase.urlFor.action(options);
}" method="POST">
<fieldset>
<legend>Create a new Arithmetic Problem Type</legend>
<div class="control-group">
<label for="title" class="control-label">Title</label>
<div class="controls">
<input class="span6" name="name" placeholder="enter name" type="text">
</div>
</div>
<div class="form-actions">
<input class="btn btn-primary" type="submit" value="Add">
</div>
</fieldset>
</form>
</div>
Indeed the message comes from the action attribute of the form element, but how can I solve it?
The message is telling you that the requested URL could not be found. AKA 404
/arithmetic_problem_types/function%20(id)%20%7B%20%20%20%20%20%20options.id%20=%20id;%20%20%20%20%20%20return%20helpersBase.urlFor.action(options);%20%20%20%20%7D
is definitely not a nice looking url. So i'm assuming there's something wrong with your form's action attribute. If that's what happened when you validate the form.
If that's what happened when you click the link to "Create a new arithmetic problem type" then you should probably put parenthesis after addArithmeticProblemTypePath

Symfony2.1 FosUserBundle translation broken

I had a project with Symfony 2.0 and FOSUserBundle 1.2.0, and everything was working fine. When I upgraded to the latest Symfony 2.1 version and the latest FOSUserBundle from the master branch, after fixing lots of stuff, the labels are not being translated, i.e. "form.username".
I had the User Bundle overwritten by a custom bundle I made. I've overwritten the following stuff:
Controller
ChangePasswordController
GroupController
RegistrationController
UserController
Form
Type
ChangePasswordFormType
RegistrationFormType
Resources
config
routing.yml
views
ChangePassword
changePassword_content.html.twig
changePassword.html.twig
Form
form_group.html.twig
form_user.html.twig
Group
edit.html.twig
list.html.twig
new.html.twig
show.html.twig
Registration
checkEmail.html.twig
email.txt.twig
register_content.html.twig
register.html.twig
User
edit.html.twig
index.html.twig
show.html.twig
I also have a custom user and group entity, and my custom UserType and GroupType which I omitted in the previous tree.
The translation files where at app/Resources/translations/FOSUserBundle.en.yml
I also tryed copying them to my bundle, src/Acme/UserBundle/Resources/translations/FOSUserBundle.en.yml
None of them is working with symfony 2.1.
Of course I cleaned the cache, the production cache, and regenerated assets just in case and refreshed the browser... Everything several times and nothing.
I searched here and on Google and I can't find any clues, I tried some things but without success.
I will copy the contents of some of the files below.
Acme/UserBundle/Controller/RegistrationController.php
<?php
namespace Acme\UserBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
class RegistrationController extends BaseController
{
public function registerAction()
{
$form = $this->container->get('fos_user.registration.form');
$formHandler = $this->container->get('fos_user.registration.form.handler');
$confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$user = $form->getData();
$authUser = false;
if ($confirmationEnabled) {
$this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$route = 'fos_user_registration_check_email';
} else {
$authUser = true;
$route = 'AcmeUserBundle_admin_user_index';
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$url = $this->container->get('router')->generate($route);
$response = new RedirectResponse($url);
if ($authUser) {
$this->authenticateUser($user, $response);
}
return $response;
}
return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
'form' => $form->createView(),
));
}
}
Acme/UserBundle/Form/Type/RegistrationFormType.php
<?php
namespace Acme\UserBundle\Form\Type;
use Doctrine\ORM\EntityManager;
class RegistrationFormType extends BaseType
{
private $entityManager;
public function __construct($class, EntityManager $entityManager)
{
parent::__construct($class);
$this->entityManager = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle', 'error_bubbling' => true))
->add('nombre', 'text', array('error_bubbling' => true))
->add('apellido', 'text', array('error_bubbling' => true))
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle', 'error_bubbling' => true))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
'error_bubbling' => true,
))
->add('groups', 'entity', array(
'class' => 'Acme\\UserBundle\\Entity\\Group',
'property' => 'name',
'label' => 'Grupos',
'empty_value' => 'Seleccione Grupos',
'multiple' => true,
'expanded' => true,
'required' => false,
));
}
public function getName()
{
return 'acme_user_registration';
}
}
Acme/Resources/views/Registration/register_content.html.twig
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="fos_user_registration_register">
<div class="content no-padding" {{ block('container_attributes') }}>
{{ form_widget(form) }}
</div>
<div class="actions">
<div class="actions-left" style="margin-top: 8px;"></div>
<div class="actions-right">
<input type="submit" value="{{ 'registration.submit'|trans({}, 'FOSUserBundle') }}" />
</div>
</div>
Acme/Resources/views/Registration/register.html.twig
{% extends "AcmeAdminBundle:Base:base_auth.html.twig" %}
{% form_theme form 'AcmeUserBundle:Form:form_user.html.twig' %}
*[...] Here are stylesheets and JS[...]*
{% block main_content %}
<!-- Start of the main content -->
<div id="main_content">
<h2 class="grid_12">{% block title "Crear Usuario" %}</h2>
<div class="clean"></div>
<div class="grid_6">
<div class="box">
<div class="header">
<img src="{{ asset('bundles/acmeadmin/img/icons/packs/fugue/16x16/ui-text-field-format.png') }}" alt="" width="16"
height="16">
<h3>Información Básica</h3>
<span></span>
</div>
{% block fos_user_content %}
{% include "AcmeUserBundle:Registration:register_content.html.twig" %}
{% endblock fos_user_content %}
</div> <!-- End of .box -->
</div> <!-- End of .grid_6 -->
</div> <!-- End of #main_content -->
<div class="push clear"></div>
{% endblock main_content %}
If I disable my bundle, removing
public function getParent()
{
return 'FOSUserBundle';
}
the labels appear translated as expected. I don't know what else to do. Any Suggestions?

Resources