我有一个名为“post”的django模型,我想在添加网址时添加帖子:
url(r'^newpost/', views.PostFormView.as_view(), name='add'),
它将我重定向到添加的帖子的详细信息页面,其中包含网址:
url(r'^(?P<pk>[0-9]+)/$', PostDetailView, name='detail'),
其中pk是id(添加帖子的主键)
我的帖子模型如下:
class Post(models.Model):
person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
speciality = models.ForeignKey(Speciality, on_delete=models.CASCADE)
level = models.ManyToManyField(Level)
date_post = models.DateTimeField()
title = models.CharField(max_length=200)
description = models.CharField(max_length=1000)
is_deleted = models.BooleanField(default=False)
date_delete = models.DateTimeField()
我的PostFormView视图添加了一个新帖子:
class PostFormView(View):
form_class = PostCreationForm
template_name = 'posts/new_post.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.person_id=request.user.id
post.save()
if post is not None:
return redirect('posts:detail', post.id)
我的提交表格如下:
<form class="form-horizontal" role="form" action="{% url 'posts:detail' pk=1 %}" method="post">
{% csrf_token %}
{% include 'form-template.html' %}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-success"> Add the post </button>
</div>
</div>
</form>
如果我把空行动“”或我将网址更改为另一个视图或我删除表单中的pk我会收到此错误:
OperationalError at /posts/newpost/
table posts_post has no column named person_id
如何提交表单,获取提交的帖子的ID并将其重定向到详细网址。
答案 0 :(得分:1)
此错误与提交或重定向无关。
您已将person
字段添加到模型中,但您尚未运行数据库迁移。