블로그 이미지
흰색앵초

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

Notice

2013. 4. 3. 16:30 프로그래밍/장고

장고로 검색기능을 구현할 때 영어의 대소문자를 구분하지 않고 검색해야할 필요가 있다

그럴때는 contains대신 icontains를 사용해주면 된다.

test = Test_table.objects.filter(title__icontains='abcd')

위와같이 검색을 하게 되면 Abcd aBcd ... 등등등의 경우에 대소문자를 가리지 않고 검색이 된다.


posted by 흰색앵초
2013. 4. 1. 17:08 프로그래밍/장고

장고에서 단순히 Object의 갯수만을 세고 싶을때는 .count()를 사용하면 된다.


count

count()

Returns an integer representing the number of objects in the database matching the QuerySet. The count() method never raises exceptions.

Example:

# Returns the total number of entries in the database.
Entry.objects.count()

# Returns the number of entries whose headline contains 'Lennon'
Entry.objects.filter(headline__contains='Lennon').count()

posted by 흰색앵초
2013. 2. 26. 19:27 프로그래밍/장고
views.py에서 아래와 같이 사용하면 된다. 원하는대로 약간씩 고쳐서 쓰면 무방할 듯
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

출처 : http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django


posted by 흰색앵초
2013. 2. 26. 19:14 프로그래밍/장고


DateTimeField에 서버의 시간을 넣고 싶을 때가 있다 그럴 때는 models.py에서 아래와 같이 넣어주면 된다.

date_modified = models.DateTimeField(auto_now=True)

혹은 다른 방법도 존재한다.


views.py 부분에서

from datetime import datetime
obj.date_modified = datetime.now()

로 처리해서 사용하면 된다.


출처:http://stackoverflow.com/questions/7465796/django-set-datetimefield-to-servers-current-time

posted by 흰색앵초
2012. 12. 22. 21:34 프로그래밍/장고

장고에서 media, static 폴더를 셋팅해야할일들이 많다. nginx나 apache를 붙여서 쓸 때는 따로 셋팅해야하지만, 개발용서버에서의 셋팅 방법은 settings.py에서 폴더를 셋팅한 다음 urls.py를 아래와 같이 추가하면 사용할 수 있다.

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
        (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
    )


posted by 흰색앵초
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. 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. 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 흰색앵초
2012. 2. 24. 03:14 프로그래밍/장고

1. 파이썬 설치

apt-get install zlibc zlib1g-dev

장고와 엔진엑스를 연동하기 위해서는 파이썬에서 FastCGI 프로토콜을 구현하는 flup라이브러리가 필요한데 이를 인스톨 해야한다.

apt-get install python-flup

2. 장고 설치

알아서 설치

3. 프로젝트 만들기

# mkdir -p /opt/project
# cd /opt/project
# django-admin.py startproject sample_project
# cd sample_project
# mkdir media

4. 프로젝트 실행

# cd /opt/project/sample_project
# python manage.py runfcgi method=threaded pidfile=/tmp/django_sample.pid host=127.0.0.1 port=8000
=====
# python manage.py runfcgi method=prefork host=127.0.0.1 port=9000 pidfile=/var/run/django.pid

위의 셋팅값을 보면 알 수 있듯이 폴더와 방식 등을 설정해서 사용하면 된다.

5. 엔진엑스 설치

- 엔진엑스를 컴파일하는데 있어서 PCRE(Perl Compatible Recular Expression)이 필요하다.

#apt-get install libpcre3 libpcre3-dev

- OpenSSL 라이브러리도 깔아야된다.

#apt-get install openssl libssl-dev

http://nginx.org/en/download.html 에서 stable버전을 다운받아서 압축을 푼 후에 다음과 같이 입력한다.

설정파일을 바꾼 다음에 실행을 하면된다.

#./configure

#make

#make install

6. 엔진엑스 설정

# cd /etc/nginx/sites-available
# vi django

server {
    listen 80;
    server_name 도메인주소;
    location /site_media  {
        root /opt/project/sample_project/media/;
    }
    location / {
        # host and port to fastcgi server
        fastcgi_pass 127.0.0.1:8000;
        fastcgi_param PATH_INFO $fastcgi_script_name;
        fastcgi_param REQUEST_METHOD $request_method;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_param CONTENT_TYPE $content_type;
        fastcgi_param CONTENT_LENGTH $content_length;
        fastcgi_pass_header Authorization;
        fastcgi_intercept_errors off;
    }
}

# cd /etc/nginx/sites-enabled
# ln -s /etc/nginx/sites-available/django django

7. 엔진엑스 실행

# /etc/init.d/nginx restart
posted by 흰색앵초
prev 1 next