简体   繁体   English

如何配置HTML表单以使用Django模型?

[英]How to configure HTML form to work with django models?

I am trying to configure HTML form to work with Django Models rather than using built-in Forms in the framework. 我正在尝试配置HTML form以与Django Models使用,而不是在框架中使用内置的Forms I have made the form using Html below and have pasted the code for Model , View and Urls.py . 我在下面使用Html制作了表格,并粘贴了ModelViewUrls.py的代码。 The problem is when I click the submit button, it doesn't perform any action. 问题是当我单击“ submit按钮时,它不执行任何操作。 I am able to view the form but it doesn't serves the purpose. 我可以查看该表格,但没有达到目的。 I know the question is very lame, but how would configure the HTML to work with the django model so that the data can be saved to the database? 我知道这个问题非常la脚,但是如何配置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>

View 视图

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

Model 模型

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

You need to add name attributes to your html form then process the form submission in the view. 您需要将名称属性添加到html表单,然后在视图中处理表单提交。 Something like - 就像是 -

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

Have a look at the docs on the request.POST dictionary. 看看request.POST词典上的文档

However you really would be better off doing this with a django ModelForm - 但是,使用django ModelForm进行操作确实会更好-

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

then in your view - 然后在您看来-

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)

And your_form_page.html can be as simple as - 而且your_form_page.html可以很简单-

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

Have a look at the docs on working with forms. 看一下使用表单的文档

You forgot to define name in each of your input 您忘记在每个输入中定义名称

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

Your addbook must be in the views.py not in your models.py. 您的Addbook必须在views.py中,而不能在models.py中。 You don't have to define templates/index.html in your render, it is understood in your settings 您无需在渲染中定义template / 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})

main urlconf 主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)),
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM