TemplateView在Django get_absolute_url

时间:2018-07-25 12:02:29

标签: django python-3.x django-templates django-views

我有一个report应用,可以管理我项目中所有不当内容的标记。成员reporter可以举报另一个成员reported张贴不当内容。一切正常,并创建了报告对象,但最终它不会重定向到感谢页面。但返回到相同的表单页面。十分奇怪的是,当我在地址栏中粘贴http://127.0.0.1:8000/report/thanks/时,我惊讶地看到了表单页面。通常,报告页面的网址为http://127.0.0.1:8000/report/Amanda/,这到底是哪里出了问题。

下面是我的 models.py

class Report(models.Model):
    reporter = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='reporting_members')
    reported = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='reported_members')
    report_url = models.URLField(max_length=2000, blank=True, null=True)
    reported_at = models.DateTimeField(auto_now_add=True)
    reporting_choices = (
        ('1', 'The images posted by this user are not relevant to the Post),
        ('2', 'Rude or abusive content, The words chosen by the user are inappropriate'),
        ('3', 'This user is asking me to change my review in return for favor '),
        ('4', 'Other'),
    )
    reason_to_report = models.CharField(max_length=1, choices=reporting_choices)
    reason = models.TextField(blank=True, null=True)

    def __str__(self):
        return '{} is reporting {} for {}'.format(self.reporter, self.reported, self.reason_to_report)

    def get_absolute_url(self):
        return reverse('report:thanks')

下面是我的 views.py

class ReportCreateView(LoginRequiredMixin, CreateView):
    model = Report
    fields = ('reason_to_report', 'reason')

    def form_valid(self, form):
        form.instance.reporter = self.request.user
        form.instance.reported = User.objects.get(username=self.kwargs.get('username'))
        next = self.request.POST.get('next')
        form.instance.report_url = next
        super().form_valid(form)
        return redirect('report:thanks')




class ThanksView(LoginRequiredMixin, TemplateView):
    template_name = 'report/thanks.html'

以下是我的 urls.py

urlpatterns = [
    url(r'^(?P<username>[-\w]+)/$', views.ReportCreateView.as_view(), name='report_user'),
    url(r'^thanks/$', views.ThanksView.as_view(), name='thanks'),

]

下面是我的报告表单的模板

<form action="" method="post" >
    {% csrf_token %}
    {% bootstrap_form form %}
      <input type="hidden" name="next" value="{{ request.META.HTTP_REFERER }}">    
      <input class="btn btn-primary" type="submit" />
      <a href="{% url 'home' %}">
         <button class="btn btn-default">Cancel</button>
      </a>
 </form>

1 个答案:

答案 0 :(得分:2)

"thanks"是您的用户名正则表达式的匹配字符串。 Django始终采用第一个匹配的模式,因此将路由到reportcreate视图。

交换网址格式的顺序。