Django form to query database (models)

后端 未结 1 1167
我寻月下人不归
我寻月下人不归 2020-12-13 16:59

So I want to create a super basic form with a single input field which will be used to query my database.

My model (models.py) is as follows:

         


        
1条回答
  •  暖寄归人
    2020-12-13 17:03

    You can do a simple search here. You do not need any POST calls or form creation. However, if you want to create a form this should still point you in the correct direction.

    Try something like this:

    search.html:

    Search Notecards:

    views.py:

    from myapp.models import Book
    from django.template import RequestContext
    from django.shortcuts import render_to_response
    
    def search(request):
        query = request.GET.get('q')
        try:
            query = int(query)
        except ValueError:
            query = None
            results = None
        if query:
            results = Book.objects.get(uid=query)
        context = RequestContext(request)
        return render_to_response('results.html', {"results": results,}, context_instance=context)
    

    results.html:

    {% if results %}
      {% for result in results %}
        {{ result.uid }}
        {{ result.xxxx }}
        {{ result.xxxx }}
      {% endfor %}
    {% else %}
        

    Please enter a valid UID

    Search Notecards:
    {% endif %}

    0 讨论(0)
提交回复
热议问题