如何使用Django在表单中撰写好文章

时间:2019-02-27 20:43:05

标签: python django django-models django-rest-framework django-views

我正在使用Django 2.1.5

我正在尝试在表单中发布帖子并在sqlite数据库中添加项目,但是它不起作用。

当我尝试添加项目时,这是我的错误:

Request Method: POST
Request URL:    http://127.0.0.1:8080/addBill/
Django Version: 2.1.5
Exception Type: ValueError
Exception Value:    
invalid literal for int() with base 10: 'thetest'
Exception Location: C:\Users\fg\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 965

: 这是我的代码:

facture.html

<body>
<h1> this is the bills template </h1>


<ul>
    {% for all_items in all_items %}
        <li> {{all_items.content}}</li>
    {% endfor %}
</ul>

<form action="/addBill/" method="post" >{% csrf_token %}
    <input type="text" name="content">
    <input type="submit" value="Add">
</form>

</body>

model.py

class Facture(models.Model):
    content = models.TextField()

views.py

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

# Create your views here.

def myView(request):
    all_bill_items=Facture.objects.all()
    return render(request,'facture.html',{
        'all_items':all_bill_items
        })



def addBill(request):
    #create and item
    #save
    #redirect the user
    new_item=Facture(request.POST['content'])
    new_item.save()
    return HttpResponseRedirect('/Home/')

urls.py

from django.contrib import admin
from django.urls import path
from facture.views import myView,addBill

urlpatterns = [
    path('admin/', admin.site.urls),
    path('Home/', myView),
    path('addBill/', addBill),
]

1 个答案:

答案 0 :(得分:0)

实例化模型时,应始终使用关键字参数。

new_item=Facture(content=request.POST['content'])

另外请注意,您实际上应该在这里使用表格。