Python (100) 썸네일형 리스트형 Python Django: 동시 접속 로그인 막기 # session # session_key Django를 통해서 동시 접속을 막기 원리: 로그인 할 때 생기는 session_key를 DB에 저장 하고, 새로 로그인이 될 때 기존 session_key를 유저의 DB에서 불러와서 DB의 Session에서 해당 session_key를 지움으로써 기존 로그인은 해지 시키기 # models.py class User(AbstractUser): username = models.CharField(max_length=150) session_key = models.CharField(max_length=40, null=True, blank=True) # views.py from django.contrib import auth user = User.objects.get("로그인하려는 유저") if user.sess.. Python Django - request session 이용하기 # get 에서 post로 data 넘기기 get으로 받은 data를 post로 넘겨주고 싶은데, 보안상 html, javascript 등에 노출시키고 싶지 않은 경우 get에서 request.session에 담아서 post에서 불러오면 된다. if request.method == 'GET' request.session['sample_value'] = 'It is sample' return render(request, 'get.html') if request.method == 'POST' print(request.session['sample_value']) # output: it is sample return JsonResponse({"response":"success"}) Django: QuerySet to Json #QuerySet Json으로 보내기 # serializer # JsonResponse Djano QuerySet 값을 Json으로 보내줄 때, data를 serialize를 하지 않고 보내면 다음과 같은 오류 발생 TypeError: Object of type MyCoupon is not JSON serializable 따라서 serialize를 해줘서 보내야 한다. from django.core import serializers 위와 같이 serializers를 import해서 이용해도 되지만 ORM query로 얻은 QuerySet을 .values()로 뽑아서 보내줘도 된다. from django.http import JsonResponse from .models import YourModel def your_view(request): queryset = YourModel.object.. Django: 시간 변환 # timezone, pytz # UTC, Asia/Seoul Django를 처음 설치하면, 시간과 관련된 설정이 아래와 같이 되어 있습니다. # settings.py TIME_ZONE = 'UTC' 우선, UTC가 무엇일까요? UTC (협정 세계시)는 Coordinated Universal Time의 약자로, 세계 표준 시간을 의미합니다. UTC는 현대 국제 시간 체계의 기준으로 사용되며, 지구의 자전 속도와 태양 시간을 기반으로 합니다. UTC는 전 세계의 시간대와 동기화되어 있어, 국제적인 커뮤니케이션과 데이터 처리에 있어서 일관된 시간을 제공합니다. UTC는 그리니치 평균시 (GMT)와 동일한 시간대를 기준으로 하지만, 두 개념 사이에는 약간의 차이가 있습니다. GMT는 지구 자전 속도를 기준으로 한 시간 체계이지만, UTC는 원자시계를 기준으로 정확한 시간.. Python: Declare variable in one line with list # 배열의 요소로 변수선언하기 List, Tuple 이용 변수 선언 ChatGPT 와의 문답 내용 첨부 Q) In Python, can you declare a variable in one line as many elements as an array has? A) Yes, you can use tuple unpacking to declare a variable for each element in an array (list or tuple) in one line. This can be done if you know the length of the array beforehand and it matches the number of variables you are trying to declare. Here's an example: # Usi.. Django ManyToMany로 생기는 중간테이블(intermediate table)에 접근하기 # through # 중간테이블 정의 없이 from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) # 새로운 저자와 책 객체 생성 book = Book.objects.create(title="Example Book") # 자동 생성된 중간 테이블에 대한 queryset 가져오기 through_queryset = book.authors.through.objects.all() .through를 통해 중간테이블 데이터를 직접 활용 가능 (join.. Python: rsplit # 파일 확장자 명 떼어서 이름 붙이기 rsplit 파일의 확장자 명과 이름 분리하기 (예시: abc.png) ChatGPT 와의 문답 내용 첨부 Q) How to remove last part of string in python? for example, abc.png -> I want to remove .png only A) You can remove the last part of a string in Python using the str.rsplit() method. In your example, you want to remove the file extension ".png" from the filename. Here's how you can do it: filename = "abc.png" base_name = filename.rspli.. Django 최신 데이터 가져오기# DateTimeField # latest # earliest Django에서 모델 설계시에 created나 updated field DateTimeField 형태로 추가 후에 가장 최근에 수정된 object 접근시 latest() 가장 오래 전 수정된 object 접근시 earliest() example new_lecture = Lectures.objects.latest('updated') old_lecture = Lectures.objects.earliest('updated') 주의) 해당 조건에 걸리는 data row가 여러개라면, 여러 개중에 한가지만 불러오기 때문에 전(후)처리가 필요할 수 있습니다. (id가 가장 큰 것을 가져오는 듯) 이전 1 ··· 3 4 5 6 7 8 9 ··· 13 다음