Home > OS >  How to give arguments to Class in python
How to give arguments to Class in python

Time:06-20

I am trying to create a Django app. I want create function to pass some initial text to text area. I tried following:

Here is required part of views.py :

    from django import forms
    
    class createform(forms.Form):
        def __init__(self, title, value):
            self.newtitle = forms.CharField(max_length=30, label='Enter Title:', widget=forms.TextInput(attrs={'value': title}))
            self.content = forms.CharField(widget=forms.Textarea(attrs={'value': value}), label='Enter the description:')

    def create(request):
        return render(request, "encyclopedia/create.html", {
            "form": createform('this title','this content')
        })

Here is my create.html file:

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Create New Page
{% endblock %}


{% block body %}
    
    <form action="{% url 'create' %}" method="post" >
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Create New Page">
    </form>
{% endblock %}

Here is url.py:

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("wiki/<str:title>/", views.entries, name="entries"),
    path("find/", views.find, name="find"),
    path("create/", views.create, name="create")
]

But when I try to run this I get following error:

snippet of error

CodePudding user response:

I think the error is because you haven't call super() inside the __init__, pass it as:

views.py

class createform(forms.Form):
    def __init__(self, title, value):
        self.newtitle = forms.CharField(
            max_length=30, label='Enter Title:', widget=forms.TextInput(attrs={'value': title}))
        self.content = forms.CharField(widget=forms.Textarea(
            attrs={'value': value}), label='Enter the description:')

        super().__init__(title, value)

def create(request):
    return render(request, "encyclopedia/create.html", {
            "form": createform('this title','this content')
    })

Generally, when forms are made without the use of models, i.e. through Form API, it is generally made it as following:

views.py

class createform(forms.Form):
    newtitle = forms.CharField(
        max_length=30, label='Enter Title:', widget=forms.TextInput(attrs={}),initial='this title')
    content = forms.CharField(widget=forms.Textarea(attrs={}),
                              label='Enter the description:',initial='this content')

Then, pass it as empty form in view as:

def create(request):
        return render(request, "encyclopedia/create.html", {
            "form": createform()
        })

Note: Classes in python are written in PascalCase not smallcase, so you may change it to CreateForm from createform.

CodePudding user response:

Turns out I was making problem too much complex. If I want to provide the initial text to text area I can simply do this:

views.py :

 class CreateForm(forms.Form):
    newtitle = forms.CharField(max_length=30, label='Enter Title:')
     content = forms.CharField(widget=forms.Textarea, label='Enter the description:')

def create(request):
    if request.method == 'POST':

        form = createform(request.POST)
        if form.is_valid():
            new_title = form.cleaned_data["newtitle"]
            content = form.cleaned_data["content"]

            if util.get_entry(new_title):
                return HttpResponse("OOPS! Entry with the title already exists")

            util.save_entry(new_title, content)

            return entries(request, new_title)

    else:
        return render(request, "encyclopedia/create.html", {
            "form": CreateForm(initial={
                "newtitle" : "this title",
                "content" : "this content"
            })
        })

Edit: Thanks Abdul Aziz Barkat for your suggestion.Used initial.

  • Related