0

I have a small Django project consisting of one app. I am very very new to Django and have run into a problem. I have an app that is a webpage with a question posed and a form that must have input. Once the button is pressed to submit the form, I would like to update the page without refreshing. I have heard AJAX is a good way to handle this but I have not been able to find any examples working with just forms.

UPDATE

after researching another users suggestions I have made some progress implementing ajax to display my form submission text. The problem is now that when navigating to the app page it displays just raw html. I am not sure why.

My Forms

from django import forms
from . import models

class AnswerForm(forms.Form):
    answer = forms.CharField(label='Answer', required=True, max_length=500)
    def save(self):
        answer_instance = models.Answer()
        answer_instance.answer_txt = self.cleaned_data["answer"]
        answer_instance.save()
        return answer_instance

My Models

from django.db import models
from django.forms import ModelForm

class Riddle(models.Model):
    riddle_txt = models.CharField(max_length=900)
    def __str__(self):
        return self.riddle_txt

class Answer(models.Model):
    answer_txt = models.CharField(max_length=900)
    def __str__(self):
        return self.answer_txt

My Views

from django.http import JsonResponse
from django.shortcuts import get_object_or_404, render
from django.template import loader
from .models import Riddle, Answer
from . import forms

# Create your views here.

def index(request):
    form = forms.AnswerForm()
    response_data = {} #new line
    if request.method == "POST":
        form = forms.AnswerForm(request.POST)
        if form.is_valid():
            form.save()
            form = forms.AnswerForm()
            response_data['text'] = form.answer_txt #new line
    else:
        form = forms.AnswerForm()

    riddle_list = Riddle.objects.all()
    answer_list = Answer.objects.all()
    form = forms.AnswerForm()
    template = loader.get_template('CricksRiddles/index.html')
    context = {
        'riddle_list': riddle_list,
        'form': form,
        'answer_list': answer_list,
    }
    #form_answer = request.POST['_form']

    return render(request, 'CricksRiddles/index.html', context, {'json_data': json.dumps(response_data)}) #new line

My JS

$('#answer_form').on('submit', function(e){
    e.preventDefault();
    console.log("form submitted");
    post_answer();
});
function post_answer() {
    console.log("answer is posted without refresh");
    console.log($('#answer_text').val());
}

and finally here is

MY Templates

{% extends 'base.html' %}
{% load static %}
{% block content%}
    <body>
    {% if riddle_list %}
        <div class="riddle_box">
        {% for riddle in riddle_list %}
            <!-- <a href="{% url 'CricksRiddles:info' riddle.id %}"></a> -->
            <p>{{ riddle.riddle_txt }}</p>
        {% endfor %}
        <!--
        <!--{% for ans in answer_list %}-->
            <li>{{ ans.answer_txt }}</li>
        <!--{% endfor %}-->

        </div>
        <form id="answer_form" action="/" method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" class="button" name="_form" value="Submit Answer">
        </form>
    {% else %}
        <p>Out foraging for sticks and dogs.</p>
    {% endif %}
    </body>
{% endblock %}
{% block js_block %}

{% endblock %}

It's my understanding that the AJAX code would go in the block js_block, but again I can not find any information on using AJAX with a django form. Everything I have found has been model forms, but I do not want to use those. Thank you for any help.

Jay Wehrman
  • 193
  • 2
  • 10
  • Can you post your JS? And you mention you've looked for django ajax, but what you're really looking for is just ajax forms. The python view has little involvement with the process - however a quick google of "django ajax form" first link provides a correct solution: https://realpython.com/django-and-ajax-form-submissions/ – Glycerine Mar 16 '20 at 20:54
  • thanks i'll take a look now – Jay Wehrman Mar 16 '20 at 21:06
  • I actually saw this page yesterday, it too deals with modelForms and not just regular forms. thank you though. – Jay Wehrman Mar 16 '20 at 21:07
  • 1
    Using a model form make no difference, you're accepting a `POST`. This can be done with pure HTML (your current code) or JS (required). Again though, none of this will work without the Ajax to do it. Your current code is not POSTing an ajax form. Like this: https://stackoverflow.com/a/6960586/235146 – Glycerine Mar 17 '20 at 04:14
  • thank you, I have been able to kind of figure out how to implement ajax code and my site "runs" but now instead of django displaying my template for my app, it displays the base html. – Jay Wehrman Mar 17 '20 at 06:17

0 Answers0