그래서 데이터베이스를 쿼리하는 데 사용할 단일 입력 필드가있는 슈퍼 기본 폼을 만들고 싶습니다.Django 폼에서 쿼리 데이터베이스 (모델)
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"를 수집 할 다음과 같이
내 모델 (models.py
)입니다 사용자가 책 모델 인스턴스의 모든 데이터를 표시합니다. e uid는 데이터베이스의 일부 책입니다.
폼이 뷰와 연결된 방식과 이후 템플릿에 대한 이해를 가지고 있지만 제대로 작동하지 않는 것 같습니다.
나는 장고 사이트와 다른 많은 자료들을 내가 배울 수있는 예제로 끊임없이 찾았지만 아무것도 찾지 못했다.
나를 도와주는 사람이 있습니까?
감사합니다.
? 양식 코드는 어디에 있습니까? –
Aamir가 말했듯이, 이미 시도한 코드 중 일부는 문제가있는 부분을 찾는데 도움이 될 수 있습니다. – asermax
Anthony, 폼 코드를 사용하여 질문을 편집하고 처리 할보기를 편집하십시오. –