Python Django表单查询数据库(模型)
因此,我想创建一个带有单个输入字段的超级基本表单,用于查询我的数据库 我的模型(Python Django表单查询数据库(模型),python,django,forms,postgresql,Python,Django,Forms,Postgresql,因此,我想创建一个带有单个输入字段的超级基本表单,用于查询我的数据库 我的模型(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' f
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.")
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))
views.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.")
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”,并显示图书模型实例中的所有数据,其中uid是数据库中的某本书
我了解表单是如何与视图以及以后的模板联系在一起的,但我似乎无法让它正常工作
我一直在Django网站和许多其他资源中寻找一个我可以学习的例子,但什么都没有
有人介意帮我吗
谢谢。您可以在这里进行简单的搜索。您不需要任何POST调用或表单创建。但是,如果您想创建表单,这仍然应该为您指明正确的方向 试着这样做: 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>
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 %}
{%if结果%}
{结果中的结果为%}
{{result.uid}
{{result.xxxx}
{{result.xxxx}
{%endfor%}
{%else%}
请输入有效的UID
搜索记事卡:
{%endif%}
您的具体问题是什么?您的表单代码在哪里?正如Aamir所说,您已经试用过的一些代码可能会帮助我们找到您遇到问题的地方。Anthony,请用表单代码编辑您的问题,以及应该处理它的视图。为什么您要删除问题的内容,并将其替换为?您要传递给搜索框的确切查询是什么?这是一个类型错误,因此它不会命中except块。Exception块正在排除值错误。你能用你在模板和搜索视图中如何实现搜索框来编辑你的原始帖子吗?你需要设置一个默认视图,例如home
。这可能非常简单,并将加载search.html(搜索框)。在搜索框中输入查询后,将加载搜索视图。听起来像是直接进入搜索视图-结果是q
等于None
。我强烈建议学习Django教程。非常好。一旦你设置了教程应用程序,你就可以将上面的建议添加到应用程序中,并查看它们是如何工作的。然后你可以重复使用你的应用程序所需的部分。此代码不适用于我,错误为异常值:赋值前引用的局部变量“results”
。我的表单操作是post,但我甚至无法到达那里,因为您的方法没有初始视图。