Django表单来查询数据库(模型) [英] Django form to query database (models)

查看:69
本文介绍了Django表单来查询数据库(模型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想创建一个具有单个输入字段的超基本表单,该表单将用于查询我的数据库。

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

我的模型( models.py )如下:

from django.db import models

class Book(models.Model):
    uid = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=30)
    class Meta:
        db_table = u'books'

forms.py

from django import forms
from myapp.models import Book

class EnterIDForm(forms.form):
book_id = forms.CharField()
# add a custom clean function to validate that the user input
#  is a valid book ID
def clean_book_id(self):
    try:
        book_id = int(self.cleaned_data["book_id"])
    except:
        book_id = None

    if book_id and Book.objects.filter(uid=book_id).count():
        return book_id
    else:
        raise forms.ValidationError("Please enter a valid book ID number.")

views.py

from django.shortcuts import render_to_response
from myapp.models import Book

def form_view(request):
    if request.method == "POST":
        # the user has submitted the form, see if we have a book
        book_id_form = EnterIDForm(request.POST) # instantiate our form class with the user data
        if book_id_form.is_valid():
            # if our form is valid, then we have a book_id that works:
            the_book = Book.objects.get(uid=book_id_form.cleaned_data["book_id"])
                return render_to_response("book_template.html", { "the_book": the_book }, context_instance=RequestContext(request))
        # if the form wasn't valid, it will fall through to the other return statement.
    else:
        # If the user didn't submit a form, instantiate a blank one.
        book_id_form = EnterIDForm()
    return render_to_response("form_template.html", { "book_id_form": book_id_form }, context_instance=RequestContext(request))

我希望输入字段从用户那里收集 uid并显示Book模型实例中的所有数据,其中uid是数据库中的某些书。

I want the input field to collect the "uid" from the user and display the all of the data from the Book model instance where uid is some book in the database.

我对表单与视图以及后面的模板的联系方式有所了解,但是我似乎无法使其正常工作。

I have an understanding of how the form is tied in with the view, and later templates, but I just cannot seem to get it to work.

我无休止地搜索了Django网站和许多其他资源,以作为我可以从中学习的示例,但一无所获。

I've endlessly searched the Django site and many other resources for an example I can learn from, but nothing.

任何人都介意

谢谢。

推荐答案

您可以简单的搜索在这里。您不需要任何POST调用或创建表单。但是,如果要创建表单,这仍应指向正确的方向。

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.

尝试类似以下操作:

search.html:

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:

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 %}

这篇关于Django表单来查询数据库(模型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆