'django don't show form in template

django dont show my form in my template where is the problem?

forms.py

from django import forms

class QuestionForm(forms.Form):
    massage = forms.CharField(widget=forms.TextInput)

views.py

from cheatexam_question.forms import QuestionForm
def newquestion(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        context = {
            'form': form
        }
    return render(request, 'homepage.html', context)

template

        <form method="post">
            {% csrf_token %}
            {{ form }}
      <input class="btn btn-warning form-control" type="submit" value="ثبت سوال">
        </form>


Solution 1:[1]

A GET request is used to retrieve the page, whereas a POST request is used to submit the form. Here you only construct a form in the POST request. For the GET request, you did not even define a context, which will thus raise an error.

from cheatexam_question.forms import QuestionForm

def newquestion(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        # …
    else:  # GET request
        form = QuestionForm()
    context = {
        'form': form
    }
    return render(request, 'homepage.html', context)

Solution 2:[2]

take the form before request.post like this :

def newquestion(request):
    form = QuestionForm(request.POST or None)
        if form.is_valid():
        .
        .
    context = {'form':form}
    retrun render(request , 'template.html' , context)

note : context and return is not in 'if' block

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem
Solution 2 DharmanBot