maria prompt, 활용한 명령어
table은 models.py를 활용해서 만든다
mysql -uroot -p
123
show databases;
create database nicedb;
use nicedb;
show tables;
desc myguest_guest;
insert into myguest_guest(title, content,regdate) values('마음','나이스',now());
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test', # DB명 : db는 미리 작성되어 있어야 함.
'USER': 'root', # 계정명
'PASSWORD': '123', # 계정 암호
'HOST': '127.0.0.1', # DB가 설치된 컴의 ip
'PORT': '3306', # DBMS의 port 번호
}
}
models.py
from django.db import models
# Create your models here.
class Guest(models.Model):
# myno = models.AutoField(auto_created=True, primary_key=True)
title = models.CharField(max_length=50)
content = models.TextField()
regdate = models.DateTimeField()
class Meta:
# 정렬 방법2
# ordering = ('title',)
# ordering = ('-title','id')
ordering = ('-id',)
admin.py
from django.contrib import admin
from myguest.models import Guest
# Register your models here.
class GuestAdmin(admin.ModelAdmin):
list_display=('id', 'title', 'content','regdate')
admin.site.register(Guest, GuestAdmin)
Anaconda Prompt
cd C:\work\psou\django6_maria
python manage.py createsuperuser
아이디 가입 후 admin 에서 컨텐츠 입력
urls.py
from django.contrib import admin
from django.urls import path
from myguest import views
from django.urls.conf import include
urlpatterns = [
path("admin/", admin.site.urls),
path('', views.MainFunc),
path('guest/', include('myguest.urls')),
]
urls.py (myguest)
from django.urls import path
from myguest import views
urlpatterns = [
path('select', views.ListFunc),
path('insert', views.InsertFunc),
path('insertok', views.InsertOkFunc),
]
views.py
from django.shortcuts import render, redirect
from myguest.models import Guest
from datetime import datetime
from django.utils import timezone
from django.http.response import HttpResponseRedirect
# Create your views here.
def MainFunc(request):
msg = "<h1>홈페이지</h1>"
return render(request, 'main.html', {'msg':msg})
def ListFunc(request):
# print(gdatas)
# print(Guest.objects.get(id=1))
# print(Guest.objects.filter(id=1))
# print(Guest.objects.filter(title='안녕'))
# print(Guest.objects.filter(title__contains='안녕'))
# #...
gdatas = Guest.objects.all()
#정렬 방법1
# gdatas = Guest.objects.all().order_by('title') # 오름차순
# gdatas = Guest.objects.all().order_by('-title') # 내림차순
# gdatas = Guest.objects.all().order_by('-id')
# gdatas = Guest.objects.all().order_by('title', '-id')
# gdatas = Guest.objects.all().order_by('-id')[0:2]
return render(request, 'list.html', {'gdatas':gdatas})
def InsertFunc(request):
return render(request, 'insert.html')
def InsertOkFunc(request):
if request.method == 'POST':
# print(request.POST.get('title'))
# print(request.POST['title'])
Guest(
title = request.POST['title'],
content = request.POST['content'],
# regdate = datetime.now()
regdate = timezone.now()
).save()
# 두가지 방식 모두 import는 필요하다
# return HttpResponseRedirect('/guest/select') # 추가 후 목록 보기
return redirect('/guest/select') # 추가 후 목록 보기
main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--html parsing-->
{{msg | safe}}
메뉴1 메뉴2 <a href="guest/select">미니 방명록</a>
</body>
</html>
list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
** 글 내용 **<p/>
<a href="/guest/insert">자료 추가</a>
<br>
<table border="1">
<tr><th>아이디</th><th>제목</th><th>내용</th><th>등록일</th></tr>
{% if gdatas %}
{% for g in gdatas %}
<tr>
<td>{{g.id}}</td>
<td>{{g.title}}</td>
<td>{{g.content}}</td>
<td>{{g.regdate}}</td>
</tr>
{% endfor %}
{% else %}
<tr>
<td colspan="4">글이 없어요</td>
</tr>
{% endif %}
</table>
</body>
</html>
insert.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
window.onload = function(){
document.getElementById("btnOk").onclick = confirmFunc;
document.querySelector("#btnShow").onclick = function(){
// alert('b');
document.location.href="/guest/select";
};
}
function confirmFunc(){
// alert('a');
if (frm.title.value === ""){
frm.title.placeholder = "제목을 입력하세요"
return false;
}
frm.submit();
}
</script>
</head>
<body>
<p>** 방명록 글 쓰기 **</p>
<form action="/guest/insertok" method="post" name="frm">{% csrf_token %}
<!-- onsubmit="return false" 버튼을 클릭했을때만 전송되게 설정 -->
<table>
<tr>
<td>제 목 : </td>
<td><input type="text" name="title" size="48" /></td>
</tr>
<tr>
<td>내 용 : </td>
<td><textarea name="content" cols="50" rows="5"></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="button" id="btnOk" value="등록하기"/>
<input type="button" id="btnShow" value="목록보기"/>
</td>
</tr>
</table>
</form>
</body>
</html>
'Django' 카테고리의 다른 글
django8 - DB, 표, CRUD, 페이징 (0) | 2022.10.18 |
---|---|
django7 - DB, multi-table (제조사, 상품 관리) (0) | 2022.10.18 |
django5 - DB (0) | 2022.10.17 |
django4 - session 예제(간이 쇼핑몰, 장바구니 기능) (0) | 2022.10.17 |
django3 - session (0) | 2022.10.17 |