Finish version

This commit is contained in:
Andros Fenollosa 2021-06-25 14:25:14 +02:00
parent 9f6fcf447d
commit 4d6f73ac63
7 changed files with 59 additions and 17 deletions

View File

@ -5,5 +5,5 @@ from rest_framework import serializers
class NewsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = News
fields = ['title', 'url', 'votes', 'created']
fields = ['id', 'title', 'url', 'votes', 'created']

View File

@ -2,6 +2,7 @@ from app.api.models import News
from rest_framework import viewsets, mixins
from app.api.serializers import NewsSerializer
from rest_framework.response import Response
import json
class NewsViewSet( mixins.UpdateModelMixin,
@ -19,11 +20,11 @@ class NewsViewSet( mixins.UpdateModelMixin,
return Response(serializer.data)
def put(self, request, pk=None):
def put(self, request):
# Update
my_news = News.objects.get(pk)
my_news = News.objects.get(pk=request.data['id'])
my_news.votes = my_news.votes + 1
my_news.save()
# Devolvemos la noticia modificada
serializer = News(my_news)
serializer = NewsSerializer(my_news)
return Response(serializer.data)

11
app/web/forms.py Normal file
View File

@ -0,0 +1,11 @@
from django import forms
class NewsForm(forms.Form):
title = forms.CharField(
label='Titulo',
required=True
)
url = forms.URLField(
label='Ruta',
required=True
)

View File

@ -1,10 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
{% extends 'layouts/base.html' %}
{% block title %}Añadir nueva noticia{% endblock %}
{% block main %}
<form novalidate method="post">
{% csrf_token %}
{{ news_form.as_p }}
<p>
<input type="submit" value="Guardar">
</p>
</form>
{% endblock %}

View File

@ -1,4 +1,6 @@
from django.shortcuts import render
from django.shortcuts import render, redirect, reverse
from app.api.models import News
from app.web.forms import NewsForm
def home(request):
@ -6,4 +8,19 @@ def home(request):
def add_news(request):
return render(request, 'pages/add-news.html', {})
mi_form = NewsForm()
# Validamos el formulario
if request.method == 'POST':
mi_form = NewsForm(request.POST)
# Muestro los errores
if mi_form.is_valid():
# Guardo
mi_new_news = News()
mi_new_news.title = mi_form.cleaned_data.get('title')
mi_new_news.url = mi_form.cleaned_data.get('url')
mi_new_news.save()
# Redirecciono a Home
return redirect(reverse('list'))
return render(request, 'pages/add-news.html', {
'news_form': mi_form
})

Binary file not shown.

View File

@ -16,6 +16,18 @@ new Vue({
.then((json) => {
this.news = json;
});
},
votar: function (id) {
fetch('/api/v1/news/', {
headers: {
'Content-type': 'application/json'
},
method: 'PUT',
body: JSON.stringify({ id: id })
})
.then((json) => {
this.getNews();
});
}
}
})