Amanda_K96
Amanda_K96

Reputation: 55

Implementing Django Form without Model

This is a continuation from last question here Coding mental block with specific Django task

The answer was:

A pure django solution would be:

However, as I am working through the steps, my form was not being rendered properly.

views.py

def form_handle(request):
    form = MyForm()
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            a = cd.get('a')
    return render(request, "rr.html", {})

forms.py

class MyForm(forms.Form):
    a = forms.CharField(max_length=20)
    mat = forms.CharField(max_length=200)

html file

  <form action="{% url 'form_handle' %}" method="POST">{% csrf_token %}
      {{form.as_p}}
      <button type="submit">Submit</button>
  </form>

When I load the page all I see is a submit button. As pictured

Can someone please advise me where I had gone wrong?

Upvotes: 1

Views: 5024

Answers (2)

Gahan
Gahan

Reputation: 4213

Do something like below: if form is valid then check for the condition otherwise post blank form; if form is valid but result answer is wrong then redirect to previous url you desire to redirect

def form_handle(request):
    if request.method == 'POST':
        form = MyForm(request.POST) # if post method then form will be validated
        if form.is_valid():
            cd = form.cleaned_data
            num1 = cd.get('num1')
            num2 = cd.get('num2')
            result = cd.get('result')
            if float(num1) + float(num2) == float(result):
                # give HttpResponse only or render page you need to load on success
                return HttpResponse("valid entiries")
            else:
                # if sum not equal... then redirect to custom url/page 
                return HttpResponseRedirect('/')  # mention redirect url in argument

    else:
        form = MyForm() # blank form object just to pass context if not post method
    return render(request, "rr.html", {'form': form})

Upvotes: 1

Cypherius
Cypherius

Reputation: 551

If I understand correctly, the form that you call in the html file is the form in the function post_question in views.py, isn't it? And where is the class QuestionForm?, can you show us the code of it? Because as I see, the class MyForm is still unused in file views.py. It would be easier if you also show us the import in views.py and the class QuestionForm instead of just a nonsensical MyForm. Cheer!

Upvotes: 0

Related Questions