0

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" class="createnew">
        {% 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

7
  • 2
    Please post a minimal reproducible example. Commented Jun 19, 2022 at 12:01
  • Do I need to add url.py? Commented Jun 19, 2022 at 12:07
  • attach code at /create/ view, where you use renderer Commented Jun 19, 2022 at 12:10
  • Hint: are you sure you override the __init__ method properly? Is the method originally supposed to do anything else? What about the method signature, have you preserved the original method signature? Commented Jun 19, 2022 at 12:13
  • @Abdul Aziz Barkat I am sorry. I don't understand. Initially I wanted to pass some text as argument to the the class createform so that I can put some text initially in textarea. I saw some solutions where __init__ was used to take arguments. I don't actually know much about it. Sorry to be dumb. Commented Jun 19, 2022 at 12:18

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

is the big bracket in 8th line last column unintended?
@MWD What mean? Call the super() with respective fields.
It does work but the form doesn't render
@MWD can you share your models? and do you mean form is not appearing?
You should also preserve the actual signature of the __init__ method. With this implementation there is no way to pass in the various arguments the form originally can take.
|
0

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.

6 Comments

Why you didn't share the full view? and it is already done by me in the second approach :)
The initial kwarg is more suitable the form will interpret what you currently do as the user passing that data in.
@Abdul Aziz Barkat Can you give me link to the page that shows the implementation difference between these two
The first argument the form class takes is the form data, as you yourself wrote createform(request.POST) this will make the form bound to some data, the initial kwarg on the other hand is specifically for the purpose of specifying initial values and will not cause the form to be bound.
@SunderamDubey your edit broke OP's answer by removing the values from there. Their code (although not ideal) would have worked before your edit. My suggestion was to use the initial kwarg.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.