我收到NoReverseMatch错误,其中包含kwargs的空白字符串。我在models.py文件中做错了什么,没有保存与帖子相关的用户名?
在/ groups / posts / in / nasa-rocks /为'for_user'反向的NoReverseMatch 找不到带有关键字参数'{'username':''}'的关键字。 1个图案 尝试过的:['posts / by /(?P [^ /] +)/ $']
models.py:
from django.db import models
from django.urls import reverse
from django.conf import settings
# Create your models here.
import misaka
from groups.models import Group
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
user = models.ForeignKey(User,related_name='posts',on_delete='CASCADE')
group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete='CASCADE')
created_at = models.DateTimeField(auto_now=True)
message = models.TextField()
message_html = models.TextField(editable=False)
def __str__(self):
return self.message
def save(self,*args,**kwargs):
self.message_html = misaka.html(self.message)
super().save(*args,**kwargs)
def get_absolute_url(self):
return reverse('posts:detail',kwargs={'username':self.user.username,'pk':self.pk})
class Meta:
ordering = ['-created_at']
unique_together = ['user','message']
urls.py:
from django.urls import path
from . import views
app_name = 'posts'
urlpatterns = [
path('',views.PostListView.as_view(),name='list'),
path('create/',views.PostCreateView.as_view(),name='create'),
path('by/<username>/',views.UserPosts.as_view(),name='for_user'),
path('by/<username>/<pk>/',views.PostDetailView.as_view(),name='detail'),
path('delete/<pk>/',views.PostDeleteView.as_view(),name='delete')
]
views.py:
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.views import generic
from django.http import Http404
from braces.views import SelectRelatedMixin
from . import models
from . import forms
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your views here.
class PostListView(SelectRelatedMixin,generic.ListView):
model = models.Post
select_related = ('user','group')
class UserPosts(generic.ListView):
model = models.Post
template_name = 'posts/user_post_list.html'
def get_queryset(self):
try:
self.post_user = User.objects.prefetch_related("posts").get(
username__iexact=self.kwargs.get("username")
)
except User.DoesNotExist:
raise Http404
else:
return self.post_user.posts.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["post_user"] = self.post_user
return context
class PostDetailView(SelectRelatedMixin,generic.DetailView):
model = models.Post
select_related = ('user','group')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user__username__iexact=self.kwargs.get('username'))
class PostCreateView(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView):
fields = ('message','group')
model = models.Post
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class PostDeleteView(LoginRequiredMixin,SelectRelatedMixin,generic.DeleteView):
model = models.Post
select_related = ('user','group')
success_url = reverse_lazy('posts:list')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user_id=self.request.user.id)
def delete(self,*args,**kwargs):
message.success(self.request,'Post Deleted')
return super().delete(*args,**kwargs)
_post.html:
<div class="post media">
<h3>{{post.message_html|safe}}</h3>
<div class="media-body">
<strong>{{post.user.username}}</strong>
<h5 class="media-heading">
<span class="username">
<a href="{% url 'posts:for_user' username=post.user.username %}">@{{ post.user.username }}</a>
</span>
<time class="time">
<a href="{% url 'posts:detail' username=post.user.username pk=post.pk %}">{{ post.created_at }}</a>
</time>
{% if post.group %}
<span class="group-name">in <a href="#">{{ post.group.name }}</a></span>
{% endif %}
</h5>
<div class="media-footer">
{% if user.is_authenticated and post.user == user %}
<a href="{% url 'posts:delete' pk=post.pk %}" title='delete' class="btn btn-simple">
<span class="fas fa-trash-alt text-danger" aria-hidden="True"></span>
<span class="text-danger icon-label">Delete</span>
</a>
{% endif %}
</div>
</div>
</div>
答案 0 :(得分:-1)
据我了解,问题是用户名为空。默认模式要求它至少是一个符号['posts/by/(?P[^/]+)/$']
。因此很可能您没有正确获取模型或没有发布用户。
顺便说一句,错误很冗长。它显示了模式和参数,您需要仔细阅读。