【发布时间】:2012-12-22 22:22:53
【问题描述】:
所以我想创建一个带有单个输入字段的超级基本表单,用于查询我的数据库。
我的模型(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 是数据库中的某本书。
我了解表单如何与视图以及后来的模板相关联,但我似乎无法让它发挥作用。
我在 Django 网站和许多其他资源中无休止地搜索了一个我可以从中学习的示例,但一无所获。
有人介意帮助我吗?
谢谢。
【问题讨论】:
-
您的具体问题是什么?你的表单代码在哪里?
-
正如 Aamir 所说,您已经尝试过的一些代码可能会帮助我们找到您遇到问题的地方。
-
Anthony,请使用表单代码和应该处理它的视图编辑您的问题。
-
你为什么要删除你的问题的内容并用 .... 替换它?
标签: python django forms postgresql