0
我稱之爲一個Django模型「後」,我想這與URL添加一個帖子的時候:(Django的)獲取主鍵形式提交表單,並使用它重定向
url(r'^newpost/', views.PostFormView.as_view(), name='add'),
它重定向我到後添加的URL的詳細信息頁面:
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並將其重定向到詳細url。
的確如此,我忘記了遷移數據庫。現在它可以工作 – A2maridz