Home > Blockchain >  How can I pass data into a class in python?
How can I pass data into a class in python?

Time:01-16

I am using django to create a blog editing page. However, my struggles do not involve django, rather just python. I have a class:

class EditForm(forms.Form):
def __init__(self, initcontent):
    self.initcontent = initcontent
title = forms.CharField(max_length=100, label='Post Title')
short_description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100}))
content = forms.CharField(widget=CKEditorWidget(), initial=Post.objects.get(pk=initcontent).content)

and I am initialising it like this:

form = EditForm()
form.initcontent = post.pk

however I get the error:

File "C:\Users\Rayyan Admin\Documents\GitHub\shaista-s-cooking-blog\blogger\forms.py", line 34, in EditForm
content = forms.CharField(widget=CKEditorWidget(), initial=Post.objects.get(pk=initcontent).content)
NameError: name 'initcontent' is not defined

How do i pass initcontent into the class?

CodePudding user response:

Hi your indenting is off so I'm not sure if that's a mistake in formatting here or causing issues with your code.

Anyways I think what you want is:

class EditForm():

    def __init__(self, initcontent):
        self.initcontent = initcontent

form = EditForm(post.pk)

CodePudding user response:

Whenever you make an instance of a class, you can pass your data into it if you have defined a constructor. That is the role of a constructor. In your case, you have defined a constructor with initcontent as a parameter. So you can do it like this -

form = EditForm(whatever you need to pass)

This will do.

  •  Tags:  
  • Related