gpt4 book ai didi

python - ListView 中的 Django 表单,表单 POST 时出错

转载 作者:行者123 更新时间:2023-12-02 09:51:35 27 4
gpt4 key购买 nike

我正在尝试为我的网站实现聊天功能。为了做到这一点,我遵循了以下教程:https://channels.readthedocs.io/en/latest/tutorial/

然后我稍微更改了代码以实现它。到这里为止,一切都很好。现在我想将表单数据存储在数据库中,这就是问题出现的地方。但首先是我的代码:

urls.py:

    from django.urls import path
from .views import ChatOverView

urlpatterns = [
path('<int:pk>/', ChatOverView.as_view(), name='chat-explicit'),
path('', ChatOverView.as_view(), name='chat-home'),
]

views.py (这里有很多代码可能不需要这个问题,但由于我不知道我可以忽略其中的哪一部分,我只是发布整个文件内容):

from django.views.generic import ListView
from django.views.generic.edit import FormMixin, FormView
from django.db.models import Q
from django.urls import resolve
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404

from .models import Message
from .forms import MessageRegisterForm


class ChatOverView(ListView, FormMixin):
model = Message
template_name = 'chat/home-chat.html'
form_class = MessageRegisterForm
success_url = '/thanks/'

def form_valid(self, form):
form = self.get_form()
if form.is_valid():
data = form.cleaned_data
return super().form_valid(form)

def get_context_data(self, *args, **kwargs):
context = super(ChatOverView, self).get_context_data(*args, **kwargs)

messages_raw = reversed(Message.objects.filter(Q(sender=self.request.user) | Q(receiver=self.request.user)))
messages = {}

for mes in messages_raw:
# i am receiver
if mes.sender != self.request.user:
if mes.sender in messages:
messages[mes.sender].append({"received": mes})
else:
messages.update({mes.sender: [{"received": mes}]})
# i sent
else:
if mes.receiver in messages:
messages[mes.receiver].append({"sent": mes})
else:
messages.update({mes.receiver: [{"sent": mes}]})

active_user = self.get_active_chat(messages)
chatroom_name = self.get_chatroom_name(active_user)
context.update(messages_data=messages, active=active_user, roomname=chatroom_name)
return context

def get_chatroom_name(self, active_chat):
# my convention
ids = [active_chat.id, self.request.user.id]
ids.sort()
return str(ids[0]) + '_' + str(ids[1])

def get_active_chat(self, messages):
url_name = resolve(self.request.path_info).url_name
if url_name == "chat-home":
return list(messages.keys())[0]
else:
pk_user = self.request.build_absolute_uri().split("/")[-2]
user = get_object_or_404(User, pk=pk_user)
return user

home-chat.html:

{% extends "solawi/base.html" %}
{% load define_dictfilters %}
{% block content %}
<form class="bg-light" method="post">
<div class="input-group">
{% csrf_token %}
{{ form }}
<div class="input-group-append">
<button type="submit" id="chat-message-submit" value="enter">send</button>
</div>
</div>
</form>
{% endblock content %}

models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User


class Message(models.Model):
sender = models.ForeignKey(User, related_name="sender", on_delete=models.CASCADE)
receiver = models.ForeignKey(User, related_name="receiver", on_delete=models.CASCADE)
content = models.TextField()
date = models.DateTimeField(default=timezone.now)

def __str__(self):
return self.sender.username + ' to ' + self.receiver.username

其余的文件/设置条目与上面链接的教程中的相同。

现在问题来了:提交表单时,出现以下错误:不允许的方法 (POST):/chat/
不允许的方法:/chat/
HTTP POST/chat/405 [0.00, 127.0.0.1:54424]

我该如何修复它?感谢您的帮助!!

最佳答案

ListView 实现了 get() 方法,但没有实现 post() 方法。您需要实现 post() 方法,以便 View 允许 POST 请求。

您可以子类化django.views.generic.ProcessFormView来获取它,或者,如果您确实需要ListView,那么您可以添加post( ) 方法到处理表单验证以及您需要执行的任何其他操作的类。以下是 ProcessFormView 的实现方式:

    def post(self, request, *args, **kwargs):
"""
Handle POST requests: instantiate a form instance with the passed
POST variables and then check if it's valid.
"""
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)

关于python - ListView 中的 Django 表单,表单 POST 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60533548/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com