get_absolute_url没有任何效果

时间:2018-01-04 09:46:21

标签: python django django-templates

我只在我的模板中使用过它。我正在学习一个教程。在教程视频中工作,但我无法使其工作。这是我的模板代码:

<i>     {% for object in object_list %}
    <div class="media">
        <div class="media-left">
            <a href="#">
                {% if object.img %} <img class="media-object" src="..." alt="...">
                {% endif %}
            </a>
        </div>
        <div class="media-body">
            {{ object.content }}<br/>
            via {{ object.user }} | {{ object.timestamp|timesince }} ago |
            <a href='{{ object.get_absolute_url }}'>View</a>
        </div>
    </div>
    <hr/> </i>

我的views.py

<i>

在此处创建您的观点。

class TweetCreateView(FormUserNeededMixin, CreateView):
    form_class = TweetModelForm
    template_name = 'tweets/create_view.html'



class TweetUpdateView(LoginRequiredMixin, UserOwnerMixin, UpdateView):
    form_class = TweetModelForm
    queryset = Tweet.objects.all()
    template_name = 'tweets/update_view.html'
    success_url = '/tweets/'


class TweetDeleteView(LoginRequiredMixin, DeleteView):
    model = Tweet
    template_name = 'tweets/delete_confirm.html'
    success_url = reverse_lazy('tweets:home')


class TweetDetailView(DetailView):
    template_name = "tweets/detail_view.html"
    queryset = Tweet.objects.all()

    def get_object(self):
        print(self.kwargs)
        pk = self.kwargs.get("pk")
        print(pk)
        return Tweet.objects.get(id=pk)


class TweetListView(ListView):
    template_name = "tweets/tweets_list.html"


    def get_queryset(self, *args, **kwargs):
        qs = Tweet.objects.all()
        print(self.request.GET)
        query = self.request.GET.get("q", None)
        if query is not None:
            qs = qs.filter(Q(content=query))
        return qs

    def get_context_data(self, *args, **kwargs):
        context = super(TweetListView, self).get_context_data(*args, **kwargs)
        context['create_form'] = TweetModelForm()
        context['create_url'] = reverse_lazy('tweets:create')
        return context


</i>

my models.py

<i>

class Tweet(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, )
    content = models.CharField(max_length=140, validators=[ validate_content ])
    updated = models.DateField(auto_now=True, )
    timestamp = models.DateField(auto_now_add=True, )

    def __str__(self):
        return str(self.content)
</i>

1 个答案:

答案 0 :(得分:0)

你必须将methode get_absolute_url添加到模型中,它应该是这样的:

def get_absolute_url(self):
    from django.urls import reverse
    return reverse('tweets:detail', kwargs={
        'pk': self.pk
    })