The current path, chat/room/1/, didn't match any of these - python-3.x

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 %}

Related

how to add specific comment to post in django post

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 %}

Simple Drupal 8 Facebook login JS code integration in twig template

I am writing a custom module for login using social network websites like Facebook, Gmail, Twitter. I have started with facebook first. I have followed all facebook login Quick Start Steps to get the code js from facebook to integrate in my website.
I am using Drupal 8 for this, I have copied all the code to the TWIG template. I don't know if anything I missed here, I can't get the facebook login button on web page. Can any one highlight my mistakes? Am looking into Network tab of Chrome browser, I can see https://connect.facebook.net/en_US/sdk.js is getting loaded and there are no errors listed.
This is my html.twig file.
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MyappId',
cookie : true,
xfbml : true,
version : '3.3'
});
FB.AppEvents.logPageView();
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
</script>
<h2><b>Choose login method</b></h2>
<ul>
{% for methods in items %}
{% if methods.id == 1 %}
<li>
<fb:login-button
scope="public_profile,email"
onlogin="checkLoginState();">
</fb:login-button>
{{ methods.name }}
</li>
{% endif %}
{% if methods.id == 2 %}
<li> GMAIL image {{ methods.name }}</li>
{% endif %}
{% if methods.id == 3 %}
<li> TWITTER image {{ methods.name }}</li>
{% endif %}
{% endfor %}
</ul>

Jinja html templates formatting with ALE and Prettier in Vim

I am using NVIM v0.3.2-208-g2841e89 on Ubuntu 16.04 LTS and using ALE as my Linting Engine plugin. I am having issue with formatting for jinja template html files with prettier.
The html files which start with <html> tag and contains jinja code are not being formatted at all. When i run ALEFix on these files nothing happens.
The html files that start with {% extends %} line are getting formatted but not the correct way. When i run ALEFix on these files, this is how the code starts to look.
Original File
{% extends "home.html" %}
{% block body %}
<div class="jumbotron">
<p>Thank you {{ session['username'] }} for signing up !!</p>
</div>
{% endblock %}
Formatted File
{% extends "home.html" %} {% block body %}
<div class="jumbotron">
<p>Thank you {{ session['username'] }} for signing up !!</p>
</div>
{% endblock %}
Here is another example.
Original File
{% extends "home.html" %}
{% block body %}
<form method="POST">
{{ form.hidden_tag() }}
{{ form.username.label }} {{ form.username }}
{{ form.password.label }} {{ form.password }}
{{ form.submit }}
</form>
{% endblock %}
Formatted File
{% extends "home.html" %} {% block body %}
<form method="POST">
{{ form.hidden_tag() }} {{ form.username.label }} {{ form.username }} {{
form.password.label }} {{ form.password }} {{ form.submit }}
</form>
{% endblock %}
I am not sure if this is the correct formatting of the jinja file but it does not look very readable.
This is how my config looks
let g:ale_fixers = {
\ '*': ['remove_trailing_lines', 'trim_whitespace'],
\ 'html': ['prettier'],
\ 'javascript': ['eslint', 'prettier'],
\ 'css' : ['stylelint', 'prettier'],
\ 'python' : ['yapf', 'isort', 'autopep8']
\ }
Below is what ALEInfo reports for a jinja template file.
Current Filetype: jinja.html
Available Linters: ['alex', 'htmlhint', 'proselint', 'stylelint', 'tidy', 'writegood']
Linter Aliases:
'writegood' -> ['write-good']
Enabled Linters: ['alex', 'htmlhint', 'proselint', 'stylelint', 'tidy', 'writegood']
Suggested Fixers:
'prettier' - Apply prettier to a file.
'remove_trailing_lines' - Remove all blank lines at the end of a file.
'tidy' - Fix HTML files with tidy.
'trim_whitespace' - Remove all trailing whitespace characters at the end of every line.
Linter Variables:
let g:ale_html_htmlhint_executable = 'htmlhint'
let g:ale_html_htmlhint_options = ''
let g:ale_html_htmlhint_use_global = 0
let g:ale_html_stylelint_executable = 'stylelint'
let g:ale_html_stylelint_options = ''
let g:ale_html_stylelint_use_global = 0
let g:ale_html_tidy_executable = 'tidy'
let g:ale_html_tidy_options = '-q -e -language en'
Global Variables:
let g:ale_cache_executable_check_failures = v:null
let g:ale_change_sign_column_color = 0
let g:ale_command_wrapper = ''
let g:ale_completion_delay = v:null
let g:ale_completion_enabled = 0
let g:ale_completion_max_suggestions = v:null
let g:ale_echo_cursor = 1
let g:ale_echo_msg_error_str = 'E'
let g:ale_echo_msg_format = '[%linter%] %s [%severity%]'
let g:ale_echo_msg_info_str = 'Info'
let g:ale_echo_msg_warning_str = 'W'
let g:ale_enabled = 1
let g:ale_fix_on_save = 1
let g:ale_fixers = {'html': ['prettier'], '*': ['remove_trailing_lines', 'trim_whitespace'], 'javascript': ['eslint', 'prettier'], 'css': ['stylelint', 'prettier'], 'python': ['yapf', 'isort', 'autopep8']}
let g:ale_history_enabled = 1
let g:ale_history_log_output = 1
let g:ale_keep_list_window_open = 0
let g:ale_lint_delay = 200
let g:ale_lint_on_enter = 1
let g:ale_lint_on_filetype_changed = 1
let g:ale_lint_on_insert_leave = 0
let g:ale_lint_on_save = 1
let g:ale_lint_on_text_changed = 'always'
let g:ale_linter_aliases = {}
let g:ale_linters = {'css': ['stylelint'], 'python': ['flake8']}
let g:ale_linters_explicit = 0
This isn't supported by prettier. Somebody needs to step up and write a plugin for it.
prettier issue: https://github.com/prettier/prettier/issues/5581
Note: It says Django but it's basically the same in this context.

Symfony2 display associative array in twig

I am new to the Symfony2 framework and am trying to parse some XML from the lastfm API and display information to the user. this would be in the format of album title, playcount and album image for each item.
I can display all this information so far to the user but this is not really useful as I intend to add CSS styling to my page. Any suggestions would be appreciated.
This is my Controller
/**
* #Route("/lastfm/albums", name="albums")
* #Template()
*/
public function albumsAction()
{
$albumsclass = new Album();
// pull in artist albums
$albums = simplexml_load_file('http://ws.audioscrobbler.com/2.0/? method=artist.gettopalbums&artist=imagine+dragons&api_key=370f98844440c2ecc8e5f7 c6cea8a7a4');
$rank = $albums->xpath('/lfm/topalbums/album/#rank');
$album_name_array=array();
$album_playcount_array=array();
$album_url_array=array();
$album_image_array=array();
foreach ($rank as $ranks){
foreach ($ranks as $rank_id) {
$album_name = $albums->xpath('/lfm/topalbums/album[#rank="'.$rank_id.'"]/name');
$album_playcount = $albums->xpath('/lfm/topalbums/album[#rank="'.$rank_id.'"]/playcount');
$album_url = $albums->xpath('/lfm/topalbums/album[#rank="'.$rank_id.'"]/url');
$album_image = $albums->xpath('/lfm/topalbums/album[#rank="'.$rank_id.'"]/image[4]');
}
$album_name = implode($album_name);
array_push($album_name_array,$album_name);
$album_playcount = implode($album_playcount);
array_push($album_playcount_array,$album_playcount);
$album_url = implode($album_url);
array_push($album_url_array,$album_url);
$album_image = implode($album_image);
array_push($album_image_array,$album_image);
}
$container=array();
for($i=0; $i<sizeof($album_name_array); $i++) {
array_push($container,$album_name_array[$i],$album_playcount_array[$i],$album_ur l_array[$i],$album_image_array[$i]);
}
//$hello = array('album_name'=>$album_name_array,
// 'album_playcount'=>$album_playcount_array,
// 'album_url'=>$album_url_array,
// 'album_image'=>$album_image_array,);
//array_push($album_name_array,$album_playcount_array);
return $this->render('AcmelastfmBundle:Default:albums.html.twig', array(
// 'pageData' => array(
// 'artistxml' => $artistxml,
'rank' => $rank,
'ranks' => $ranks,
//'rank_id' => $rank_id,
// 'ranks' => $ranks,
'album_name' => $album_name_array,
//'album_playcount' => $album_playcount_array[$i],
'album_url' => $album_url_array,
'album_image' => $album_image_array,
'container' =>$container,
'data' => var_export($container, true),
//
// 'hello' => $hello,
// 'james' => array('album_name' => $albumsclass->getAlbumName()),
// ),
));
}
This is my view
{% extends '::lastfmbase.html.twig' %}
{% block title %}Albums{% endblock %}
{% block body %}
{% for key in container %}
{{key}} <br>
{% endfor %}<br>
{% endblock %}
I am basically trying to convert this code in PHP to symfony2. However I cannot find a way to pass the associative array values to twig as I get an array to string conversion error
<?php
// pull in artist albums
$albums = simplexml_load_file('http://ws.audioscrobbler.com/2.0/? method=artist.gettopalbums&artist=imagine+dragons&api_key=370f98844440c2ecc8e5f7 c6cea8a7a4');
$rank = $albums->xpath('/lfm/topalbums/album/#rank');
foreach ($rank as $ranks){
foreach ($ranks as $rank_id) {
$album_name = $albums->xpath('/lfm/topalbums/album[#rank="'.$rank_id.'"]/name');
$album_playcount = $albums->xpath('/lfm/topalbums/album[#rank="'.$rank_id.'"]/playcount');
$album_url = $albums->xpath('/lfm/topalbums/album[#rank="'.$rank_id.'"]/url');
$album_image = $albums->xpath('/lfm/topalbums/album[#rank="'.$rank_id.'"]/image[4]');
}
$album_name = implode($album_name);
$album_playcount = implode($album_playcount);
$album_url = implode($album_url);
$album_image = implode($album_image);
print_r($rank_id);
?>
<article class="album">
<?php
echo "".$album_name."<br>";
echo $album_playcount." listeners<br>";
echo "<div><img src=\"".$album_image."\" title=\"$album_name\" /></div><br>";
?>
</article>
<?php
}
I am not sure exactly what you are asking.
Do you mean this?
{% for key, value in container %}
{{ key }}: {{ value }}
{% endfor %}

What is auto escape used for in Swig templating for Node.js?

I'm trying to write an itinerary app built on Express. Swig is the template engine. I'm confused by Swig's autoescape feature. What exactly does it do?
Swig documentation example:
"Control auto-escaping of variable output from within your templates."
// myvar = '<foo>';
{% autoescape true %}{{ myvar }}{% endautoescape %}
// => <foo>
{% autoescape false %}{{ myvar }}{% endautoescape %}
// => <foo>
My code:
<script>
{% autoescape false %}
var all_hotels = {{ hotels | json }};
var all_restaurants = {{ restaurants | json }};
var all_things_to_do = {{ things_to_do | json }};
{% endautoescape %}
</script>
Thank you.
The documentation should read like this:
"Control auto-escaping of variable output from within your templates."
// myvar = '<foo>';
{% autoescape true %}{{ myvar }}{% endautoescape %}
// => <foo>
{% autoescape false %}{{ myvar }}{% endautoescape %}
// => <foo>
So when autoescape is true, it will HTML-escape variable content. I think this is the default setting for Swig.
Since you want to render JSON-variables, your code should work okay (turning off autoescaping to prevent HTML-escaping of the JSON content). Alternatively, you could use the safe filter:
var all_hotels = {{ hotels | safe | json }};
var all_restaurants = {{ restaurants | safe | json }};
...

Resources