M
M
mr_3efup2021-04-23 13:23:04
Django
mr_3efup, 2021-04-23 13:23:04

Keeping previous values ​​after page reload django?

I have a drop down list of countries:

60829f3688aa0763659190.png

models.py code:

from django.db import models


class CountriesView (models.Model):

    name = models.CharField(max_length=100)


views.py code

class IndexView(View):

    def get(self, request, *args, **kwargs):
        countries = CountriesView.objects.all()
        context = {
            'countries': countries,
        }
        return render(request, 'index.html', context=context)

    def post(self, request, *args, **kwargs):

        list_countries = []

        if request.method == 'POST':
            country = request.POST['name']

        list_countries.append(country)
        countries = CountriesView.objects.all()

        # контекст
        context = {
            'countries': countries,
            'list_countries': list_countries,
        }
        return render(request, 'index.html', context=context)


html code:

<body>

<form method="post">
    {% csrf_token %}
    <select name="name">
        <option selected="selected">Страны</option>
        {% for country in countries %}
        <option>{{ country.name }}</option>
        {% endfor %}
    </select>
    <input type="submit" value="Вести">
</form>

{% for c in list_countries %}
    <p>{{ c }}</p>
{% endfor %}

</body>


When I select a country and click on the button, the country is written at the bottom

60829ff676808223342007.png

. But when I select a country again, the previous one is replaced by the current one. And how to make sure that the old one does not disappear, but the new one is written from below, and so on. How to make sure that the data is saved when updating?

[1]: https://i.stack.imgur.com/QAqX8.png
[2]: https://i.stack.imgur.com/CAKaV.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
olexndr090, 2021-04-30
@olexndr090

You can do this with jquery, there's an append function that adds a boring element to the end of the selected element. for example like this:

jQuery("document").ready(function($){
      $('body').on('click', 'input', function() {
           $('p').append($('select').val());
    });
});

This is based on your code, it is better to assign classes to the necessary elements and replace the tag names in brackets with classes. But there is one thing, but I always have a problem with select tags, I don’t know if you will, but if it doesn’t work, try replacing the select tag with input type="list".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question