Update post

This commit is contained in:
Andros Fenollosa 2021-03-12 00:09:19 +01:00
parent ae05e3a6f1
commit 901226c700
7 changed files with 127 additions and 63 deletions

View File

@ -1,12 +1,12 @@
import json
from channels.generic.websocket import WebsocketConsumer
from django.template.loader import render_to_string
from apps.back.models import Post
class BlogConsumer(WebsocketConsumer):
def connect(self):
''' Cliente se conecta '''
print('cooooooooooooonectando')
# Recoge el nombre de la sala
self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
self.room_group_name = "blog_%s" % self.room_name
@ -17,17 +17,6 @@ class BlogConsumer(WebsocketConsumer):
# Informa al cliente del éxito
self.accept()
# Send message to WebSocket
self.send(
text_data=json.dumps(
{
"selector": "#articles",
"position": "appendChild",
"html": render_to_string('blog/articles.html', {'pag': 1})
}
)
)
def disconnect(self, close_code):
''' Cliente se desconecta '''
# Leave room group
@ -36,31 +25,23 @@ class BlogConsumer(WebsocketConsumer):
def receive(self, text_data):
''' Cliente envía información y nosotros la recibimos '''
text_data_json = json.loads(text_data)
name = text_data_json["name"]
text = text_data_json["text"]
selector = text_data_json["selector"]
template = text_data_json["template"]
data = text_data_json["data"]
# Enviamos el mensaje a la sala
self.channel_layer.group_send(
self.room_group_name,
{
"type": "chat_message",
"name": name,
"text": text
}
)
# Database
if template == "partials/blog/all_articles.html":
data["posts"] = Post.objects.all()[:5]
def chat_message(self, event):
''' Recibimos información de la sala '''
name = event["name"]
text = event["text"]
if template == "partials/blog/single.html":
data["post"] = Post.objects.get(data['id'])
# Send message to WebSocket
self.send(
text_data=json.dumps(
{
"type": "chat_message",
"name": name,
"text": text
"selector": selector,
"html": render_to_string(template, data)
}
)
)

View File

@ -13,9 +13,6 @@ class Post(models.Model):
status = models.IntegerField(choices=STATUS, default=0)
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
@ -25,8 +22,5 @@ class Comment(models.Model):
post = models.ForeignKey(Post, on_delete= models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.name

View File

@ -14,42 +14,85 @@
<link rel="stylesheet" href="https://unpkg.com/spectre.css/dist/spectre-icons.min.css">
</head>
<body>
<div class="container">
<nav id="nav">
<ul class="nav">
<li class="nav-item">
<a href="#">All</a>
<ul class="tab tab-block">
<li class="tab-item">
<a id="link-all" href="#">All</a>
</li>
<li class="nav-item">
<a href="#">About</a>
<li class="tab-item">
<a id="link-about" href="#">About</a>
</li>
</ul>
</nav>
<main id="main"></main>
<main id="main">
<div id="articles">
{% for post in posts %}
<article>
<h2>{{ post.title }}</h2>
<p>Author: {{ post.author }}</p>
<p><button class="btn">More</button></p>
<hr>
</article>
{% endfor %}
</div>
<ul class="pagination">
<li class="page-item disabled">
<a href="#" tabindex="-1">Previous</a>
</li>
<li class="page-item">
<a href="#">Next</a>
</li>
</ul>
</main>
</div>
<script>
const CHAT_SOCKET = new WebSocket('ws://my-demo.localhost/ws/blog/{{ CHANNEL}}/');
document.$CHAT_SOCKET = new WebSocket('ws://my-demo.localhost/ws/blog/{{ CHANNEL}}/');
// Conectado
CHAT_SOCKET.addEventListener('open', () => {
console.log('Conectado');
document.$CHAT_SOCKET.addEventListener('open', () => {
console.log('Connect');
});
// Desconectado
CHAT_SOCKET.addEventListener('close', () => {
console.log('Desconectado');
document.$CHAT_SOCKET.addEventListener('close', () => {
console.log('Disconnect');
});
// Recibir mensaje
CHAT_SOCKET.addEventListener('message', (event) => {
console.log('Recibido nuevo mensaje');
const MI_NUEVA_DATA = JSON.parse(event.data);
});
// Recibir mensaje y dibujar
document.$CHAT_SOCKET.addEventListener('message', (event) => {
console.log('New HTML');
const NEW_DATA = JSON.parse(event.data);
//document.querySelector(NEW_DATA.selector).innerHTML = NEW_DATA.html;
// Desconectado
CHAT_SOCKET.addEventListener('error', (event) => {
console.log('error');
console.log(event)
const rangeHTML = document.createRange().createContextualFragment(NEW_DATA.html);
document.querySelector(NEW_DATA.selector).innerHTML = '';
document.querySelector(NEW_DATA.selector).appendChild(rangeHTML);
console.log(rangeHTML)
});
document.querySelector('#link-about').addEventListener('click', (event) => {
event.preventDefault();
document.$CHAT_SOCKET.send(JSON.stringify({
selector: "#main",
template: "partials/website/about.html",
data: {}
}));
});
document.querySelector('#link-all').addEventListener('click', (event) => {
event.preventDefault();
document.$CHAT_SOCKET.send(JSON.stringify({
selector: "#main",
template: "partials/blog/all_articles.html",
data: {}
}));
});
</script>
</body>
</html>

View File

@ -0,0 +1,34 @@
<div id="articles">
{% for post in posts %}
<article>
<h2>{{ post.title }}</h2>
<p>Author: {{ post.author }}</p>
<p><button data-id="{{ post.id }}" class="btn">More</button></p>
<hr>
</article>
{% endfor %}
</div>
<ul class="pagination">
<li class="page-item disabled">
<a href="#" tabindex="-1">Previous</a>
</li>
<li class="page-item">
<a href="#">Next</a>
</li>
</ul>
<script>
const buttons = document.querySelectorAll('.btn');
buttons.forEach((button) => {
button.addEventListener('click', event => {
document.$CHAT_SOCKET.send(JSON.stringify({
selector: "#main",
template: "partials/blog/single.html",
data: {
id: event.target.dataset.id
}
}))
});
});
</script>

View File

@ -0,0 +1,5 @@
<article>
<h1>{{ post.title }}</h1>
<h2>{{ post.author }}</h2>
<div>{{ post.content }}</div>
</article>

View File

@ -0,0 +1,5 @@
<h2>About page</h2>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Nam molestias ex vitae officiis, autem repellendus, ea doloribus voluptates. Odit accusamus alias soluta animi cumque, aspernatur, beatae repudiandae non laudantium sunt?</p>
<p>Necessitatibus at hic ducimus quam numquam aspernatur fugit quia molestiae. Ipsum quibusdam quae placeat nemo? Eaque, vel repellendus ea tenetur non veniam dicta? Itaque ipsum tempora inventore, assumenda dignissimos ratione.</p>
<p>Dicta voluptatem repudiandae exercitationem possimus iure, cumque, minus, odit accusamus, fugiat nulla ratione nobis ad harum. Recusandae obcaecati eligendi, amet officiis iusto porro saepe quaerat, cum labore molestiae? Praesentium, omnis!</p>
<p>Voluptate nostrum qui porro est magni excepturi maxime, modi nobis nesciunt quaerat soluta error alias quis voluptatibus iusto hic minus ipsam. Repudiandae quisquam quaerat illo eos quo error, ipsa nemo.</p>

View File

@ -1,7 +1,9 @@
from django.shortcuts import render
from apps.back.models import Post
import uuid
def all_articles(request):
return render(request, 'layouts/main.html', {
"CHANNEL": uuid.uuid4().hex[:20].upper()
"CHANNEL": uuid.uuid4().hex[:20].upper(),
"posts": Post.objects.all()[:5]
})