Reputation: 319
I want to pass values are gotten in views.py
to forms.py.
I wrote in 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']
in 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
I am new to Django, so how should I write codes to do my ideal thing?
Upvotes: 2
Views: 291
Reputation: 739
As I said in my comment:
Use variables in Form class.
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']
I have just seen that your cleaned_data
come from your form so why not working in it directly like this in form 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']
and simply keep your view like this.
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']
but the goal of this answer is not to give you the exact solution but to let you experiment with your problem a bit. As a Python beginer you will learn more if you try by yourself and make a few reasearches.
Also consider reading this: https://docs.djangoproject.com/en/2.1/topics/forms/#building-a-form-in-django
Upvotes: 1
Reputation: 604
actually you can access data in a form by cleaned_data
property (that is a dict object), so as an example checkout save
method here:
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
Upvotes: 2