我无法将表单数据保存到django中的数据库

时间:2018-04-16 07:51:13

标签: python django forms views models

我想通过表单添加数据,并在我的模板中查看它

博客网址:

urlpatterns = [

    url(r'^admin/',admin.site.urls),
    url(r'^blog/',include('content.urls',)),
]

内容网址:

urlpatterns = [
    url(r'^add/$', views.add_content, name='content'),
]

models.py

from django.db import models

class AddContent(models.Model):
    content_name = models.CharField(max_length=100, default='', blank=False, unique=True)

def __str__(self):
    return self.content_name

forms.py

from django import forms
from .models import AddContent

class AddContentForm(forms.ModelForm):
    class Meta:
        model = AddContentModel
        fields = [
            "content_name",
        ]

views.py

def add_content(request):
    form = AddContentForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return redirect("/blog/content/")

    content_data = AddContent.objects.all()

    context = {
        "form":form,
        "content":content_data,
    }
    return render(request, "add_content.html", context)

def view_content(request):
    view_data = AddContent.objects.all()
    context = {
        "show_content":view_data,
    }
    return render(request, 'show_content.html', context)

模板: add_content.html

{% extends 'base.html' %}

{% block content %}

<form method='POST' action="/blog/content/">
{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Add Content'/>

<h3>Recent content</h3>
{% for show in show_content %}
<p>{{ show.content_name }}</p>
{% endfor %}

{% endblock %}

表单数据未保存,当我通过管理界面添加表单数据时,它会提供结果但表单失败。

(这只是我在括号中写的一些无用的内容,stackoverflow不允许我发帖,因为看起来我的帖子主要是代码;请添加更多详细信息,但我认为代码有很多细节我只是为了长度而不能写任何东西)

4 个答案:

答案 0 :(得分:1)

您的模型表单应如下所示

from django import forms
from .models import AddContent

class AddContentForm(forms.ModelForm):
class Meta:
    model = AddContent
    fields = [
        "content_name",
    ]

您已在模型表单的Meta类中定义了错误的模型名称。它应该是 AddContent 而不是 AddContentModel

答案 1 :(得分:0)

我也是django的新手,但是你不需要在views.py中的函数中指定请求,如:

def add_content(request):
    if(request.method == 'POST'):
        # rest of code here

答案 2 :(得分:0)

您的表单不会发布到保存数据的视图中;它直接发布到view_content视图,该视图完全忽略数据。

您可以将表单操作设置为".",以使其回发到呈现它的同一视图。

(另外一点,您应该避免使用硬编码网址。使用模板中的{% url %}标记和视图中的reverse()函数,根据视图名称输出网址。)

答案 3 :(得分:0)

第一: 更正表单中的重定向()。

Sub Scraping_xScores()

   Dim objIE As Object

   Dim itemEle As Object
   Dim desc As String, pt1 As String, pt2 As String, price As String
   Dim y As Integer

   Sheets("Foglio1").Activate
   Range("A:AA").ClearContents

   Set objIE = CreateObject("internetexplorer.application")
   objIE.Visible = True

   objIE.navigate "http://www.xscores.com/soccer/leagueresults/england/premier_league/2017-2018/r/0"
   Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

   y = 1

   For Each itemEle In objIE.document.getElementsByClassName("score_row match_line e_true")

       'desc = itemEle.getElementsByTagName("a")(0).innerText
       Sheets("Foglio1").Range("A" & y).Value = itemEle.Children(0).innerText
       'put text of 2nd 'td' in col B
        Sheets("Foglio1").Range("B" & y).Value = itemEle.Children(2).innerText
        'put text of 3rd 'td' in col C
        Sheets("Foglio1").Range("C" & y).NumberFormat = "@"
        Sheets("Foglio1").Range("C" & y).Value = itemEle.Children(3).innerText

        'put text of 4th 'td' in col D
        Sheets("Foglio1").Range("D" & y).NumberFormat = "@"
        Sheets("Foglio1").Range("D" & y).Value = itemEle.Children(4).innerText
       y = y + 1
   Next

   objIE.Quit
   Set objIE = Nothing

   Cells.Select
   With Selection
       .HorizontalAlignment = xlGeneral
       .VerticalAlignment = xlBottom
       .WrapText = False
       .Orientation = 0
       .AddIndent = False
       .IndentLevel = 0
       .ShrinkToFit = False
       .ReadingOrder = xlContext
       .MergeCells = False
   End With
   Range("A1").Select
End Sub

第二:您需要为内容视图指定一个URL:view_content

return redirect("add_content", request.POST= None)

您需要一个模板来呈现内容(show_content.html:

url(r'^content/$', views.view_content, name='content'),

修改:

您的表单定义不明确。我编辑我的答案以使其完整:

您必须更正表单中的模型(AddContent而不是AddContentModel):

{% extends 'base.html' %}

    {% block content %}


    <h3>Recent content</h3>
    {% for show in show_content %}
    <p>{{ show.content_name }}</p>
    {% endfor %}

    {% endblock %}