1. Django DB 설정
1. DB 데이터 필드 만들어주기
app 폴더에 models.py 에 들어간다
class 를 만들어주고
클레스명(models,model):
이제 컬럼 속성을 정해준다
admin 에 추가해준다
2. 데이터 필드 적용해주기
python manage.py makemigrations 엡이름
python manage.py migrate #적용해주기
이제 관리자 페이지를 가본다
<관리자 페이지 이미지 넣기>
2. html에 적용하기
1. view 에서 모델 가져오기
from models import Coffee
coffee_DB = Coffee.objects.all() # 이게 다가져오는거
2. html에 적용하기
<코드 넣어주기>
<이미지 넣어주기>
2. Form 설정
1. forms.py 생성해주기
forms.py 추가해준다
파일을 작성해준다
class 를 만들어 받을 형식을 정해준다
<코드 넣어주기>
2. view에 적용하기
view에 폼을 가져와 적용해준다
3. html에 적용하기
<form method= "POST">{% csrf_token %}
{{ coffee_form.as_p}}
<button type="submit"> save</>
</>
3. Form 데이터 DB에 저장하기
1. view 설정
request 데이터를 확인하고
form을 DB에 저장한다
영상은 나중에 올릴꼐요 .. 정리가 안됫음
원하시면 뎃글 달아주세요 아마 그럼 작업 할지도 몰라요
코드만 올리겟음
수정해야될게 많음...
<<<<web_dj>>>>>
<setting.py>
"""
Django settings for web_dj project.
Generated by 'django-admin startproject' using Django 3.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-%#s#d88dg-ji7!1&n81rhg=4+&mh5%_=@+lt$8ginp7ii$3$ba'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'web_dj.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR,"main","templates")
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'web_dj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'main','static'),
)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
<urls.py>
"""web_dj URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from main.views import main
urlpatterns = [
path('', main),
path('admin/', admin.site.urls),
]
<<<<<main>>>>>
<<<templates>>>
<index.html>
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fullscreen Overlay Responsive Navigation Menu</title>
<link rel="stylesheet" href="{% static 'style.css' %}" />
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js"></script>
<script defer src="{% static 'script/main.js' %}"></script>
</head>
<body>
<!-- main -->
<div class="container">
<div class="menu-close">
<div class="menu-close-img"><img src="{% static 'close-icon.png' %}" alt="" /></div>
</div>
<div class="hr"></div>
<div class="menu">
<div class="menu-left">
<div class="menu-links">
<div class="menu-link">
<a id="unclick" href="#">Home <span>01</span></a>
</div>
<div class="menu-link">
<a id="clicked" href="#">cafe <span>02</span></a>
</div>
<div class="menu-link">
<a id="unclick" href="#">DATA <span>03</span></a>
</div>
<div class="menu-link">
<a id="unclick" href="#" >Django <span>04</span></a>
</div>
</div>
</div>
<div class="menu-right">
<div class="contact">
<div class="mail">
<div><span class="title">Contact</span><br /><br /></div>
<div><span class="info">name : 이경근</span><br /></div>
<div><span class="info">chuimi : lol</span><br /></div>
<div><span class="info">E-Mail : liebespaar93@gmail.com</span><br /></div>
</div>
<div class="socials">
<div><span class="title">Follow Us</span><br /><br /></div>
<div><span class="info">git : <a id="href_info" href="https://github.com/liebespaar93">https://github.com/liebespaar93 </a></span><br /><br /></div>
<div><span class="info">blog :<a id="href_info" href="https://topknell.tistory.com/">https://topknell.tistory.com/</a></span></div>
</div>
</div>
</div>
</div>
</div>
<div class="menu-open">menu</div>
<!-- cafe -->
<div class ="cafe">
<div class="containar">
<table id="cafe_tb">
<thead>
<tr id='cols'>
<td id='td1'>id</td>
<td id='td2'>name</td>
<td id='td3'>price</td>
</tr>
</thead>
<tbody>
{% for coffee in coffee_list %}
<tr id="uncheck" name='{{coffee.id}}'>
<td>{{forloop.counter}} {{coffee.id}}</td>
<td>{{coffee.name}}</td>
<td>{{coffee.price}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="control">
<div class='btn'>
<input type="button" id="view" value="보기">
<input type="button" id="create" value="추가">
<input type="button" id="update" value="편집">
<input type="button" id="delet" value="삭제">
</div>
</div>
</div>
<div class="clickdataboard">
<form name="sub1" method ="POST"> {% csrf_token %}
<div class="clickdata" id="clickdata" >
{{ coffee_form.as_p }}
<input type="text" readonly id="cafe_id" name="cafe_id" style="display: none;" value="0">
<input type="submit" id="submit_coffee" name="view" value="확인">
<input type="button" id="maker" name="close" value="닫기">
</div>
</form>
</div>
</div>
</body>
</html>
<<<static>>>
이미지 2개있음
<style.css>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100vh;
font-family: "Bridge Head Con Medium";
}
.menu {
position: fixed;
width: 100%;
height: 100vh;
display: flex;
pointer-events: none;
}
.hr {
position: fixed;
left: 50%;
width: 6px;
height: 100vh;
background-color: #fff;
z-index: 1;
transform: scaleY(0);
}
/* cafe */
.cafe {
width: 100%;
height: 100%;
background-image: url("cafe/coffee_bg.jpg");
background-position: center;
background-size: cover;
vertical-align: middle;
}
/* cafe table */
.containar { padding: 10px; vertical-align: middle;width: 100%; height: 100%;display:flex;}
.containar table {margin-left:20%;margin-right: 10px;margin-top: 42vh;width: 50%;text-align: right; line-height: 1.5;}
.containar table tr {cursor: pointer; transition: 1.s ease-in-out;}
.containar table tr:hover {background-color: rgba(255, 255, 255, 10%);}
.containar table thead td{padding: 10px; font-family: 'knell'; vertical-align: top;background-color: rgba(0, 0, 0, 70%);color:#cccccc; border-bottom: 3px solid ; border-top-left-radius: 20px;border-top-right-radius: 4px;}
.containar table tbody td{padding: 10px; border-bottom: 1px solid;color:#cccccc;background-color: rgba(0, 0, 0, 20%);}
.containar table tbody #check {background-color: rgba(255, 255, 255, 25%);}
/* control */
.control {display:flex;margin-top: 40vh;margin-right: 20%;}
.control .btn input {display: block; border: 1px solid #cccccc;width: 130px; height: 40px; font-family: 25px; background-color: rgba(0, 0, 0, 50%);color:#cccccc;border-radius: 40px;margin:20px;transition: 1.0s ease; box-shadow: 3.3s ease ;}
.control .btn input:hover {background-color: rgba(255, 255, 255, 80%);color:#222222}
.clickdataboard {position: absolute; left:50%;transform: translateX(-50%);top:40%; display: none}
.clickdata {border: 1px solid; padding: 10px; border-radius: 10px;width: 120px; background-color: rgba(0, 0, 0, 80%); width: 250px; }
.clickdata label {color: white;}
.clickdata input {text-align: center;margin-bottom: 10px;border-radius: 10px; width: 90%;color: rgba(0, 0, 0, 80%);}
.clickdata input#maker {display: block;width: 40%; border: 1px solid white;background: black;color: white;transition: 1.0s ease, box-shadow 3.3s ease;}
.clickdata input#maker:hover {background-color: white; color: black;}
/* menu */
.menu-left,
.menu-right {
position: fixed;
width: 50%;
height: 100vh;
background: #000;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
z-index: -1;
}
.menu-left {
left: -50%;
}
.menu-right {
right: -50%;
}
.menu-right .socials #href_info { color: white; text-decoration: none;}
.menu-link a {
text-decoration: none;
color: #fff;
font-size: 100px;
}
.menu-link a#clicked::before {
display: block;
position: relative;
content: "";
background-image: url("brush-stroke.png");
background-size: 100%;
background-repeat: no-repeat;
top: 80px;
left: 0;
height: 40px;
width: 240px;
}
.menu-link a span {
font-family: "Bigilla";
font-size: 24px;
}
.contact .title {
font-size: 80px;
}
.contact .info {
font-family: Helvetica, sans-serif;
font-weight: lighter;
}
.mail {
margin-bottom: 60px;
}
.menu-close {
z-index: 2;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
opacity: 1;
}
.menu-close-img {
width: 140px;
height: 140px;
border-radius: 100%;
border: 10px solid #000;
}
img {
width: 100%;
}
.menu-open {
position: fixed;
z-index: 1;
top: 0;
right: 0;
padding: 2rem;
cursor: pointer;
font-size: 20px;
color: #000;
}
@media (max-width: 900px) {
.menu-right {
display: none;
}
.menu-left {
width: 100%;
}
.menu-close {
position: fixed;
top: 10%;
left: 80%;
transform: translate(-50%, -50%);
margin: 40px;
}
.hr {
display: none;
}
img {
width: 40%;
}
}
<<cafe>>
이미지있음
<<script>>
<main.js>
/* main menu */
var togl = 1
tl = new TimelineMax({ paused: true });
tl.to(".menu-left", 1, {left: "0%", ease: Expo.easeInOut, });
tl.to(".menu-right", 1, {right: "0%", ease: Expo.easeInOut, }, "-=1");
tl.staggerFrom(".menu-links > div", 0.8, { y: 100, opacity: 0, ease: Expo.easeOut, }, "0.1", "-=0.4" );
tl.staggerFrom( ".mail > div, .socials > div", 0.8, { y: 100, opacity: 0, ease: Expo.easeOut, }, "0.1", "-=1" );
tl.from( ".menu-close", 1, { scale: 0, opacity: 1, ease: Expo.easeInOut, }, "-=1" );
tl.to( ".hr", 0.4, { scaleY: 1, transformOrigin: "0% 50%", ease: Power2.ease, }, "-=2");
tl.reverse();
$(document).on("click", ".menu-open", function () {
tl.reversed(!tl.reversed());
$('.menu').css('pointer-events','all')
togl = 1
});
$(document).on("click", ".menu-close", function () {
tl.reversed(!tl.reversed());
$('.menu').css('pointer-events','none')
togl = 0
});
/* click menu option */
$('.menu-link').on('click', 'a', function(){
$(clicked).prop('id','unclicked');
this.id = 'clicked';
if (this.text == "cafe 02"){
$('.cafe').css('display','block')
}
else{
$('.cafe').css('display','none')
}
});
/* width resize */
$(window).resize(function (){
// width값을 가져오기
if (togl == 0){
$('.menu-left').css('left','-50%');
$('.menu-right').css('right','-50%');
}
});
/* cafe maker */
$('.btn').on('click','input', function(){
cafe_click = this.id;
$('#submit_coffee').prop('name',cafe_click);
if (cafe_click == "delet"){
if (document.getElementById('check')){
document.getElementById("submit_coffee").click();
}
}
if (cafe_click == "create" ){
$(".clickdataboard").css('display','block');
}
else if (cafe_click == "update" && document.getElementById('check')){
$(".clickdataboard").css('display','block');
}
else{
$(".clickdataboard").css('display','none');
}
});
/* table check */
var table = document.getElementById('cafe_tb'),rIndex;
for (var i = 0; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
console.log(this.getAttribute('name'));
document.getElementById('cafe_id').value = this.getAttribute('name');
document.getElementById('id_name').value = this.cells[1].innerHTML;
document.getElementById('id_price').value = this.cells[2].innerHTML;
if (document.getElementById('check')){
document.getElementById('check').id = "uncheck";
}
this.id ="check";
}
}
/* close box */
$("#maker").click(function(){
$(".clickdataboard").css('display','none')
});
<admin.py>
from django.contrib import admin
from .models import Coffee
# Register your models here.
admin.site.register(Coffee)
<apps.py>
from django.apps import AppConfig
class MainConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'main'
<views.py>
from django.shortcuts import render
from .models import Coffee
from .froms import CoffeeForm
# Create your views here.
def main(request):
coffee_DB = Coffee.objects.all()
if request.method == "POST":
# cafe post 처리
print("requw 데이", request.POST)
coffeeform = CoffeeForm(request.POST)
if request.POST.get('view'):
print('view')
elif request.POST.get('create') and coffeeform.is_valid():
form = CoffeeForm(request.POST)
if form.is_valid():
form.save()
elif request.POST.get('update'):
print('udate')
cofe = Coffee.objects.get(id=request.POST.get('cafe_id'))
form = CoffeeForm(request.POST,instance= cofe)
if form.is_valid():
form.save(commit=True)
elif request.POST.get('delet'):
print('delet')
cofe = Coffee.objects.get(id=request.POST.get('cafe_id'))
cofe.delete()
coffeeform = CoffeeForm()
return render(request,"index.html", {"coffee_list":coffee_DB, "coffee_form":coffeeform })
<froms.py>
from django import forms
from .models import Coffee
class CoffeeForm(forms.ModelForm):
class Meta:
model = Coffee
fields = '__all__'
<model.py>
from django.db import models
# Create your models here.
class Coffee(models.Model):
def __str__(self):
return self.name
name = models.CharField(default="",max_length=30, null=False, unique=True)
price = models.IntegerField(default=0)
'Programmers > 데브코스 인공지능' 카테고리의 다른 글
[프로그래머스 스쿨 AI] Weak 6 머신러닝이란 1 (0) | 2021.05.28 |
---|---|
[프로그래머스 스쿨 AI] Weak 5 Django + uwsgi+ nginx + aws 완전 삭제후 따라해보기 드뎌! 배포 됫다 (0) | 2021.05.21 |
[프로그래머스 스쿨 AI] Weak 5 django (0) | 2021.05.17 |
[프로그래머스 스쿨 AI] Weak 4 미션들 (0) | 2021.05.17 |
[프로그래머스 스쿨 AI] Weak 4 EDA (0) | 2021.05.13 |