我正在尝试使用Django 2.7在网页上直接创建新闻,但是在/ home / create /中添加类别和国家/地区IntegrityError时遇到了问题(1048,“ column'country_id'不能为null”) 这是我的代码: home / 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)
home / 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>
请帮助!
答案 0 :(得分:0)
您可以在<select>
标签中指定<select>
输入元素的名称,在 标签中指定 not 。因此,您应该将表单写为:<option>
<select name="Country">
{% if countries %}
{% for el in countries %}
<option>{{ el.name }}</option>
{% endfor %}
{% endif %}
</select>
话虽如此,我强烈建议您与Django forms [Django-doc]合作。这些封装了逻辑,减少了犯错的可能性,并删除了大量样板代码。