블로그 이미지
흰색앵초

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

2012. 12. 13. 17:54 프로그래밍/장고

장고로 이런저런 기능을 구현하다보면 Ajax를 통한 비동기 방식이 필요할 때가 있다. 

간단한 예제를 통하여 방법을 알아보자.


먼저 views.py에 아래와 같이 추가한다.

    
def test(request):
    value = RequestContext(request, {'user':request.user})
    template = get_template('test.html')
    output = template.render(value)
    return HttpResponse(output)

def test2(request):
    name = request.GET['name']
    age = request.GET['age']
    value = RequestContext(request, {'name':name, 'age':age})
    template = get_template('test2.html')
    output = template.render(value)
    return HttpResponse(output)

특별한건 없고 예제 구현에 필요한 test.html, test2.html을 보여주는게 거의 대부분인 소스이다. Ajax를 통해 값을 넘길 때 GET 방식을 사용함으로 test2.html에는 request.GET을 사용하여 처리하였다.

test.html

아래는 템플릿 소스이다.

<p><br /></p>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
  $('#btn').click(function(){
   $.ajax({
   	url : '/test2/',
   	data : {name:'name1', age:'27'},
   	success:function(data){
   		$('body').append(data)
   	}
   });
  });
 });
</script>
 <input type="button" value="클릭" id="btn">
 <body>
</html>

test2.html
이름 : {{name}}
나이 : {{age}}

결과는 이름:21 나이:27로 출력된다.

posted by 흰색앵초
2012. 12. 5. 14:11 프로그래밍/파이썬

for문을 수행할 때 for문이 돌고 있는 카운터를 알고 싶을 때가 있다.

그럴 때는 아래와 같은 방법으로 처리하면 된다.

li1 = ['a','b','c']

for idx, data in enumerate(li1):
    print idx #for문 카운터 출력
    print data 
posted by 흰색앵초
2012. 11. 26. 02:21 프로그래밍/장고

실행 - cmd 을 통해 터미널 창을 띄운 뒤

python c:\Python27\Scripts\django-admin.py startproject 생성할 프로젝트 이름

python 다음에 나오는 폴더명은 설치된 python의 폴더를 넣으면 된다.

posted by 흰색앵초
2012. 9. 18. 21:33 프로그래밍/장고

Django로 로그인을 구현하다 보면 브라우저를 껐다 켰음에도 불구하고 세션이 계속 유지되는 경우가 있다.


이러한 것은 Django의 기본 세션 유지가 꽤 길게 설정되어있기 때문인데 이러한 경우 아래와 같이 처리하면 된다.

delete FROM django_session where 1=1;

이미 있는 세션을 제거.


settings.py에 아래를 추가

SESSION_EXPIRE_AT_BROWSER_CLOSE = True 


이렇게 하면 브라우저를 껐을 때 세션이 파기되고 브라우저를 껐다켜면 다시 로그인을 해야한다.

posted by 흰색앵초
2012. 7. 13. 21:27 프로그래밍/파이썬

HTML을 파싱하다보면 개행문자가 깨지면 \n이 아닌 ^M이 될 경우가 있다 이러한 경우 VIM 등에서 확인할 수 있는데 python에서는 간단히 제거할 수 있다.

예를들어 f1라는 문자변수에 값이 저장되어있다고 치자

f1 = f1.replace('\r','')

사실 python에서 ^m의 값은 \r인 것만 알면 간단히 고칠 수 있다.

posted by 흰색앵초
2012. 6. 23. 15:42 프로그래밍/파이썬
'''
Created on 2012. 6. 23.

@author: mutsumi
'''

a = ['1','2','3','4','5','6','7','8','9','10']

b = [0,1,2,3,4]

delSu = 0

for c in range(0,len(b)): #원하는 리스트만 지우기
    del a[b[c-delSu]]
    delSu += 1
print a


파이썬 코드를 짜다보면 같은 순서의 여러개의 배열을 지워야하는 경우가 있다.
(ex:a와 b의 [0,3,5]번째의 배열을 똑같이 지워야한다거나)

그럴 경우 위의 코드와 같이 사용하면 된다.

posted by 흰색앵초
2012. 5. 26. 15:09 프로그래밍

nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

Today I’m facing the following error message after added custom module to nginx
1root@ibnuyahya:~# sudo /etc/init.d/nginx restart
2 * Stopping Web Server nginx [OK]
3 * Starting Web Server nginx                                                                                                                                                         nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
4nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
5nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
6nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
7nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
8nginx: [emerg] still could not bind()

solution?
check running pid

1fuser -n tcp 80
280/tcp:              26621 26622

Kill

1root@ibnuyahya:~# kill -9 26621
2root@ibnuyahya:~# kill -9 26622

restart nginx

1root@ibnuyahya:~# sudo /etc/init.d/nginx restart

posted by 흰색앵초
2012. 5. 4. 02:21 프로그래밍/파이썬
1. 특정 날짜로부터 며칠 지난 날짜 구하기
import datetime
day = datetime.date(2009,05,01)
afterday = day + datetime.timedelta(92)
print afterday

어제날짜: datetime.timedelta(days = -1)
내일날짜: datetime.timedelta(days = 1)

2. 오늘 날짜 구하기
datetime.date.today()



요일은 우선 두가지 방법이 있다.


import time

now = time.localtime()

print now.tm_wday #Monday is 0



import datetime

datetime.datetime

print datetime.datetime.today().weekday()


둘다 월요일은 0으로 나오고 일요일은 6으로 표현된다.


월화수목금토일로 바꾸고 싶은 경우 배열에 넣고 바꿔서 사용하면 되겠다.

posted by 흰색앵초
2012. 4. 20. 12:59 프로그래밍

사용자 삭제

use mysql;
DELETE FROM mysql.user WHERE user='username' and host='hostname';

헤매지 말고 보고 하자

============================

사용자 추가

mysql> use mysql INSERT INTO user VALUES('%', '사용자', PASSWORD('비밀번호'), 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y');


posted by 흰색앵초
2012. 3. 8. 01:18 프로그래밍/장고
admin페이지에서 CSS가 불러와지지 않는 경우가 발생하는데 이러한 경우 nginx

/etc/nginx/sites-enabled/설정파일이름(본인의 경우에는 django) 을 vim으로 연다음

    location /static {
        autoindex   on;
        root /opt/project/sample_project/static/; #static폴더를 원하는 폴더로 수정
    }

을 추가해준 다음 파이썬 라이브러리 폴더에서 css가 있는 media 폴더 등을 복사해주면 admin에 css가 적용되는 것을

볼 수 있다. 설치환경 등에 따라 폴더가 상이할 수 있으니 잘 찾아서 넣으면 된다.

혹시나 하는 마음에 포스팅해본다.
posted by 흰색앵초
prev 1 2 3 4 next