B
B
becks2014-06-16 23:33:16
Django
becks, 2014-06-16 23:33:16

How to show data in django template filtered by user criteria?

I learn django (and the web in general) by trial and error on a home project.
There is a simple model:

class CrArchive(models.Model):
    cr_id = models.IntegerField(primary_key=True)
    type = models.ForeignKey(CrType, db_index=True)   
    cr_description = models.TextField(blank=True)
    latitude = models.FloatField(blank=True)
    longitude = models.FloatField(blank=True)

    class Meta:
        managed = False
        db_table = 'cr_archive'
For reference, I wrote a view for her:
def index(request):
    latest_crime_list = CrArchive.objects.order_by('-cr_id')[:5]
    context = {'latest_crime_list': latest_crime_list, }
    return render(request, 'archive/archive.html', context)

And part of the template below it:
<div class="row">
        {% if latest_crime_list %}
            {% for crime in latest_crime_list %}
            <div class="col-md-12">
            	<div class="bs-callout bs-callout-warning">
            		<h4>{{ crime.latitude }} | {{ crime.longitude }}  | {{ crime.type }}</h4>
            		<p>{{ crime.cr_description }}</p>
            	</div>
            </div>
            {% endfor %}
        {% endif %}
  </div>

The last 5 records from cr_archive are displayed fine.
Now I decided to complicate the task. Suppose the user decides to display all records where latitude = 34.567 (the latitude value, for example, is entered in some component on the page). Here I have a plug. I don't really understand how to pass this filter to the model and filter the values ​​and how to remake the view. And how not to display anything if the filter search is not running? Please help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Soshnikov, 2014-06-17
@becks

Familiarize yourself with forms
https://docs.djangoproject.com/en/dev/topics/forms/
Get data, validate, then you can use this data as you like.
For example:
latest_crime_list = CrArchive.objects.filter(latitude=latitude).order_by('-cr_id')[:5]
As an option, if the coordinates are saved and you can choose from the existing ones instead of forcing the user to enter, then extract the parameter from the address:
url(r'^/places/latitude/(.+)', places_views.show_latitude),
and in views use this option.
Examples and docks shaft, write in detail vlom. If you want, put the project on bitbucket or github - it will be faster to show the code than to explain :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question