gpt4 book ai didi

python -/home/create/处的完整性错误(1048, "Column 'country_id'不能为空”)

转载 作者:太空宇宙 更新时间:2023-11-03 19:59:10 25 4
gpt4 key购买 nike

我尝试使用 Django 2.7 直接在网页上创建新闻,但在/home/create/处添加类别和国家/地区时出现 IntegrityError 问题(1048,“列 'country_id' 不能为空”)这是我的代码:首页/models.py

class Category(models.Model):

name = models.CharField(max_length=255)

def __str__(self):
return self.name


class Country(models.Model):

name = models.CharField(max_length=255)

def __str__(self):
return self.name


class News(models.Model):

pub_date = models.DateTimeField('Date: ')
article = models.CharField(max_length=200)
content = models.TextField(default="")
country = models.ForeignKey(Country, on_delete=models.CASCADE)
likes = models.IntegerField(default=0)
category = models.ForeignKey(Category, on_delete=models.CASCADE)

def __str__(self):
return self.article

def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

首页/views.py

def create(request):

if request.method == "POST":
adding = News()
adding.likes = 0
adding.pub_date = timezone.now()
adding.article = request.POST.get("Article")
adding.content = request.POST.get("Content")
adding.category = request.POST.get("Category")
adding.country = request.POST.get("Country")
adding.save()

return HttpResponseRedirect("/home/")

home/urls.py

from django.urls import path

from . import views

app_name = 'home'
urlpatterns = [
path('', views.index, name='index'),
path('<int:news_id>/', views.detail, name='detail'),
path('create/', views.create),
path('<int:news_id>/delete/', views.delete_news, name='delete'),

]

index.html(我从主页添加帖子)

<body>
<form method="POST" action="create/" class="post_form">
{% csrf_token %}

<p>
<label>Article</label><br>
<input type="text" name="Article" />
</p>

<p>
<label>Content</label><br>
<input type="text" name="Content" />
</p>
<p>
<label>Category</label><br>
<select>
{% if category %}
{% for el in category %}
<option name="Category">{{ el.name }}</option>
{% endfor %}
{% endif %}
</select>
</p>
<p>
<label>Country</label><br>
<select>
{% if countries %}
{% for el in countries %}
<option name="Country">{{ el.name }}</option>
{% endfor %}
{% endif %}
</select>
</p>
<input type="submit" value="Submit" >
</form>
</body>

请帮忙!

最佳答案

您指定 <select> 的名称<select> 中的输入元素标签,不在 <option> 标签。因此,您应该将表单编写为:

<select <b>name="Country"</b>>
{% if countries %}
{% for el in countries %}
<option>{{ el.name }}</option>
{% endfor %}
{% endif %}
</select>

话虽这么说,我强烈建议您与 Django forms [Django-doc] 合作。 。这些封装了逻辑,降低了出错的可能性,并删除了大量样板代码。

关于python -/home/create/处的完整性错误(1048, "Column 'country_id'不能为空”),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59356880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com