【问题标题】:How to configure HTML form to work with django models?如何配置 HTML 表单以使用 django 模型?
【发布时间】:2013-03-02 09:30:32
【问题描述】:

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

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

Urls.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)),
)

【问题讨论】:

    标签: python html django


    【解决方案1】:

    您忘记在每个输入中定义 name

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

    【讨论】:

    • 我已经按照你说的添加了urlpatterns,但是当我点击提交数据时,url 找不到addbook 视图。有没有其他方法可以将url 添加到“表单”操作中?
    • 我的 urls.py 在项目目录中。我用过这个,但urlpatterns 问题仍然存在。我尝试将一个新的urlpatterns 与原来的连接起来。还是不行。
    • @mozart 好的,我更新了答案,抱歉,我忘了在 url 中添加视图,这就是它不起作用的原因
    • 我已经尝试过了。我应该添加一个新模板addbook吗?
    • 好多了,这样您就无法在表单中输入 url
    【解决方案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 字典中的 docs

    但是你真的会更好用 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>
    

    查看docs 使用表单。

    【讨论】:

    • 它现在说:'url' 需要一个非空的第一个参数。这是什么意思?
    • {% url book_view %} 标签出错。阅读功能 - docs.djangoproject.com/en/dev/topics/http/urls/…
    • 您可以将其替换为实际的 url 以使其工作,但您不应该使用硬编码的 url - 请阅读 reverse 函数以了解它的工作原理(您需要对您的 url.conf 进行更改)。
    猜你喜欢
    • 2018-03-17
    • 1970-01-01
    • 2023-02-12
    • 2013-10-20
    • 2017-05-01
    • 2016-06-02
    • 2018-05-27
    • 1970-01-01
    • 2015-11-21
    相关资源
    最近更新 更多