我收到错误 - 找不到关键字参数'{u'slug':None}'的'add_comment'。尝试了1种模式:[u'blog /(?P \ d +)/ comment / $']
我添加了 - app_name ='blog' - 用于解决命名空间
的早期错误的网址但现在我遇到了新的错误
my urls.py
url(r'^(?P<pk>\d+)/comment/$', views.add_comment, name='add_comment')
my views.py
def add_comment(request, slug):
post = get_object_or_404(Post, slug=slug)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('blog:post', slug=post.slug)
else:
form = CommentForm()
template = 'blog/add_comment.html'
context = {'form': form}
return render(request, template, context)
my models.py
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
date = models.DateTimeField()
slug = models.SlugField(max_length=250, blank=True, null=True)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absoulte_url(self):
return reverse('blog:post.html', args=[self.slug])
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', blank=True,
null=True)
user = models.CharField(max_length=250)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
approved = models.BooleanField(default=False)
def approved(self):
self.approved = True
self.save()
def __str__(self):
return self.user
我的模板add_comment.html
{% extends "personal/header.html" %}
{% block content %}
<h1>Add new comment</h1>
<form method='POST'>{% csrf_token %}
{{ from.as_p }}
<button type='submit'>Submit</button>
</form>
{% endblock %}
答案 0 :(得分:0)
这是来自您提供add comment
链接的页面,很可能在详细的博客/帖子页面中。
您正在创建add comment
网址,而不会将pk
参数传递给它。
它应该是类似的东西。
<a href="{% url 'add_comment' blog.pk %}">Add Comment</a>
但您在创建网址时遗漏了blog.pk
或类似post.pk
的内容。
只需这样做,错误就会得到解决。