postgresql Django表单查询数据库(模型)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14225601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:42:38  来源:igfitidea点击:

Django form to query database (models)

pythondjangoformspostgresql

提问by Jake D

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:

我的模型(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:

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:

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))

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.

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

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.

我了解表单如何与视图以及后来的模板相关联,但我似乎无法让它工作。

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

我无休止地搜索了 Django 站点和许多其他资源,以寻找我可以学习的示例,但一无所获。

Anyone mind helping me out?

有人介意帮我吗?

Thanks.

谢谢。

回答by Dan Hoerst

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.

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

Try something like this:

尝试这样的事情:

search.html:

搜索.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:

视图.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:

结果.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 %}