0

I am making a form but when the data is invalid, it empties the field when loading the page again, how can i solve this? My view:

def create_country(request):

    if request.POST:
        country_form = CountryForm(request.POST)
        if country_form.is_valid():
            country_form.save()
            return HttpResponseRedirect(reverse('country'))

        else:
            return render(request, 'create_country.html', {'country_form': country_form})

    country_form = CountryForm()
    return render(request, 'create_country.html', {'country_form': country_form})

And my template:

<div>
    <center>
        <h2>Create a new country</h2>
    </center>
    <form action="{% url 'create_country' %}" method="post">{% csrf_token %}
        <table>
            <tr>
                <b>{{ country_form.non_field_errors }}</b>
            </tr>
            <tr>
                <b>{{ country_form.name.errors }}</b>
            </tr>
            <tr>
                <td><label for="id_name">Name:</label></td>
                <td><input id="id_name" type="text" name="name" size= "25" maxlength="127" /></td>
            </tr>
            <tr>
                <b>{{ country_form.flavor.errors }}</b>
            </tr>
            <tr>
                <td><label for="id_flavor">Flavor Text:</label></td>
                <td><textarea style="width: 300px; height: 200px;" id="id_flavor" type="text" name="flavor" maxlength="511"></textarea></td>
            </tr>
            <tr>
                <td></td>
                <td style="float: right;"><input type="submit" value="add country" /></td>
            </tr>
        </table>
    </form>
</div>

How can i add my old data thats put in before the post add back into the form after it returns as non valid?

Hans de Jong
  • 2,030
  • 6
  • 35
  • 55

1 Answers1

1

If the basic form layouts like {{ form }} or {{ form.as_ul }} do not render the way you want, then have a good read of the docs on customizing the form template. Using that, you should be able to render the form the way you want using CSS. You could specify the widget in your form fields to set any attributes required.

Try to avoid rendering form inputs by hand in your templates. It is repetitive, and increases the chances of making mistakes.

Alasdair
  • 298,606
  • 55
  • 578
  • 516