1. Model (user)

- 기존 user에서 필드를 추가해주고 싶어서 AbstractUser를 상속해주었다!

  - 단, settings에서 따로 설정해줄 것 :

# 커스텀 유저 모델을 생성하기 위한 셋팅
AUTH_USER_MODEL = 'member.User'

- 처음에 추가한 필드 : 소개, 프로필 사진, 전화번호, 생일, 웹사이트

- 이후 기능구현을 위해 추가한 필드 : 팔로워, 사진 갯수

  - followers : 팔로우 기능을 구현하기 위해 ManyToManyField를 이용함.

from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models

# User : 기본 user를 상속하여 추가 field로 구성
# cf. blank=True :빈 채로 저장 & null=True : null 값으로 저장


class User(AbstractUser):

    bio = models.TextField(null=True, blank=True) # 소개
    photo = models.ImageField(upload_to='user/%Y/%m/%d', null=True, blank=True) # 프로필 사진
    phone_number = models.CharField(null= True, blank=True, max_length=20) # 전화번호
    date_of_birth = models.DateField(null=True, blank=True) # 생일
    website = models.CharField(null=True, blank=True, max_length=100) # 웹사이트
    followers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followings') # follow 기능을 위해 추가함.
    # ManyToManyField -> related_name : 정참조하고 있는 클래스의 인스턴스에서 거꾸로 호출(역참조 할지를 정해주는 이름)
    photo_cnt = models.IntegerField(default=0)

2. URLs

- view와 template을 이어주는 역할!

from django.conf.urls import url
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url('join/', views.create_user, name="join"),
    url('login/', views.sign_in, name="login"),
    url('logout/', views.sign_out, name='logout'),
    url('delete/',views.delete, name='delete'),
    url('change_password/',views.change_password,name='change_password'),
    url('profile_update/',views.profile_update, name='profile_update'),
    path('people/<str:username>/', views.peoplePage , name="people"),
    path('follow/<str:username>/',views.follow, name='follow'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

3. View

- 각 함수마다 기능 해당하는 url의 기능 수행

# 절대 경로 설정을 위해 추가
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from photo.models import Photo

from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash, get_user_model
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django.views.generic import ListView
from rest_framework.generics import get_object_or_404

from .forms import UserCreationForm, ProfileForm
from .models import User

def change_password(request):
    if request.method == "POST":
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, '패스워드가 성공적으로 업데이트 되었습니다.')
            return redirect('index') # 다음 url로 이동한다.
        else:
            messages.error(request,"다음 에러를 확인해주세요.")
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'registration/change_password.html',{'form':form})

# 계정 삭제 기능
def delete(request):
    if request.method == "POST":
        request.user.delete()
        return redirect('index')
    else:
        return render(request, 'registration/delete.html')



# New User Registration(회원가입 기능)
def create_user(request):
    if request.method == 'POST':
        try:
            username = request.POST['username']
            email = request.POST['email']
            password = request.POST['password1']
            new_user = User.objects.create_user(username, email, password)
            new_user.save()
            return render(request, 'registration/signup_done.html', {'message': '회원가입이 완료되었습니다.'})
        except:
            return render(request, 'registration/signup_done.html', {'message': '회원이 이미 있음'})
    else:
        form = UserCreationForm()
        return render(request, 'registration/signup.html', {'form': form})


# 로그아웃 기능
def sign_out(request):
    logout(request)
    return render(request, 'home/base.html')

# 로그인 기능
def sign_in(request):
    if request.method == 'POST':
        # 유저 (username, password)로 인증
        user = authenticate(request, username=request.POST.get('username', ''),
                            password=request.POST.get('password', ''))
        if user is not None:
            login(request, user) 
            return render(request, 'registration/signup_done.html', {'message': "로그인 되었습니다."})
        else:
            return render(request, 'registration/signup_done.html', {'message': "로그인에 실패하였습니다."})
    else:
        # 로그인 폼 생성
        form = AuthenticationForm()
        return render(request, 'registration/login.html', {'form': form})
        
# profile update
def profile_update(request):
    user = request.user
    if request.method == 'POST':
        profile_form = ProfileForm(request.POST, request.FILES, instance=user)
        if profile_form.is_valid(): # 단, form이 valid하지 않으면 저장되지 않는다. (예) 생일의 형식이 안맞을 때
            profile_form.save()
        return redirect('people', request.user.username)
    else:
        profile_form = ProfileForm(instance=user)
    return render(request, 'profile/profile_update.html', {'profile_form': profile_form})



# 게시물의 작성자의 username을 통해 user 페이지에 접근하기
def peoplePage(request,username):
    person = get_object_or_404(User, username=username)
    # 작성자가 username인 photo를 전달하기
    photo_list = Photo.objects.filter(Q(user=person))
    context={}
    context['people']=person
    context['object_list']= photo_list

    return render(request, "profile/people.html",context)

# 팔로우 기능 
def follow(request, username):
    people = get_object_or_404(get_user_model(), username=username)
    if request.user in people.followers.all():
        # people을 unfollow하기
        people.followers.remove(request.user)
    else:
        # people을 follow하기
        people.followers.add(request.user)
    return render(request, "profile/people.html",{'people': people})


WRITTEN BY
choco-songyi

,

유저의 종류가 다양한데, 어떤 것을 사용해야 할지 고민이 되어서 찾아보았다!

- abstractUser는 장고의 내장 인증 기능을 이용하되, 특정 속성을 추가하고 싶을 때 사용한다! 

 

Conclusions

Alright! We’ve gone through four different ways to extend the existing User Model. I tried to give you as much details as possible. As I said before, there is no best solution. It will really depend on what you need to achieve. Keep it simple and choose wisely.

  • Proxy Model: You are happy with everything Django User provide and don’t need to store extra information.
  • User Profile: You are happy with the way Django handles the auth and need to add some non-auth related attributes to the User.
  • Custom User Model from AbstractBaseUser: The way Django handles auth doesn’t fit your project.
  • Custom User Model from AbstractUser: The way Django handles auth is a perfect fit for your project but still you want to add extra attributes without having to create a separate Model.

simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

 

How to Extend Django User Model

The Django’s built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot ofdevelopment and testing effort. It fits ...

simpleisbetterthancomplex.com

 


WRITTEN BY
choco-songyi

,

장고 프레임워크는 MVT 모델로 이루어있는데, Django에 내장된 User를 이용하면 model을 따로 만들어줄 필요가 없다.

  • 대신 forms.py를 만들어서 로그인, 회원가입 폼을 만들어야 한다.

1. forms.py

  • UserCreateForm은 django.contrib.auth.forms의 UserCreateForm 에서 오버라이딩한 클래스이다.
class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("email", "username")

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

    # Help메시지가 표시되지 않도록 수정
    def __init__(self, *args, **kwargs):
        super(UserCreateForm, self).__init__(*args, **kwargs)

        for fieldname in ['username', 'password1', 'password2']:
            self.fields[fieldname].help_text = None

2. urls.py

  • views.py와 template의 url을 연결해주는 역할을 한다.
from django.conf.urls import url
from . import views

urlpatterns = [
    url('join/', views.create_user, name="join"),
    url('login/', views.sign_in, name="login"),
    url('logout/', views.sign_out, name='logout'),
]

3. views.py

  • urls.py에서 지정한 url과 연결되는 메소드 - 회원가입, 로그인, 로그아웃 기능- 을 구현한다.
  • 대부분의 기능이 기존 authentication에 함수로 내장되어 있어서 잘 사용하기만 하면 된다.
    • 회원가입
    • 로그인/로그아웃
from django.shortcuts import render
# Create your views here.

from .forms import UserCreateForm 
from django.contrib.auth.models import User 
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm

def create_user(request):
    if request.method == 'POST':  
        try:  
            username = request.POST['username']
            email = request.POST['email']
            password = request.POST['password1']
            new_user = User.objects.create_user(username, email, password) 
            new_user.save()
            return render(request, 'registration/signup_done.html', {'message': '회원가입이 완료됨'})
        except:
            return render(request, 'registration/signup_done.html', {'message': '회원이 이미 있음'})
    else:
        form = UserCreateForm()
        return render(request, 'registration/signup.html', {'form': form})
def sign_out(request):
    logout(request)
    return render(request, 'home/base.html')


def sign_in(request):
    if request.method == 'POST':
        user = authenticate(request, username=request.POST.get('username',''), password=request.POST.get('password',''))
        if user is not None:
            login(request, user)
        return render(request, 'registration/login.html', {'message': "로그인 되었습니다."})
    else:
        form = AuthenticationForm()
        return render(request, 'registration/login.html', {'form': form})

4. template

  • 넘어가는 메뉴(home/navbar.html)
<div class="dropdown-menu">
    <a class="dropdown-item" href="{% url 'login' %}">Login</a>
    <a class="dropdown-item" href="{% url 'join' %}">Register</a>
</div>
  • registration/login.html
{% extends 'home/base.html' %}
{% block content %}
<div id="content-wrapper">
    <div class="container-fluid">
        <div>
            <h1>Login</h1>
        </div>
        <form method="post" action="{% url 'login' %}">
            {% csrf_token %}
            {{ form.as_p }}
            <div><button type="submit", class="btn btn-success", value="save">Submit Login</button>
            </div>
        </form>
        <a href="{% url 'index' %}"><button type="button" class="btn btn-primary">Back to List</button></a>
    </div>
</div>
{% endblock content %}
  • registration/signup.html
{% extends 'home/base.html' %}
{% block content %}
<div id="content-wrapper">
    <div class="container-fluid">
        <div>
            <h1>New User Registration</h1>
        </div>
        <form method="post" action="{% url 'join' %}">
            {% csrf_token %}
            {{ form.as_p }}
            <div><button type="submit", class="btn btn-success", value="save">Submit Registration</button>
            </div>
        </form>
        <a href="{% url 'index' %}"><button type="button" class="btn btn-primary">Back to List</button></a>
    </div>
</div>
{% endblock content %}

5. 결과 화면

  • 회원가입

  • 회원가입 후

  • 로그인

  • 로그인 후

+ 참고로...

유저가 추가된 것을 localhost:8000/admin에서 admin계정을 통해서 확인할 수 있다.

  • 이전에 test로 만든 계정들을 확인할 수 있다.

  • 추가할 기능 : 개인 계정 업데이트 및 관리
  • 앞으로의 방향 : 유저에 다양한 필드를 갖추기 위해서는 기본적으로 제공되는 user에 한계점이 보여서 다른 user를 사용해서 구현할 것.

- 참고 : m.blog.naver.com/PostView.nhn?blogId=rudnfskf2&logNo=221377212957&proxyReferer=https:%2F%2Fwww.google.com%2F

[

20. Django authentication를 활용한 회원가입 구현

이번 포스트에서는 장고에서 자체적으로 내장하고 있는 authentication를 활용하여 회원가입을 구현하는 것...

blog.naver.com

](https://m.blog.naver.com/PostView.nhn?blogId=rudnfskf2&logNo=221377212957&proxyReferer=https:%2F%2Fwww.google.com%2F)


WRITTEN BY
choco-songyi

,

* 오류 원인 : Git pull을 할 때, 다른 팀원의 앱과 Merge를 하게되어서 DB가 꼬이게 됨

* 발생한 오류 내용

django.db.utils.DatabaseError: database disk image is malformed

* 수정 방법

더보기

1. db.sqlite3 파일과 migrations 파일을 모두 지운다.

2. 아래 두 가지를 해준다.

python manage.py makemigrations
python manage.py migrate

 

* 결과 : 서버가 실행이 됨.

* 보완할 점 : migrate 파일은 다시 생성이 되지 않음. (나오지 않는 url이 있음) 

django.db.utils.OperationalError: no such table: photo_photo

... 진행 중...

* 수정한 것: makemigrations에 [앱이름]을 붙임!!

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py makemigrations photo
Migrations for 'photo':
  photo\migrations\0001_initial.py
    - Create model Photo

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, authtoken, contenttypes, photo, sessions
Running migrations:
  Applying photo.0001_initial... OK

* 결과 : ok...!!


WRITTEN BY
choco-songyi

,

왜? db를 확인하고 싶어서 localhost:8080/admin으로 접속했는데 계정 정보를 모름!

1. django shell에 들어가서 계정 정보를 확인한다.

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py shell
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> superusers = User.objects.filter(is_superuser=True)
>>> superusers
<QuerySet [<User: kho903>]>
>>>

 

2. 패스워드를 바꾸어준다.

- 너무 쉬우면 계속 다시 하라고 함.

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py changepassword kho903
Changing password for user 'kho903'
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Password:
Password (again):
Password changed successfully for user 'kho903'

3. localhost:8000/admin/auth/user에서 확인해보기

- /admin 에서 로그인

 

 

- test로 회원가입한 user 두 명이 있는 것을 확인할 수 있음.

 

*** 새로 superuser 계정을 만들어줄 수도 있음.

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py createsuperuser
Username (leave blank to use 'user'): mink
Email address:
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

WRITTEN BY
choco-songyi

,

0. 앱 실행하기 위해서!

- 앱을 생성한다.

django-admin startapp 앱이름

 

- 전체 urls.py와 해당앱의 urls.py에 추가한다.

urlpatterns = [
    # 새로만들어준 app의 url 기본 path설정해주기
    path('member/', include('member.urls')),
   ...
]

- 앱의 urls.py는 없으므로 새로 만들어줄 것! (views.py의 method와 연결해준다.)

from django.urls import path
from .views import SignUp,Login

urlpatterns = [
    path('join/',SignUp.as_view(), name="join"), # name을 붙이는 이유는 html에서 불러오기 위함.
    path('login/',Login.as_view(), name="login")
]

- settings에 추가한다.

INSTALLED_APPS = [
  	...
    '{앱이름}.apps.{클래스이름}Config' # 앱 추가
]

- model 설정하기

 

 

* 데이터베이스를 이용하기 위해서 사용하는 명령어 두 가지 

  makemigrations, migrate

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py makemigrations
Migrations for 'member':
  member\migrations\0001_initial.py
    - Create model Member

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, authtoken, contenttypes, member, sessions
Running migrations:
  Applying member.0001_initial... OK

 

- views에서 작동하는 코드를 작성한다.

- template 에서 html 코드를 작성한다.

 

- 로그인 기능을 위해 django-rest-auth를 설치한다. (결과적으로는 필요하지는 않았다.)

(venv) C:\Users\user\PycharmProjects\DjangoProject\insta>pip install django-rest-auth
Collecting django-rest-auth
  Downloading django-rest-auth-0.9.5.tar.gz (53 kB)
     |████████████████████████████████| 53 kB 777 kB/s
Requirement already satisfied: Django>=1.8.0 in c:\users\user\pycharmprojects\instagram\venv\lib\site-packages (from django-rest-auth) (3.1.2)
Requirement already satisfied: djangorestframework>=3.1.3 in c:\users\user\pycharmprojects\instagram\venv\lib\site-packages (from django-rest-auth) (3.12.1
)
Requirement already satisfied: six>=1.9.0 in c:\users\user\pycharmprojects\instagram\venv\lib\site-packages (from django-rest-auth) (1.15.0)
Requirement already satisfied: pytz in c:\users\user\pycharmprojects\instagram\venv\lib\site-packages (from Django>=1.8.0->django-rest-auth) (2020.1)
Requirement already satisfied: asgiref~=3.2.10 in c:\users\user\pycharmprojects\instagram\venv\lib\site-packages (from Django>=1.8.0->django-rest-auth) (3.
2.10)
Requirement already satisfied: sqlparse>=0.2.2 in c:\users\user\pycharmprojects\instagram\venv\lib\site-packages (from Django>=1.8.0->django-rest-auth) (0.
4.1)
Using legacy 'setup.py install' for django-rest-auth, since package 'wheel' is not installed.
Installing collected packages: django-rest-auth
    Running setup.py install for django-rest-auth ... done
Successfully installed django-rest-auth-0.9.5

 

 

- 참고 :  wave1994.tistory.com/65

 

파이썬(Django) :: 회원 가입 및 로그인 API 구현

장고(Django)를 이용하여 간단하게 회원가입과 로그인 기능을 구현한 API에 패스워드 암호화 및 토큰 기능을 추가해보았다.  * 이전에 구현한 코드 https://wave1994.tistory.com/57 # models.py models.py 파일..

wave1994.tistory.com

 


WRITTEN BY
choco-songyi

,

[문제] 서버를 작동시켜보자

python manage.py runserver

- 결과  :

System check identified no issues (0 silenced).
October 23, 2020 - 14:49:15
Django version 3.1.2, using settings 'insta.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\user\PycharmProjects\Instagram\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\user\PycharmProjects\Instagram\venv\lib\site-packages\django\core\management\commands\runserver.py", line 139, in inner_run
    run(self.addr, int(self.port), handler,
  File "C:\Users\user\PycharmProjects\Instagram\venv\lib\site-packages\django\core\servers\basehttp.py", line 206, in run
    httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
  File "C:\Users\user\PycharmProjects\Instagram\venv\lib\site-packages\django\core\servers\basehttp.py", line 67, in __init__
    super().__init__(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 452, in __init__
    self.server_bind()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\wsgiref\simple_server.py", line 50, in server_bind
    HTTPServer.server_bind(self)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\http\server.py", line 140, in server_bind
    self.server_name = socket.getfqdn(host)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\socket.py", line 756, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 0: invalid start byte
​

[해결책]

 

1. 먼저는 Sqlite3를 설치하자.

- 설치 및 환경변수 설정

- 결과 : 아래 명령어가 수행됨. 

python manage.py dbshell

[진짜 해결책]

- runserver 시 인코딩 문제 : 컴퓨터 이름이 한글로 되어 있어서 그런 것이었음..!!!

- 컴퓨터의 이름을 바꿔주고 재부팅하고 나서 실행하니 해결됨!!!


WRITTEN BY
choco-songyi

,

1. 첫 번째 뷰 작성하기

  • {api명}/views
  • 가장 단순한 형태의 뷰
from django.http import HttpResponse

def index(request):
	return HttpResponse("Hello world")
    
  • 뷰를 호출하려면 이와 연결된 URL이 필요하기 때문에 URLconf가 사용됩니다.

2. urls.py 파일 만들어주기

  • 해당 api 디렉토리에서 URLconf를 생성하려면 urls.py라는 파일이 만들어주어야 합니다.
  • {api명}/urls
from django.urls import path
from . import views

urlpatterns = [
	path('', views.index, name='index')
]

3. 최상위 URLconf에서 api의 urls 모듈을 바라볼 수 있게 만들어주기

  • {프로젝트명}/urls
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
	path( {api명}+'/', include( {api명}+'.urls')), 
    	path('admin/', admin.{프로젝트명}.urls),
]
  • include()함수는 다른 URLconf들을 참조할 수 있게 도와준다. 
  • Django가 이 함수를 만나면, URL의 그 시점까지 일치하는 부분을 잘라내고, 남은 문자열 부분을 후속 처리를 위해 include된 URLconf로 전달합니다. 

 

 

참고 : docs.djangoproject.com/ko/3.1/intro/tutorial01/

 

첫 번째 장고 앱 작성하기, part 1 | Django 문서 | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 


WRITTEN BY
choco-songyi

,

1. pycharm 에서 new project를 만들어준다.

2. Alt+F12 (단축키)로 파이참 터미널을 열어서 장고 프로젝트를 생성한다.

django-admin startproject (프로젝트명)
  • 'django-admin'은 내부 또는 외부 명령, 실행할 수 있는 프로그램 또는 배치 파일이 아닙니다.' 가 뜨게 되면, django를 다시 설치해서 똑같은 명령어를 입력한다.
  • 그러면 다음과 같은 디렉토리가 생성된다. 

- __init__.py : 아무것도 들어있지 않은 빈 파일, 파이썬에게 현재 폴더가 파이썬 파일임을 알려준다.

- settings.py : 장고 프로젝트의 셋팅과 설정이 포함된 파일 

- urls.py : 장고 프로젝트 안의 URL을 선언하는 곳 

- wsgi.py : WSGI 프로토콜을 사용하는 웹서버가 프로젝트의 페이지를 보여주기 위해 먼저 사용하는 파일 

 

 

 

 

 

 

 

 

3. Django App 만들기

cd {프로젝트명}
django-admin startapp {앱이름}

4. 서버 구동하기

python manage.py runserver

- 결과 : 

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 22, 2020 - 15:46:15
Django version 3.1.2, using settings 'insta.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

- 고치기

python manage.py makemigrations
python manage.py migrate

- 결과 :

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

- 다시 실행해도 오류 발생!

(venv) C:\Users\user\PycharmProjects\DjangoTest\insta>python manag
e.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
October 22, 2020 - 15:47:51
Django version 3.1.2, using settings 'insta.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:

- Why? 데이터베이스 호환 문제로 나중에 연결해서 해결할 것

 

참고 : https://7stocks.tistory.com/58

 

Windows + Pycharm + Django 설치부터 시작까지

서비스하기 전까지는 Linux가 아닌 Windows 또는 Mac 환경에서 작업하는 것이 편하다. 여기서는 윈도우에서 편하게 개발하기 위한 Back-End 환경을 조성하는 방법을 알아보자. * 개발 환경 OS: Windows 10

7stocks.tistory.com

 


WRITTEN BY
choco-songyi

,

Windows8 에서 Django 프레임워크를 설치하기 위해서

1. python 을 설치한다.

- 라이브러리들을 사용할 수 있는 Anaconda를 설치한다.

 

2. Anaconda powershell propmt에서 Django를 설치한다.

pip install Django

- 버전이 안맞아서 중간에 설치 오류가 나기 때문에 python 버전을 업그레이드 해준다.

python -m pip install --upgrade pip

- Restful 웹을 만들기 위해 rest-framework도 함께 설치해준다.

 pip install django-rest-framework

 


WRITTEN BY
choco-songyi

,