我要创建自定义消息Web应用程序,用户可以互相发送消息(不聊天,仅发送消息)。我有消息模型和消息表单,但我不了解视图和模板的外观。我找不到任何教程或与此有关的东西,大多数我只是找到库或软件包。然后,这些视图和模板如何?
这是我的模型。py:
from django.contrib.auth import get_user_model
class Message(models.Model):
sender = models.ForeignKey(get_user_model(), related_name="sender")
receiver = models.ManyToManyField(get_user_model(), related_name="receiver")
message_file = models.FileField(upload_to='mails/')
timestamp = models.DateTimeField(auto_now_add=True)
unread = models.BooleanField(default = True)
forms.py
from django import forms
from .models import Message
class MessageForm(forms.ModelForm):
class Meta:
model = Message
fields =[
'sender',
'receiver',
'message_file',
]
非常感谢
答案 0 :(得分:0)
我将使用一个更基本的方法来代替您一个简单的示例,而不是使用一个表单。您需要的是与此类似的东西:
views.py
class SendMessageView(View):
def post(self, request, *args, **kwargs):
receiver_id = request.POST.get('receiver_id', '')
file = request.FILES.get('file', '')
Message.objects.create(sender=request.user, receiver__id=receiver_id, message_file=file)
return render(request, 'success.html', {})
urls.py
path('message/send/', views.SendMessageView.as_view(), name="send_message")
html
<form action="{% url 'send_message' %}" method="post">
{% csrf_token %}
<input type="hidden" name="receiver_id" value="{{ receiver.id }}" />
<input type="file" name="file" />
</form>