在UpdateView(基于类的视图)中,需要PK或ID来获取success_message

时间:2019-07-17 18:14:18

标签: python django django-class-based-views

我想在UpdateView中发送一条成功消息,该消息具有一个链接,允许用户改变其对更新的看法。这意味着我需要主键。

我无法确定如何在UpdateView中检索主键。其他所有东西都起作用,因此您会在我的代码中看到我已将主键永久性地硬编码为434。

我是所有编程的新手,所以我相信这里有愚蠢的东西。我尝试一次减少一些愚蠢的东西。因此,大多数情况下,我希望重点关注如何检索PK(或ID)。谢谢。

URL:

# CLASS BASED VIEWS #
path('event/list', EventListView.as_view(), name='list'),
path('event/detail/<int:pk>', EventDetailView.as_view(), name='detail'),
path('event/create', EventCreateView.as_view(), name='create'),
path('event/update/<int:pk>', EventUpdateView.as_view(), name='update'),

视图:

class EventUpdateView(SuccessMessageMixin,UpdateView):

    template_name = 'update.html'
    form_class = EventForm
    success_url = '../list'
    queryset = Event.objects.all()

    def get_object(self, queryset=None):  # here we override the get_object method in UpdateView, don't need queryset
        #obj = Event.objects.get(id=self.kwargs['pk'])
        pk_=self.kwargs.get("pk")
        print("The pk is", pk_)
        return get_object_or_404(Event,pk=pk_)

    def form_valid(self, form):
        return super().form_valid(form)

    message_part_1 = "Record has been updated <a href='unupdate?recordtobeunupdated="
    message_part_2 =  '434'
    message_part_3 = "'>Undo</a>"
    undo_message = message_part_1  + message_part_2 + message_part_3
    success_message = (mark_safe(undo_message))

模型:

from django.db import models
from django.urls import reverse

class Event(models.Model):  # This is our database table
    company = models.CharField(default='UL',   max_length=20)
    engine = models.CharField(blank=True, max_length=15)
    date = models.DateTimeField(default=datetime.now, blank=True, null=True)  # default the date to today
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='Weights')
    description = models.TextField(blank=True, null=True)
    reason = models.TextField(blank=True, null=True)
    assess_date = models.DateTimeField(null=True, blank=True)
    outcome = models.CharField(blank=True, max_length=200)
    # the default is True, it can't be blank
    visible = models.BooleanField(default=True, blank=False)


    def get_absolute_url(self):
        return reverse("SiteEventsAPP: SiteEventsAPP-detail", kwargs={"pk": self.pk})

    # See below __str__(self) is a special method
    # It does a cool thing
    # Whenever Python asks for a string representation of my Event object, this method returns a human-readable version
    # If there is no string method, then Python returns the object type
    # This class method is really only needed for the admin page

    def __str__(self):
        return self.engine  # I have to have a field here. Whatever field I pick will be the field shown in admin

这是用户看到的结果: enter image description here

2 个答案:

答案 0 :(得分:1)

如果您查看SuccessMessageMixin的代码,则会看到以下内容:

    class SuccessMessageMixin:
    """
    Add a success message on successful form submission.
    """
    success_message = ''

    def form_valid(self, form):
        response = super().form_valid(form)
        success_message = self.get_success_message(form.cleaned_data)
        if success_message:
            messages.success(self.request, success_message)
        return response

    def get_success_message(self, cleaned_data):
        return self.success_message % cleaned_data

如您在此处看到的,返回成功消息的函数为get_success_message,因此您只需要重写该函数即可。

您的代码应为:

class EventUpdateView(SuccessMessageMixin,UpdateView):

    template_name = 'update.html'
    form_class = EventForm
    success_url = '../list'
    queryset = Event.objects.all()    

    def form_valid(self, form):
        return super().form_valid(form)

    def get_success_message(self, cleaned_data):
        message = "Record has been updated <a href='unupdate?recordtobeunupdated="
        message += str(self.kwargs.get("pk"))
        message += "'>Undo</a>"
        return (mark_safe(message))

让我给您一个建议,不要将python库/框架视为黑匣子实体,只需输入它们并探索它们的工作方式,这将使您的编程工作变得更加轻松。

祝你好运,继续努力!

答案 1 :(得分:0)

您可以使用django内置消息:

def form_valid(self, form):
        messages.add_message(
            self.request, 
            messages.SUCCESS, 
            """
            Record has been updated <a href="unupdate?recordtobeunupdated={}">Undo</a>""".format(
                kwargs={'pk': self.kwargs['pk']}
             """"
        )

        return super(UserUpdate, self).form_valid(form)

使用kwargs = {'pk':self.kwargs ['pk']},您将获得ID。

之后,您可以在模板中捕获消息:

{% if messages %}
    {% for msg in messages %}
      <div class="alert
      alert-{% if msg.level_tag == 'debug' %}rose{% endif %}
      {% if msg.level_tag == 'info' %}info{% endif %}
      {% if msg.level_tag == 'success' %}success{% endif %}
      {% if msg.level_tag == 'warning' %}warning{% endif %}
      {% if msg.level_tag == 'error' %}danger{% endif %} alert-with-icon" data-notify="container">
        <i class="material-icons" data-notify="icon">
          {% if msg.level_tag == 'debug' %}code{% endif %}
          {% if msg.level_tag == 'info' %}info{% endif %}
          {% if msg.level_tag == 'success' %}done_all{% endif %}
          {% if msg.level_tag == 'warning' %}warning{% endif %}
          {% if msg.level_tag == 'error' %}error{% endif %}
        </i>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <i class="material-icons">close</i>
        </button>
        <span data-notify="message">
          {% autoescape off %}
            {{ msg.message }}
          {% endautoescape %}
        </span>
      </div>
    {% endfor %}
  {% endif %}

上面的代码捕获所有消息(假设您使用的是常规布局),并使用引导程序将消息呈现为通知。

更多信息here