add new project

This commit is contained in:
Tu Quyen Tran Ngoc 2019-12-10 15:01:13 +01:00
parent f1eb3bccbd
commit 487a8b5ed2
13 changed files with 182 additions and 7 deletions

2
.idea/misc.xml generated
View File

@ -3,5 +3,5 @@
<component name="JavaScriptSettings"> <component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" /> <option name="languageLevel" value="ES6" />
</component> </component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (news1)" project-jdk-type="Python SDK" /> <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (venv)" project-jdk-type="Python SDK" />
</project> </project>

2
.idea/news1.iml generated
View File

@ -16,7 +16,7 @@
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" /> <excludeFolder url="file://$MODULE_DIR$/venv" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="jdk" jdkName="Python 3.7 (venv)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
<component name="TemplatesService"> <component name="TemplatesService">

17
news1/routing.py Normal file
View File

@ -0,0 +1,17 @@
from channels.routing import ProtocolTypeRouter
from django.urls import re_path
from channels.routing import URLRouter
from channels.http import AsgiHandler
from channels.auth import AuthMiddlewareStack
import django_eventstream
urlpatterns = [
re_path(r'^events/',
AuthMiddlewareStack(URLRouter(django_eventstream.routing.urlpatterns)),
{'channels': ['notice']}),
re_path(r'', AsgiHandler),
]
application = ProtocolTypeRouter({
'http' : URLRouter(urlpatterns)
})

View File

@ -31,12 +31,17 @@ ALLOWED_HOSTS = []
# Application definition # Application definition
INSTALLED_APPS = [ INSTALLED_APPS = [
'posts.apps.PostsConfig',
'rest_framework',
'channels',
'django_eventstream',
'django.contrib.admin', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
] ]
MIDDLEWARE = [ MIDDLEWARE = [
@ -47,6 +52,8 @@ MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_grip.GripMiddleware',
'django.middleware.security.SecurityMiddleware',
] ]
ROOT_URLCONF = 'news1.urls' ROOT_URLCONF = 'news1.urls'
@ -69,6 +76,7 @@ TEMPLATES = [
] ]
WSGI_APPLICATION = 'news1.wsgi.application' WSGI_APPLICATION = 'news1.wsgi.application'
ASGI_APPLICATION = 'news1.routing.application'
# Database # Database
@ -104,7 +112,7 @@ AUTH_PASSWORD_VALIDATORS = [
# Internationalization # Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/ # https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'de-de'
TIME_ZONE = 'UTC' TIME_ZONE = 'UTC'

View File

@ -15,8 +15,12 @@ Including another URLconf
""" """
from django.contrib import admin from django.contrib import admin
from django.urls import path,include from django.urls import path,include
from posts import views
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('posts/', include('posts.urls')) path('posts/', include('posts.urls')),
path('new', views.new, name='new'),
] ]

14
posts/forms.py Normal file
View File

@ -0,0 +1,14 @@
from django import forms
import datetime
class NoticeForm(forms.Form):
date_formats = ['%d.%m.%Y', '%d.%m.%y']
title = forms.CharField(label='Titel', max_length=80)
text = forms.CharField(label='Text', max_length=400)
start = forms.DateField(label='Von',
input_formats=date_formats,
initial=datetime.date.today)
end = forms.DateField(label='Bis',
input_formats=date_formats,
initial=datetime.date.today)

View File

@ -0,0 +1,24 @@
# Generated by Django 2.2.7 on 2019-11-19 13:25
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Notice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('notice_title', models.CharField(max_length=80)),
('notice_text', models.CharField(max_length=400)),
('pub_start', models.DateTimeField()),
('pub_end', models.DateTimeField()),
],
),
]

View File

View File

@ -1,3 +1,11 @@
from django.db import models from django.db import models
# Create your models here. # Create your models here.
from django.db import models
class Notice(models.Model):
notice_title = models.CharField(max_length=80)
notice_text = models.CharField(max_length=400)
pub_start = models.DateTimeField()
pub_end = models.DateTimeField()

8
posts/serializer.py Normal file
View File

@ -0,0 +1,8 @@
from rest_framework import serializers
from .models import Notice
class NoticeSerializer(serializers.ModelSerializer):
class Meta:
model = Notice
fields = ('id', 'notice_title', 'notice_text', 'pub_start', 'pub_end')

View File

@ -2,5 +2,13 @@ from django.urls import path
from . import views from . import views
urlpatterns = [ urlpatterns = [
path('', views.post, name='post') # path('', views.index, name='post'),
# path('delete/<int:deleteId>', views.delete, name='delete')
path('', views.index, name='index'),
path('new', views.new, name='new'),
path('delete/<int:deleteId>', views.delete, name='delete'),
path('notices/', views.notice_list),
path('notices/<int:id>', views.notice_detail),
] ]

View File

@ -1,6 +1,12 @@
from django.shortcuts import render from django.shortcuts import render, redirect
from .models import Notice
from django.utils import timezone
from django.http import HttpResponse from django.http import HttpResponse
from .forms import NoticeForm
from posts.serializer import NoticeSerializer
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
# Create your views here. # Create your views here.
@ -8,3 +14,71 @@ from django.http import HttpResponse
def post(request): def post(request):
return render(request, "posts/index.html") return render(request, "posts/index.html")
def index(request):
notices = Notice.objects.all()
notices = notices.filter(pub_start__lt = timezone.now())
notices = notices.filter(pub_end__gt = timezone.now())
context = { "notices" : notices}
return render(request, 'posts/index.html', context)
def new(request):
if request.method == "POST":
form = NoticeForm(request.POST)
if form.is_valid():
newNotice = Notice(notice_title=form.cleaned_data['title'],
notice_text=form.cleaned_data['text'],
pub_start=form.cleaned_data['start'],
pub_end=form.cleaned_data['end'])
newNotice.save()
#return redirect('index')
context = {'form': NoticeForm()}
return render(request, 'posts/edit.html', context)
def delete(request, deleteId=None):
if deleteId != None:
delNotice = Notice.objects.get(id=deleteId)
if delNotice != None:
delNotice.delete()
return redirect('index')
@csrf_exempt
def notice_list(request):
if request.method == 'GET':
notices = Notice.objects.all()
serializer = NoticeSerializer(notices, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = NoticeSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
@csrf_exempt
def notice_detail(request, id):
try:
notice = Notice.objects.get(id=id)
except Notice.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = NoticeSerializer(notice)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer=NoticeSerializer(notice, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
notice.delete()
return HttpResponse(status=204)

10
templates/posts/edit.html Normal file
View File

@ -0,0 +1,10 @@
{% extends "base.html" %}
{% block title %}edit.html{% endblock %}
{% block content %}
<h1>Neue Nachricht</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Speichern</button>
</form>
{% endblock %}