Django在类视图中尝试异常

时间:2019-03-18 22:17:03

标签: python django django-views

我是唯一的学生,所以请忍受我。我已经在函数视图中发布了与此有关的另一个主题。现在,我想将这个try异常转换为类视图,并添加该注释表单。

这是我的views.py def

def BookDetail(request, id):
    most_recent = Book.objects.order_by('-timestamp')[:3]
    book= get_object_or_404(Book, id=id)
    form = CommentForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            form.instance.user = request.user
            form.instance.post = book
            form.save()
            return redirect(reverse("book-detail", kwargs={
                'id': book.pk
            }))

    if request.user.is_anonymous:
        user_membership = None
    else:
        try:
            user_membership = Customer.objects.get(user=request.user)
        except Customer.DoesNotExist:
            user_membership = None

    context = {
        'user_membership': user_membership,
        'form': form,
        'book': book,
        'most_recent': most_recent,

    }
    return render(request, 'catalog/book_detail.html', context)

这是我的新课堂视图

class BookDetailView(NeverCacheMixin, generic.DetailView):
    model = Book

更新帖子

这是我的模型。py。

class Book(models.Model):
    slug = models.SlugField(unique=True, help_text="Enter BIC Code", null=True)
    title = models.CharField(max_length=200) #more fields after this

    timestamp = models.DateTimeField(default=timezone.now)


    activeReference = models.ManyToManyField(Membership)


    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('book-detail', kwargs={'slug': self.slug})

    @property
    def get_comments(self):
        return self.comments.all().order_by('-timestamp')

    @property
    def pages(self):
        return self.page_set.all()

class Page(models.Model):
    slug = models.SlugField(max_length=50)
    book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True)
    preview = models.FileField(upload_to='book_content', validators=[pdf_file_extension], help_text="PDF File Only")

    def __str__(self):
        return self.slug

    def get_absolute_url(self):
        return reverse('page-detail',
                       kwargs={
                           'book_slug': self.book.slug,
                           'page_slug': self.slug
                       })

这是我的网址格式

urlpatterns = [
path('', views.index, name='index'),
path('books/', views.BookListView.as_view(), name='book-list'),
path('book-detail/<slug>', views.BookDetailView.as_view(), name='book-detail'),
path('book-detail/<book_slug>/<page_slug>', views.PageDetailView.as_view(), name='page-detail'),


path('search/', views.Search, name='search'),

]

和我的book_detail.html

        {% for content in book.pages %}
            <a href="{{ content.get_absolute_url }}" class="site-btn">Read</a>
        {% endfor %}

      {% else %} 

2 个答案:

答案 0 :(得分:0)

当您需要继承或需要处理不同的HTTP方法以具有相同的路由时,CBV很好。如果不是这种情况,FBV是更好的选择。话虽这么说,对于您想做的事情,您应该只使用FormView即可处理有关帖子和表单的所有内容。

类似的东西:

class BookViewSet(FormView):
form = CommentForm
template_name = 'catalog/book_detail.html'

def form_valid(self, form):
    self.send_mail(form.cleaned_data)
    return super(BookViewSet, self).form_valid(form)

答案 1 :(得分:0)

如果要处理表单,则应使用CreateView或FormView而不是DetailView。这是一个实现示例,如您所见,对于刚接触Django的人来说有点复杂:

from django.views.generic import CreateView


class BookDetailView(NeverCacheMixin, CreateView):
    form_class = CommentForm
    template_name = 'catalog/book_detail.html'

    def dispatch(self, request, *args, **kwargs):
        book_slug = self.kwargs.get('slug')  # url variables are stored in self.kwargs
        self.book = get_object_or_404(Book, slug=book_slug)  # attach book to your view
        return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        # context data passed to template
        kwargs['book'] = self.book
        kwargs['most_recent'] = Book.objects.order_by('-timestamp')[:3]

        if request.user.is_anonymous:
            user_membership = None
        else:
            try:
                user_membership = Customer.objects.get(user=self.request.user)
            except Customer.DoesNotExist:
                user_membership = None
        kwargs['user_membership'] = user_membership
        return super().get_context_data(**kwargs)

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.user = self.request.user
        instance.post = self.book
        instance.save()
        return redirect(self.book.get_absolute_url())