본문 바로가기
수업(국비지원)/Django

[Django] 파일 업로드

by byeolsub 2023. 4. 27.

📌 join.html

{% extends "base1.html" %} {# 한줄주석#}
{% block content %}
<script type="text/javascript">
   function win_upload() {
	   var op = "width=500, height=500, left=50,top=150";
	   open("../picture/","",op); 요청url pricture
   }
</script>
<form action="../join/" name="f" method="post">
  {%  csrf_token  %}
 <input type="hidden" name="picture" value="" >
 <table><tr><td rowspan="4" valign="bottom">
   <img src="" width="100" height="120" id="pic"><br>
 <font size="1"><a href="javascript:win_upload()">사진등록</a></font>
 </td><th>아이디</th><td><input type="text" name="id"></td></tr>
 <tr><th>비밀번호</th><td><input type="password" name="pass"></td></tr>
 <tr><th>이름</th><td><input type="text" name="name"></td></tr>
 <tr><th>성별</th>
     <td><input type="radio" name="gender" value="1" checked>남
         <input type="radio" name="gender" value="2">여</td></tr>
<tr><th>전화번호</th>
    <td colspan="2"><input type="text" name="tel"></td></tr>
<tr><th>이메일</th>
    <td colspan="2"><input type="text" name="email"></td></tr>
<tr><td colspan="3"><input type="submit" value="회원가입"></td></tr>
 </table></form>
{% endblock %}

📌 views.py picture 추가부분

def picture(request) :
    if request.method != 'POST' :
        return render(request,'member/pictureform.html')
    else :
        pass

BASE_DIR/file/picture 폴더 생성 : 이미지 업로드 폴더 

📌 settings.py 내용 추가

"""
Django settings for study1 project.

Generated by 'django-admin startproject' using Django 4.1.4.

For more information on this file, see
<https://docs.djangoproject.com/en/4.1/topics/settings/>

For the full list of settings and their values, see
<https://docs.djangoproject.com/en/4.1/ref/settings/>
"""

from pathlib import Path

# 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/4.1/howto/deployment/checklist/>

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-zskt0=@(+^8=+-&_+_!!3fbt=_hyw&+0!@-epor%4!vo&72@tv"

# 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",
    "member",
]

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 = "study1.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR/'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 = "study1.wsgi.application"

# Database
# <https://docs.djangoproject.com/en/4.1/ref/settings/#databases>
'''
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3", 
    }
}
'''

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": 'kic',
        "USER": 'kic',
        "PASSWORD": '1234',
        "HOST": 'localhost',
        "PORT": '3307'
    }
}

# Password validation
# <https://docs.djangoproject.com/en/4.1/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/4.1/topics/i18n/>

# LANGUAGE_CODE = "en-us"
LANGUAGE_CODE = "ko-kr"

# TIME_ZONE = "UTC"
TIME_ZONE = "Asia/Seoul"

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# <https://docs.djangoproject.com/en/4.1/howto/static-files/>

STATIC_URL = "/static/" # css, js 파일의 위치

# Default primary key field type
# <https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field>

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

import os
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]  # css, js 파일의 위치 폴더 설정

**# 파일 업로드 폴더, URL설정 
MEDIA_URL = "/file/"
MEDIA_ROOT = os.path.join(BASE_DIR,"file")**

📌 urls.py 내용 추가

"""study1 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    <https://docs.djangoproject.com/en/4.1/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,include
**from django.conf import settings
from django.conf.urls.static import static**

# 127.0.0.1:8000/member/login/
urlpatterns = [
    path("admin/", admin.site.urls),
    path("member/", include("member.urls")),
]

**# 파일 업로드 위치 설정
urlpatterns += \\
    static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)**

 

'수업(국비지원) > Django' 카테고리의 다른 글

[Django] 게시판 생성  (0) 2023.04.27
[Django] 비밀번호 수정  (0) 2023.04.27
[Django] 회원탈퇴  (0) 2023.04.27
[Django] 회원가입, 로그아웃, 업데이트  (0) 2023.04.27
[Django] main페이지 생성  (0) 2023.04.27