我的数据库中有3个表。 用户 sessiontokens 3.发布
我使用外键在sessiontoken和post中引用用户表。 如果查询存在,我想检查accessstoken表,并从中获取相应的user_id值。
模型
class User(models.Model):
email = models.EmailField()
name = models.CharField(max_length=30)
username = models.CharField(max_length=20)
password = models.CharField(max_length=100)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class SessionToken(models.Model):
user = models.ForeignKey(User)
session_token = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
is_valid = models.BooleanField(default=True)
def create_token(self):
self.session_token = uuid.uuid4()
class Post(models.Model):
user = models.ForeignKey(User)
image = models.FileField(upload_to='user_images')
caption = models.CharField(max_length=240)
image_url = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
以下是发生的事情, 每次用户登录时都会生成session_token。 然后我们使用以下功能检查用户是否立即登录。
def check_validation(request):
if request.COOKIES.get('session_token'):
session = SessionToken.objects.filter(session_token=request.COOKIES.get('session_token'))
if session:
return session
else:
return None
我想在post表中设置user_id来匹配来自上面函数的sessiontoken中的user_id
def upload_view(request):
usr = check_validation(request)
if usr:
if request.method == "GET":
form = PostForm()
return render(request, 'upload.html', {'form': form})
elif request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
pic = form.cleaned_data.get('image')
title = form.cleaned_data.get('caption')
post = PostForm().instance
post.user = usr
post.image = pic
post.caption = title