反转&#39; user_posts&#39;使用关键字参数&#39; {&#39;用户名&#39;:&#39;&#39;}&#39;未找到。尝试了1种模式:[&#39; posts / by /(?P <username> [ - \\ w] +)/ $&#39;]?

时间:2017-09-14 20:39:43

标签: python django django-templates django-views django-urls

我一直在django中收到此错误: NoReverseMatc ,我无法弄清楚原因。

my models.py:

from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models

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")
   created_at = models.DateTimeField(auto_now=True)
   message = models.TextField()
   message_html = models.TextField(editable=False)
   group = models.ForeignKey(Group, related_name="posts",null=True, blank=True)

   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:single",
           kwargs={"username": self.user.username,"pk": self.pk})


   class Meta:
       ordering = ["-created_at"]
       unique_together = ["user", "message"]

my views.py:

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin

from django.core.urlresolvers import reverse_lazy
from django.http import Http404
from django.views import generic

from braces.views import SelectRelatedMixin

from . import forms
from . import models

from django.contrib.auth import get_user_model
User = get_user_model()

class PostList(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 PostDetail(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 CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView):
    # form_class = forms.PostForm
    fields = ('message','group')
    model = models.Post

    # def get_form_kwargs(self):
    #     kwargs = super().get_form_kwargs()
    #     kwargs.update({"user": self.request.user})
    #     return kwargs

    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 DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView):
    model = models.Post
    select_related = ("user", "group")
    success_url = reverse_lazy("posts:all")

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(user_id=self.request.user.id)

    def delete(self, *args, **kwargs):
        messages.success(self.request, "Post Deleted")
        return super().delete(*args, **kwargs)

my urls.py 是这样的:

from django.conf.urls import url
from . import views

app_name='posts'

urlpatterns = [
    url(r"^$", views.PostList.as_view(), name="all"),
    url(r"new/$", views.CreatePost.as_view(), name="create"),
    url(r"by/(?P<username>[-\w]+)/$",views.UserPosts.as_view(),name="user_posts"),
    url(r"by/(?P<username>[-\w]+)/(?P<pk>\d+)/$",views.PostDetail.as_view(),name="single"),
    url(r"delete/(?P<pk>\d+)/$",views.DeletePost.as_view(),name="delete"),
]

my _post.html

&#13;
&#13;
<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:single' 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 and not hide_delete %}
                <a href="{% url 'posts:delete' pk=post.pk %}" title="delete" class="btn btn-simple">
                    <span class="glyphicon glyphicon-remove text-danger" aria-hidden="true"></span>
                    <span class="text-danger icon-label">Delete</span>
                </a>
            {% endif %}
        </div>
    </div>
</div>
&#13;
&#13;
&#13;

我还有一个名为&#39;问题的应用程序&#39;在我的项目中,它几乎使用了短语,所以可能是问题,但我不确定。

2 个答案:

答案 0 :(得分:0)

在您的user_posts网址中,您还需要传递username,通过定义 success_url

来完成
from django.views.generic import ListView

class UserPosts(ListView):
   model = models.Post
   template_name = "posts/user_post_list.html"

   def get_queryset(self):
        .. . . 

   def get_context_data(self, **kwargs):
        . . . . 

   def get_success_url(self):
       username = self.kwargs['username']
       return reverse('user_posts', kwargs={'username': username})

答案 1 :(得分:0)

您在模板文件中指定的url名称为'for_user'。该名称与urls.py文件中定义的url名称(名称=“ user_posts”)不匹配。这两个名称对于django必须相同,以便能够在urlpatterns中建立匹配。另外,您代码中的网址格式也适用于django 1.11或更低版本。

但是,如果您使用的是django 2.0或更高版本,请在下面使用以下两个网址之一;

from django.urls import path, re_path
urlpatterns = [
    re_path(r'^by/(?P<username>\w+)/$', views.UserPosts.as_view(), name='for_user'),
    path('by/<slug:username>/', views.UserPosts.as_view(), name='for_user')
]