gpt4 book ai didi

python - Django form.save() 到另一个类/函数

转载 作者:太空宇宙 更新时间:2023-11-03 17:27:19 24 4
gpt4 key购买 nike

如何 .save() 到另一个类/函数,例如:

def save_page(request):

# contains 3 fields

form = sample_tableform(request.POST)
if request.method == 'POST':
if form.is_valid():

#send a confirmation code to email
#redirect to code confirmation page

def valcode(request):

#contains 1 field

sub_form = confirmform(request.POST)
if request.method == 'POST':

if sub_form.is_valid():

#compare if code from save_pages matches the input field
# if it matches then the data can be stored

form.save()
subform.save()

可能还是不可能?

我喜欢使用 session 的想法,但如何实现它?

最佳答案

假设您的代码来自 views.py,答案是不能

View 不是这样工作的(HTTP 也不是)。如果您想在后续 HTTP 请求之间访问数据,则必须将其保存在某处。

在您的情况下,您可能需要使用 model 将验证代码存储在数据库中。 :

# models.py
from django.db import models

class ValidationCode(models.Model):
code = models.CharField(max_length=10, unique=True)
creation_date = models.DateTimeField(auto_now_add=True)
is_validated = models.BooleanField(default=False)

# views.py

def save_page(request):

# contains 3 fields

form = sample_tableform(request.POST)
if request.method == 'POST':
if form.is_valid():

validation_code = ValidationCode(code="random_code_here")
validation_code.save()

# send email with the code here
#redirect to code confirmation page

def valcode(request):

#contains 1 field

sub_form = confirmform(request.POST)
if request.method == 'POST':

if sub_form.is_valid():

try:
code_from_db = ValidationCode.objects.get(code=form.fields['code'])
except ValidationCode.DoesNotExist:
# Not code matching input exist in database
# return some error to the user

# code exist in db, just mark it as validated
code_from_db.is_validated = True
code_from_db.save()

关于python - Django form.save() 到另一个类/函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32384915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com