Django form to query database (models)

后端 未结 1 1168
我寻月下人不归
我寻月下人不归 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:

    <form method="get" action="/search/">
      Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/>
      <input type="submit" value="Search" />
    </form>
    

    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 %}
        <h3 class='error'>Please enter a valid UID</h3>
        <form method="get" action="/search/">
          Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/>
          <input type="submit" value="Search" />
        </form>
    {% endif %}
    
    0 讨论(0)
提交回复
热议问题