로컬에서 잘되던게 aws에 배포후 특정 템플릿을 부르려고 하면 404 not found 나 django Server Error (500)가 발생하는 현상이 일어났다


한참을 헤매고나서


보니 템플릿 html파일 중 메소드 호출이 안되는거 같았다 로컬에서는 잘 되었으나 


문제가 된 부분은 페이스북과 트위터 공유부분이었는데

<a target='_blank' href="https://twitter.com/home?status={{obj.get_share_message|safe }}">
<i class="fa fa-twitter-square fa-3x" aria-hidden="true"></i>
</a>
<a target='_blank' href="https://www.facebook.com/sharer/sharer.php?u={{obj.get_share_link }}">
<i class="fa fa-facebook-square fa-3x" aria-hidden="true"></i>
</a>

여기에서{{obj.get_share_message|safe }} 와

{{obj.get_share_link }}것이 문제였다 원래 개발서버에서는 잘 호출되던 것이었으나.... ㅠ

시간도 없고 해서 삭제 후에는 모든것이 배포 후 실 서버에서 잘 작동한다

nginx 설정 문법 검사를 하려고 아래 구문을 실행하면

sudo nginx -t

sudo service nginx configtest


django nginx error 에러가 난다

 [emerg] could not build the server_names_hash, you should increase server_names_hash_bucket_size: 64


보니까 서버네임이 길어서 그런거 같은데, 이걸 짧게 해주거나 

그 밑에 가보면 디폴드 설정파일이 있더라 그걸 수정해 주면되는데


sudo nano /etc/nginx/nginx.conf 편집기를 열고

http {


        ##

        # Basic Settings

        ##


        sendfile on;

        tcp_nopush on;

        tcp_nodelay on;

        keepalive_timeout 65;

        types_hash_max_size 2048;

        # server_tokens off;


        server_names_hash_bucket_size 128;

        # server_name_in_redirect off;


해쉬버킷사이즈를 증가시켜 주니까 에러가 없어졌다

django aws deploy 시 포트를 개발시 8000번을 쓴다 그래서 

pip3 manage.py runserver 0.0.0.0:8000 이렇게 하면

http://ec2-52-79-104-150.apxxx-northeast-2.compute.amazonaws.com:8000



이렇게 브라우저에서 접속이 가능한데

80포트로 접속하려고 

pip3 manage.py runserver 0.0.0.0:80

이렇게 하면 

Error: You don't have permission to access that port.

이런 에러가 난다
앞에 sudo를 붙여주면 안난다

sudo pip3 manage.py runserver 0.0.0.0:80



pillow cannot install

can't install pillow

system check error


일단 발생한 에러는 runserver 를 하면 멈추고 실행이 안되었다


SystemCheckError: System check identified some issues:


ERRORS:

videos.Category.image: (fields.E210) Cannot use ImageField because Pillow is not installed.

        HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow".


필로우를 설치하라는 건데 

로컬에서는 잘되던것이 aws 에 올리니 안되는것이 

이미지필드를 쓰기위해선 pillow 가 필요한데

    image=models.ImageField(upload_to='images/', null=True, blank=True)

aws 에서 설치가 안되는 현상이 발생했다


pip3 install Pillow 해도 계속 에러나면서 설치가 안되길래, 아래와 같은 에러가 발생

Command /usr/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip_build_root/Pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-23lnbl7n-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_root/Pillow

Storing debug log for failure in /home/ubuntu/.pip/pip.log



그래서 확인해 보니 디펜던시관련하여 또 설치해줘야 하는게 있는거 같다

$ sudo apt-get build-dep python-imaging
$ sudo apt-get install libjpeg8 libjpeg62-dev libfreetype6 libfreetype6-dev

두 명령어를 통해 의존 라이브러리들을 설치해주고 나서

pip3 install Pillow 하면 그제서야 설치가 된다

django 에러 : CSRF verification failed. Request aborted.

장고에서 결제관련 처리하다가 csrf 에러가 났다


보통 템플릿 폼에서 post 전송할때는 폼에서 

<form action="" method="post">{% csrf_token %}

이런식으로 csrf_token 을 전달하면 되는데


뷰단에서 처리할때는 어떻게 해야할지를 찾아보니

views.py 에서 처리할때는

from django.views.decorators.csrf import csrf_exempt

임포트 해주고

@csrf_exempt
def upgrade_reply(request):

함수전에 @csrf_exempt 데코레이션을 해주면 된다

django error 장고에러 AttributeError: module 'html.parser' has no attribute 'HTMLParseError'

이런 메시지가 출력되었다


import urllib.parse을 사용하기 위해서

urllib.parse.urlencode({})을 쓰는데 서버구동시 에러가 찍혔다

확인해보니 장고 버전 1.7대에서는 위의 에러가 난다고 한다


1.10대를 사용하니 정상적으로 서버가 구동된다 + 파이썬버전을 3.5대를 사용해야한다

django error intergrityError UNIQUE constraint field


오브젝트를 생성할때 objects.create 로 생성하면 에러날때가 있음


merchant_obj, created =UserMerchantId.objects.get_or_create(user=request.user)


장고 django 에서 쿼리를 가져올때 해당 오브젝트가 없으면 예외처리를 해줘야 한다

그래서 보통 try~ except ~ 문을 이용한다

try:
cat = Category.objects.get(slug=cat_slug)
except:
raise Http404

그런데 이게 계속 예외처리를 해줘야해서 불편하다 그래서 나온게 get_object_or_404 이다

이걸 이용하면 쿼리가 없으면 404에러를 자동으로 날려준다

obj = get_object_or_404(Category, slug=cat_slug)

위의 두가지는 동일한 기능을 하는 코드이다

get_object_or_404 를 이용하기 위해서는 아래 import 임포트가 필요하다

from django.shortcuts import  get_object_or_404


django 장고 정렬하기 ordering 글 컨텐츠 정렬


장고에서 정렬을 하기위한 방법

1. order_by(정렬기준인자) 이용

직접 쿼리에 적용하는 것이다.

def all(self):
return self.get_queryset().active().has_embed().order_by('timestamp')

점 찍고 order_by( ) 하면된다

전달인자로 timestamp 로 하면 생성시간 순서대로 

title이라는 항목이 있다면 title 알파벳 순서로 정렬된다. 이때 ABC...Z abc...z 이런식으로 대문자부터 정렬된다

역정를 하고 싶다면 인자로 -timestamp  로 -마이너스를 전달하면된다


2. class Meta 이용

class Video(models.Model):
title=models.CharField(max_length=120)
........

class Meta:
ordering = ['-timestamp']

클래스 메타를 이용해서 정렬해도 된다

django 장고 이미지 미디어파일 로딩못할때

로컬에서 개발할때 이런현상이 종종 발생

static 파일이나 css 로딩을 못할때가 있다


이것은 장고가 서빙을 못해서 인데 , 임시로 방법이 있다. 하지만 보안적으로좋지 않다고함


settins.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static", "media")

미디어 경로설정을  추가하고


urls.py

from django.conf.urls.static import static
from django.conf.urls import include, url
from django.conf import settings
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)

models.py

def get_image_url(self):
return '%s%s' %(settings.MEDIA_URL, self.image)


불러올 html에서

{% block content %}
{% for q in queryset %}
<a href="{{q.slug}}">{{q.title}}</a>
<a href="{{q.slug}}"><img src="{{q.get_image_url}}" class="img-responsive"></a>
<br/>
{%endfor%}
{% endblock %}

이렇게 하면 이미지가 로컬에서 불러와 진다


위에 settins 랑 url 를 생략하면 엑박으러 나온다

+ Recent posts