我在Django views.py中错过了什么?

时间:2019-07-12 10:43:28

标签: django-forms django-templates django-views

因此,我有一个业务详细信息,并且在业务详细信息页面上,我想添加评论表单,并且仅显示“提交”按钮,并且该表单也链接到已登录的用户,但是如果评论未链接到业务,则我点击提交按钮。

models.py

from django.db import models
from django.urls import reverse # added for redirect after new byz added
from django.contrib.auth import get_user_model

class Byz(models.Model):
    name = models.CharField(max_length=200)
    owner = models.ForeignKey(
            get_user_model(),
            on_delete=models.CASCADE,
            )
    date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    details = models.TextField()

    def __str__(self):
        return self.name

    def get_absolute_url(self): # redirect after new byz added
        return reverse('byz_detail', args=[str(self.id)])

class BReview(models.Model): # new
    byz = models.ForeignKey(Byz, on_delete=models.CASCADE, related_name='breviews', null=True, blank=True)
    review = models.CharField(max_length=140, null=True, blank=True)
    user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    updated = models.DateTimeField(auto_now=True, null=True, blank=True)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ('created',)

    def __str__(self):
        return 'by {}: {}'.format(self.user, self. byz)

    def get_absolute_url(self):
        return reverse('byz_list')

views.py

from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.views.generic import ListView, DetailView
from .models import Byz, BReview
from django.views.generic.edit import CreateView, UpdateView, DeleteView # help to add edit
from django.urls import reverse_lazy # added with DelelteView

class ByzListView(LoginRequiredMixin, ListView):
    model = Byz
    template_name = 'byz/fp/list.html'
    login_url = 'login'

class ByzDetailView(LoginRequiredMixin, DetailView):
    model = Byz
    template_name = 'byz/bp/byzdet.html'
    login_url = 'login'

class ByzCreateView(LoginRequiredMixin, CreateView): # new byz added
    model = Byz
    template_name = 'byz/bp/new.html'
    fields = ('name', 'details')
    login_url = 'login'

    def form_valid(self, form): # to be set the current user logedin as owner
        form.instance.owner = self.request.user
        return super().form_valid(form)

class ByzUpdateView(LoginRequiredMixin, UpdateView): # edit/update byz added
    model = Byz
    template_name = 'byz/bp/edit.html'
    fields = ['name', 'owner'] # only those fields will be updated/edited
    login_url = 'login'

    def dispatch(self, request, *args, **kwargs): # new
        obj = self.get_object()
        if obj.owner != self.request.user:
            raise PermissionDenied
        return super().dispatch(request, *args, **kwargs)

class ByzDeleteView(LoginRequiredMixin, DeleteView): # new
    model = Byz
    template_name = 'byz/bp/del.html'
    success_url = reverse_lazy('home')
    login_url = 'login'

    def dispatch(self, request, *args, **kwargs): # new
        obj = self.get_object()
        if obj.owner != self.request.user:
            raise PermissionDenied
        return super().dispatch(request, *args, **kwargs)

################################################################################

class BRevCreateView(LoginRequiredMixin, CreateView): # new byz added
    model = BReview
    template_name = 'byz/rev/rn.html'
    fields = ('review',)
    login_url = 'login'

    def form_valid(self, form): # to be set the current user logedin as owner
        form.instance.user = self.request.user
        return super().form_valid(form)

urls.py

from django.urls import path
from .views import (
    ByzListView,
    ByzDetailView,
    ByzCreateView,
    ByzUpdateView,
    ByzDeleteView,
    BRevCreateView,
)

urlpatterns = [
    path('<int:pk>/delete/', # new
        ByzDeleteView.as_view(), name='byz_delete'),
    path('<int:pk>/edit/',
        ByzUpdateView.as_view(), name='byz_edit'), # new
    path('new/', ByzCreateView.as_view(), name='byz_new'), # new byz add
    path('<int:pk>/', ByzDetailView.as_view(), name='byz_detail'),
    path('', ByzListView.as_view(), name='byz_list'),
]

business_detail_page.html

{% extends 'layout/base.html' %}

{% block content %}
  <div class="byz-entry">
    <h4>{{ byz.name }}| {{ byz.date }}</h4>
    <p>{{ byz.details }}</p>
  </div>
  <a href="{% url 'byz_edit' byz.pk %}">+ Edit</a>
  <p><a href="{% url 'byz_delete' byz.pk %}">- Delete</a></p>
  <p>Back to <a href="{% url 'byz_list' %}">Byz List</a>.</p>
  {% for breview in byz.breviews.all %}
  <ol>
    <li><b>{{ breview.user }} &middot; </b>{{ breview.review }}</li>
    </ol>
  {% endfor %}
  <h1>New Review</h1>
  <form action="" method="post">{% csrf_token %}
  {{ form.as_p }}
  <input type="submit" value="Save" />
  </form>
{% endblock content %}

Print screen how it looks

0 个答案:

没有答案