2

我正在尝试配置HTML form为使用Django Models而不是使用框架中的内置Forms。我使用下面的表格制作了表格,并Html粘贴了 和 的代码。问题是当我单击按钮时,它没有执行任何操作。我可以查看表格,但它没有达到目的。我知道这个问题很蹩脚,但是如何配置 HTML 以使用 django 模型以便将数据保存到数据库中?ModelViewUrls.pysubmit

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body style="font-family:Courier New">
    <h1>Add / Edit Book</h1>
    <hr/>
    <form id="formHook" action="/istreetapp/addbook" method="post">
        <p style="font-family:Courier New">Name <input type="text" placeholder="Name of the book"></input></p>
        <p style="font-family:Courier New">Author <input type="text" placeholder="Author of the book"></input></p>
        <p style="font-family:Courier New"> Status
            <select>
                <option value="Read">Read</option>
                <option value="Unread">Unread</option>
            </select>
        </p>
    <input type="submit" id="booksubmit" value="Submit"></input>
</form>
</body>
</html>

看法

from django.shortcuts import HttpResponse
from istreetapp.models import bookInfo
from django.template import Context, loader
from django.shortcuts import render_to_response

def index(request):
    booklist = bookInfo.objects.all().order_by('Author')[:10]
    temp = loader.get_template('app/index.html')
    contxt = Context({
        'booklist' : booklist,
    })
return HttpResponse(temp.render(contxt))

模型

from django.db import models

class bookInfo(models.Model):
    Name = models.CharField(max_length=100)
    Author = models.CharField(max_length=100)
    Status = models.IntegerField(default=0) # status is 1 if book has been read

def addbook(request, Name, Author):
    book = bookInfo(Name = Name, Author=Author)
    book.save
    return render(request, 'templates/index.html', {'Name': Name, 'Author': Author})

网址.py

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('app.views',
    url(r'^$', 'index'),
    url(r'^addbook/$', 'addbook'),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)
4

2 回答 2

2

您需要在 html 表单中添加名称属性,然后在视图中处理表单提交。就像是 -

from django.http import HttpResponseRedirect
from django.shortcuts import render

def book_view(request):
    if request.method == 'POST':
        name = request.POST['name']
        author = request.POST['author']
        book = BookInfo(name=name, author=author)
        if book.is_valid():
            book.save()
            return HttpResponseRedirect('your_redirect_url')
    else:
        return render(request, 'your_form_page.html')

查看request.POST 字典上的文档。

但是,您真的会更好地使用 django ModelForm 来执行此操作 -

class BookForm(ModelForm):
    class Meta:
        model = BookInfo # I know you've called it bookInfo, but it should be BookInfo

那么在你看来——

from django.http import HttpResponseRedirect
from django.shortcuts import render

def book_view(request, pk=None):
    if pk:
        book = get_object_or_404(BookInfo, pk=pk)
    else:
        book = BookInfo()
    if request.method == 'POST':
        form = BookForm(request.POST, instance=book)
        if form.is_valid():
            book = form.save()
            return HttpResponseRedirect('thanks_page')
    else:
        form = BookForm(instance=book)
    return render(request, 'your_form_page.html', {'form': form)

并且your_form_page.html可以很简单 -

<form action="{% url book_view %}" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

查看有关使用表单的文档。

于 2013-03-02T09:36:27.187 回答
2

您忘记在每个输入中定义名称

<form id="formHook" action="/addbook/" method="post">
    {% csrf_token %}
    <p style="font-family:Courier New">
        Name <input type="text" name="name" placeholder="Name of the book"></input>
    </p>

    <p style="font-family:Courier New">
        Author <input type="text" name="author" placeholder="Author of the book"></input>
    </p>

    <p style="font-family:Courier New"> 
        Status
        <select name="status">
            <option value="Read">Read</option>
            <option value="Unread">Unread</option>
        </select>
    </p>
    <input type="submit" id="booksubmit" value="Submit"></input>
</form>

您的addbook 必须在 views.py 中,而不是在您的 models.py 中。您不必在渲染中定义 templates/index.html,在您的设置中可以理解

def addbook(request):
    if request.method == 'POST':
        name = request.POST['name']
        author = request.POST['author']
        bookInfo.objects.create(Name = name, Author=author)
        return render(request, 'index.html', {'Name': name, 'Author': author})

主 urlconf

from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', 'project_name.views.index'),
    url(r'^addbook/$', 'project_name.views.addbook'),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)
于 2013-03-02T10:00:17.097 回答