【问题标题】:What is wrong in if request.method == 'POST'如果 request.method == 'POST' 有什么问题
【发布时间】:2021-09-30 12:37:48
【问题描述】:

请问我在 Django 的这个功能中做错了什么?

models.py

class Notification(models.Model):
    user = models.ForeignKey('User', models.CASCADE, related_name='notifications')
    message = models.TextField('Повідомлення')
    viewed_at = models.DateTimeField('Проглянуто в', null=True, blank=True)
    created_at = models.DateTimeField('Створено', auto_now_add=True, editable=False)

views.py

class NotificationListView(core.ListView):
    permission_classes = [IsAuthenticated]
    model = Notification
    template_name = 'auth/notifications.html'

    def get_queryset(self):
        return super().get_queryset().filter(user=self.request.user).annotate(
            viewed_at_null=ExpressionWrapper(
                Q(viewed_at__isnull=True),
                output_field=BooleanField()
            )).order_by('-created_at')

def notification_read(request, pk):
    if request.method == 'POST':
        notification = get_object_or_404(Notification, pk=pk, viewed_at=None, user=request.user)
        form = NotificationForm(request.POST, instance=notification)
        if form.is_valid():
            notification.viewed_at = timezone.now()
            notification.save(update_fields=['viewed_at'])
            form.save()
            return redirect('users:notification')

urls.py

path('notification/', views.NotificationListView.as_view(), name='notification'),
    path('notification/<pk>/', views.notification_read, name='viewed-notification'),

模板

<tbody>
    {% for item in object_list %}
      {% if item.viewed_at is None %}
        <tr>
          <td>
            {{ item.message }}
          <td>
          <td>
            {{ item.created_at }}
          <td>
            <form method="post"  action="{% url 'users:viewed-notification' item.pk %}" enctype="multipart/form-data">
              {% csrf_token %}
              <p>{{ form.non_field_errors }}</p>
              <span class="badge badge-error">
                {{ form.viewed_at }}
                        <p><input type="submit" value="See it"/> 
           </p>
                </span>
            </form>

          </td>
        </tr>
      {% else %}
      {% endif %}
    {% endfor %}
  </tbody>

我怎样才能做得更好?谁能解释一下,为什么它不能正常工作? 我的错误是,当我单击此按钮时,ListPage 中的所有数据都无法正常工作! 它显示列表中没有数据!当我进入 pk 视图时,它会显示错误

UnboundLocalError 在 /users/notification/16/ 赋值前引用的局部变量“form”

【问题讨论】:

  • 请至少包含错误消息,以及您如何首先调用该函数以确保请求实际上是一个请求
  • @EdoardoFacchinelli 更新了我的代码!请检查!
  • 尝试“POST”而不是“post”
  • 这是行不通的!我怎么理解-在此之后-表单不保存新的更新字段!(((
  • 至少说明错误是什么。

标签: django django-views django-templates


【解决方案1】:

您需要遵循文档并在函数返回中声明一个表单变量:

return render(request, 'my_template.html', {'form': form})

看这个帖子:How to update an object from edit form in Django?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-04
    • 2014-12-07
    • 2013-02-03
    • 2021-05-20
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多