How To Show Forms.py File In Html
Solution 1:
In your views.py file write:
defvote_view(request):
    from .forms import QuestionForm
    question_form = QuestionForm()
    return render(request, 'path/to/your/template.html', locals())
Then in your HTML write:
<div>
    {{ question_form.as_p }}
    or
    {{ question_form.as_table }}
</div>
You can render the form in different formats. See here.
Also the locals() is a python convenient way to pass to the HTML template all the local variables of the current scope (i.e of the vote_view view function).
Do not forget, of course to link the view to your base urls.py file like this:
from your_app.views import vote_view
urlpatterns = [...]  # the previous urls (if any)
urlpatterns += [ url(r'^polls/$', vote_view, name='polls'), ]
[UPDATE]: The format of your Question_CHOICES is wrong for this type of form field. You should to define it this way:
Question_CHOICES = (
    ('1', '1'),
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
)
Then is will render to your HTML template either via {{ question_form }} or {{ question_form.as_p }} or {{ question_form.as_table }} or whatever!
Solution 2:
If you use FBV then you need to create a view_function and initialize the form with your custom form and pass the form to your template via context.
1. view.py
    from .forms import QuestionForm
    def custom_view_function(request):
        if request.method == 'POST':
            form = QuestionForm(request.POST)
            if form.is_valid():
                return HttpResponseRedirect('---success url---')
        else:
            form = QuestionForm()
        return render(request, 'template.html', {'form': form})
2. template.html
    <form action="." method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit" />
    </form>
check official django docs for more details link
Post a Comment for "How To Show Forms.py File In Html"