我正在构建一个Django消息传递应用程序,其中每个聊天室都有自己的模板,模型和视图。我正在努力寻找一种方法,让用户使用用户输入来创建私人聊天室。我希望用户以模板形式指定详细信息,当他们单击提交时,将生成文件以创建聊天室。还是有更好的方法来做到这一点?任何建议将不胜感激。
哦,我将Django 2.1.2与Python 3.6.5结合使用。谢谢
编辑:我在下面添加一些代码
models.py:
class Chat(models.Model):
created = models.DateTimeField(auto_now_add=True)
#timeNow = models.DateTimeField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
message = models.TextField()
file_upload = models.FileField()
class Meta:
verbose_name_plural = "general Chat"
def __unicode__(self):
return self.message
views.py:
def GeneralChat(request):
c = Chat.objects.all()
documents = Document.objects.all() #file upload
return render(request, "channels/generalChat.html", {'generalChat': 'active', 'chat': c, 'documents': documents})
def Post(request):
if request.method == "POST":
msg = request.POST.get('msgbox', None)
time = datetime.now()
c = Chat(user=request.user, message=msg, created=time)
c = Chat(user=request.user, message=msg)
if msg != '':
c.save()
return JsonResponse({ 'msg': msg, 'user': c.user.username})
else:
return HttpResponse('Request must be POST.')
def Uploads(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/generalChat')
else:
form = DocumentForm()
return render(request, 'channels/uploads.html', {
'form': form
})
generalChat.html:
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<div><title>General Chat</title></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div id="chat-body" class="panel panel-default">
<div id="panel-heading" class="panel-heading"><h4>General Chat</h4></div>
<div id="msg-list-div" class="panel-body">
<ul id="msg-list" class="list-group">
{% for obj in chat %}
{%if obj.user == request.user %}
<li class="text-right list-group-item">
<font color="#3498DB">{{ obj.user }}</font><br><font color="#000000"></font>{{ obj.message }}
<br><font size="1" >{{ obj.created }}</font></li>
<br>
{% else %}
<li class="text-left list-group-item">
<font color="#1ABC9C">{{ obj.user }}</font><br><font color="#000000"></font>{{ obj.message }}
<br><font size="1" >{{ obj.created }}</font></li></li>
<br>
{%endif%}
{% empty %}
<li class="text-right list-group-item">No messages yet.</li>
{% endfor %}
<h4>Files</h4>
{% for obj in documents %}
{%if obj.userUpload == request.user %}
<li class="text-right list-group-item">
<font color="#3498DB">{{ obj.userUpload }}</font><br>
<a href="{{ obj.document.url }}"><font color="#000000">{{ obj.document.name }}</a></font>
<br><small>{{ obj.created }}</small></li><br>
{% else %}
<li class="text-left list-group-item">
<font color="#1ABC9C">{{ obj.userUpload }}</font><br>
<a href="{{ obj.document.url }}"><font color="#000000">{{ obj.document.name }}</a></font>
<br><small>{{ obj.created }}</small></li><br>
{% endif %}
{% endfor %}
<script>
var chatlist = document.getElementById('msg-list-div');
//chatlist.scrollTop = chatlist.scrollHeight;
</script>
</ul>
<div><a class="btn btn-warning" value="Upload File" href="{% url 'uploads' %}" >Upload File</a></div>
</div>
</div>
<div id="form-input" style="height: 100px;">
<form id="chat-form" method="post" action="/post/">{% csrf_token %}
<div id="chat-bottom" class="input-group">
<input type="text" id="chat-msg" name="chat-msg" class="form-control"/>
<span class="input-group-btn">
<input class="btn btn-default" id="send" type="submit" value="Send"/>
</span>
</div>
</form>
</div>
<script src="{% static 'chat.js' %}"></script>
<script src="{% static 'jquery.cookie.js' %}"></script>
{% endblock %}
chat.js
$('#chat-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url : '/post/',
type : 'POST',
data : {msgbox: $('#chat-msg').val() },
success : function(json){
console.log(json);
$('#chat-msg').val('');
$('#msg-list').append('<li class="text-right list-group-item">' + json.msg + '</li>');
var chatlist = document.getElementById('msg-list-div');
//chatlist.scrollTop = chatlist.scrollHeight;
}
});
});
function getMessages(){
if (!scrolling){
$.get('/messages/', function(messages){
console.log(messages);
$('#msg-list').html(messages);
var chatlist = document.getElementById('msg-list-div');
//chatlist.scrollTop = chatlist.scrollHeight;
});
}
scrolling = false;
}
var scrolling = false;
$(function(){
/*$('#msg-list-div').on('scroll', function(){
scrolling = true;
});*/
refreshTimer = setInterval(getMessages, 5000); //0.5 seconds
});
$(document).ready(function(){
$('#send').attr('disabled','disabled');
$('#chat-msg').keyup(function(){
if($(this).val() != ''){
$('#send').removeAttr('disabled');
}
else{
$('#send').attr('disabled', 'disabled');
}
});
});
//using JQuery
function getCookie(name){
var cookieValue = null;
if (document.cookie && document.cookie != ''){
var cookies = document.cookie.split(';');
for (var i=0; i < cookies.length; i++){
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method){
// these http methodes don't need CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings){
if(!csrfSafeMethod(settings.type) && !this.crossDomain){
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});