类视图和NoReverseMatch

时间:2019-02-06 23:51:03

标签: python django

我是编码新手,尤其是使用Django的新手。我想为我和其他学生建立一个小的“论坛”,并且效果很好。

我一次又一次遇到一个错误:

Exception Type: NoReverseMatch
Exception Value: Reverse for 'thread-create' with 
  arguments '('',)' not found. 1 pattern(s) tried: ['forum/(?P<pk>[0-9]+)/add/$']

我可以使用函数而不是基于类的View来解决它,但是我怀疑那是应该这样做的。

在使用类视图时,我感到自己缺少一些非常重要的东西。

如果有人可以帮助我,我真的很感激:-)

这是无效的链接:

{% url 'user-posts' thread.author.username %}

更重要的是:

{% url 'forum:thread-create' thread.id %}

使用类时还不起作用的是:

{% for thread in thema.thread_set %} (works with the functions)

(我只想查看绑定到特定主题的线程。这对于函数也很好用)。

您可能还会问为什么我不仅仅使用基于函数的视图:

  • 我想知道我在做什么错
  • 我希望能够轻松对我的网站进行分页。

代码:

# models.py

from django.db import models
from django.urls import reverse
from PIL import Image
from django.utils import timezone
from django.contrib.auth.models import User


class Thema(models.Model):
    themengebiet = models.CharField(max_length=350)
    beschreibung = models.TextField()
    themen_logo = models.FileField(max_length=350, upload_to="logos",        default='default.jpg')
    erstellt_am = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.themengebiet

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

       img = Image.open(self.themen_logo.path)

       if img.height > 300 or img.width > 300:
           output_size = (300, 300)
           img.thumbnail(output_size)
           img.save(self.themen_logo.path)


class Thread(models.Model):
    thema = models.ForeignKey(Thema, on_delete=models.CASCADE)
    titel = models.CharField(max_length=350)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    erstellt_am = models.DateTimeField(default=timezone.now)
    thread_logo = models.ImageField(upload_to="logos", d  efault='default.jpg')

    def get_absolute_url(self):
        return reverse('forum:thread-page', kwargs={'pk': self.thema.id})

   def __str__(self):
        return self.titel


class Posting(models.Model):
    thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
    titel = models.CharField(max_length=350)
    erstellt_am = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    inhalt = models.TextField()

    def __str__(self):
        return self.titel

views.py

from django.views import generic
from django.views.generic import CreateView, UpdateView, DeleteView, ListView
from .models import Thema, Thread, Posting
from django.shortcuts import render, get_object_or_404
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.core.paginator import Paginator


class ThemenView(ListView):
     template_name = 'forum/posts_original.html'
     context_object_name = 'all_themen'

     def get_queryset(self):
         return Thema.objects.all()


class ThemaCreate(CreateView):
    model = Thema
    fields = ['themengebiet', 'beschreibung', 'themen_logo']
    success_url = "/forum/"


class ThreadCreate(CreateView):
    model = Thread
    fields = ['thema', 'titel', 'erstellt_am']
    success_url = reverse_lazy('forum:posts_original')

    def get_object(self):
        return Thread.objects.get(pk=self.kwargs['pk'])

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)


class PostCreate(CreateView):
    model = Posting
    fields = ['thread', 'titel', 'inhalt', 'erstellt_am']
    success_url = "/forum/"

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)


class ThreadView(ListView):
    model = Thread
    context_object_name = 'threads'
    template_name = 'forum/thread.html'
    success_url = reverse_lazy('forum:posts_original')

    def get_object(self):
        return Thread.objects.get(pk=self.kwargs['pk'])


class PostView(ListView):
    model = Posting
    context_object_name = 'posts'
    template_name = 'forum/posts.html'


urls.py

from django.urls import path
from . import views


app_name = 'forum'

urlpatterns = [
    # /forum/
    path('', views.ThemenView.as_view(), name='posts_original'),
    # forum/id/
    path('<int:pk>/', views.ThreadView.as_view(), name='thread-page'),
    # forum/thread/add
    #path('<int:pk>/add/', views.thread_create, name='thread-create'),
    # forum/id//id
    path('thread/<int:pk>/', views.PostView.as_view(), name='post-page'),
    path('add/', views.ThemaCreate.as_view(), name='thema-create'),
    path('<int:pk>/add/', views.ThreadCreate.as_view(), name='thread-create'),
    path('thread/<int:pk>/add/', views.PostCreate.as_view(), name='post-create'),

]

'''

def thread(request, pk):
    try:
       thema = get_object_or_404(Thema, pk=pk)
    except Thema.DoesNotExist:
       raise Http404("Thema existitiert nicht")
    return render(request, 'forum/thread.html', {'thema': thema})


def post(request, pk):
    try:
        thread = get_object_or_404(Thread, pk=pk)
    except Thread.DoesNotExist:
        raise Http404("Thema existitiert nicht!")
    return render(request, 'forum/posts.html', {'thread': thread})
'''

{% extends "blog/base.html" %}
{{ threads }}
{% block content %}
    <a href="{% url 'forum:posts_original'  %}">Zurück zur Themenübersicht</a>
    {% for thread in threads %}
         <article class="media content-section">
          <img class="rounded-circle article-img" src= "{{ thread.thread_logo.url }}">
          <div class="media-body">
            <div class="article-metadata">
               <a class="mr-2" href="{% url 'user-posts' thread.author.username %}">{{ thread.author }}</a>
              <small class="text-muted">{{ thread.erstellt_am|date:"d. F Y" }}</small>
            </div>
             <h2><a class="article-title" href=" {% url 'forum:post-page' thread.id %}">{{ thread.titel }}</a></h2>

            <p class="article-content">Thema: {{ thread.thema }}</p>
          </div>
        </article>
    {% endfor %}

    <form action="{% url 'forum:thread-create' thread.id %}" method="post" enctype="multipart/form-data" style="display: inline;">
    {% csrf_token %}
    <a href="{% url 'forum:thread-create' thread.id %">Thread hinzufügen</a>
    </form>
    {% endif %}
{% endblock content %}

0 个答案:

没有答案
相关问题