Как передать аргументы классу в python

Я пытаюсь создать приложение Django. Я хочу создать функцию для передачи некоторого начального текста в текстовую область. Я пробовал следующее :

Вот необходимая часть 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')
        })

Вот мой create.html файл:

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

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


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

Вот 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")
]

Но когда я пытаюсь запустить это, я получаю следующую ошибку:

snippet of error

Я думаю, что ошибка связана с тем, что вы не вызвали super() внутри __init__, передайте его как:

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')
    })

Обычно, когда формы делаются без использования моделей, т.е. через Form API, то обычно это делается следующим образом:

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')

Затем, передайте его как пустую форму в представлении как:

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

Note: Классы в python пишутся в PascalCase, а не в smallcase, поэтому вы можете изменить его на CreateForm из createform.

Оказывается, я слишком усложнил задачу. Если я хочу предоставить начальный текст в текстовую область, я могу просто сделать следующее:

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: Спасибо Abdul Aziz Barkat за ваше предложение. Использовано initial.

Вернуться на верх