我对 Django 比较陌生。我想将 Django-chatrooms( https://github.com/qubird/django-chatrooms ) 应用程序集成到我的项目中。这个应用程序有3个不同的URL(1.Available-ChatRooms list 2.Set-guestname/Login 3.Room(实际聊天界面))。但我想让所有这 3 个功能(加入房间、设置访客名/登录和聊天窗口)在同一个 URL(这是我的项目主页)上对用户可用。所以我将通过 Ajax 来实现。
我需要从应用程序调用 3 个类视图;这是应用程序的相应 URL 和视图文件:
网址.py
#encoding=utf8
from django.conf.urls.defaults import url, patterns
from . import views
from .utils.decorators import room_check_access
from .ajax import chat
urlpatterns = patterns('chatrooms',
# room views
url(r'^rooms/$',
views.RoomsListView.as_view(),
name="rooms_list"),
url(r'^room/(?P<slug>[-\w\d]+)/$',
room_check_access(views.RoomView.as_view()),
name="room_view"),
url(r'^setguestname/$',
views.GuestNameView.as_view(),
name="set_guestname"),
# ajax requests
url(r'^get_messages/', chat.ChatView().get_messages),
url(r'^send_message/', chat.ChatView().send_message),
url(r'^get_latest_msg_id/', chat.ChatView().get_latest_message_id),
url(r'^get_users_list/$', chat.ChatView().get_users_list),
url(r'^notify_users_list/$', chat.ChatView().notify_users_list),
)
视图.py
#encoding=utf8
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.views.generic import ListView, DetailView, FormView
from .utils.auth import get_login_url
from .forms.guest import GuestNameForm
from .models import Room
class RoomsListView(ListView):
"""View to show the list of rooms available """
context_object_name = "rooms"
template_name = "chatrooms/rooms_list.html"
paginate_by = 20
def get_queryset(self):
filters = {}
if self.request.user.is_anonymous():
filters['allow_anonymous_access'] = True
return Room.objects.filter(**filters)
class RoomView(DetailView):
"""View for the single room """
model = Room
context_object_name = 'room'
template_name = "chatrooms/room.html"
class GuestNameView(FormView):
"""Shows the form to choose a guest name to anonymous users """
form_class = GuestNameForm
template_name = 'chatrooms/guestname_form.html'
def get_context_data(self, **kwargs):
kwargs.update(super(GuestNameView, self).get_context_data(**kwargs))
room_slug = self.request.GET.get('room_slug')
next = ''
if room_slug:
next = reverse('room_view', kwargs={'slug': room_slug})
kwargs['login_url'] = get_login_url(next)
return kwargs
def get_initial(self):
init = super(GuestNameView, self).get_initial()
room_slug = self.request.GET.get('room_slug')
if room_slug:
init.update(room_slug=room_slug)
return init
def form_valid(self, form):
guest_name = form.cleaned_data.get('guest_name')
room_slug = form.cleaned_data.get('room_slug')
self.request.session['guest_name'] = guest_name
if room_slug:
redirect_url = reverse('room_view', kwargs={'slug': room_slug})
else:
redirect_url = reverse('rooms_list')
return HttpResponseRedirect(redirect_url)
我的主页视图包含 home.html 模板(我想在其中集成聊天)
def home_view(request):
site = Site.objects.get_current()
return render_to_response('home.html', {'user':request.user,'data':request.POST , 'site':site})