我想将值从views.py
传递到forms.py.
我在views.py
中写信,
def app(request):
if request.method == "POST":
form = InputForm(data=request.POST)
if form.is_valid():
name = form.cleaned_data['name']
age = form.cleaned_data['age']
forms.py
class InputForm(forms.Form):
name = forms.CharField(max_length=100)
age = forms.CharField(max_length=100)
def logic(self):
#I want to use views.py’s name&age’s value here
我是Django的新手,那么我应该如何编写代码来实现自己的理想目标?
答案 0 :(得分:2)
实际上,您可以通过cleaned_data
属性(这是一个dict对象)访问表单中的数据,因此,这里有一个示例save
方法签出:
class CreatePostFrom(forms.Form):
image = forms.ImageField(required=True)
des = forms.CharField(required=False, max_length=250)
location = forms.CharField(required=False, max_length=100)
tags = forms.CharField(required=False, max_length=250)
def save(self, user):
tags = self.cleaned_data["tags"].split()
for tag in tags:
Tag.objects.get_or_create(name=tag)
post = Post.objects.create(user=user,
image=self.cleaned_data["image"],
des=self.cleaned_data["des"],
location=self.cleaned_data["location"])
post.tags.add(*tags)
return post
答案 1 :(得分:0)
正如我在评论中所说:
在Form类中使用变量。
class InputForm(forms.Form):
name = forms.CharField(max_length=100)
name_data = ""
age = forms.CharField(max_length=100)
age_date = 0
def logic(self):
# I want to use views.py’s name&age’s value here
# You can play here with your age_data and name_data
and views.py:
def app(request):
if request.method == "POST":
form = InputForm(data=request.POST)
if form.is_valid():
form.name_data = form.cleaned_data['name']
age.name_data = form.cleaned_data['age']
我刚刚看到您的cleaned_data
来自您的表单,所以为什么不直接在类Class中像这样工作呢?
class InputForm(forms.Form):
name = forms.CharField(max_length=100)
age = forms.CharField(max_length=100)
def logic(self):
# I want to use views.py’s name&age’s value here
# Why don't you use cleaned_data['name'] and age from here?
name = cleaned_data['name']
并保持这种观点。
def app(request):
if request.method == "POST":
form = InputForm(data=request.POST)
if form.is_valid():
name = form.cleaned_data['name']
age = form.cleaned_data['age']
,但是此答案的目的不是给您确切的解决方案,而是让您稍微尝试一下问题。作为Python初学者,如果您自己尝试并进行一些重新搜索,您将学到更多。
也可以考虑阅读以下内容:https://docs.djangoproject.com/en/2.1/topics/forms/#building-a-form-in-django