Django:包含的模板未出现

时间:2020-10-17 13:08:02

标签: django ajax django-views django-templates

我正在用ajax实现消息系统。发布新消息时,一切正常。我的意思是,新消息出现后没有重新加载,但是当我转到'create_message'页面时,看不到包含的模板(messages.html),它包含在发布消息之后。我试图包括其他模板,它的工作。我的下面的代码,感谢您的提前帮助。

views.py

class MessageCreateView(CreateView):
    model = Message
    fields = ['content']
    template_name = 'users/create_message.html'
    
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            if request.method == 'POST':
                sender = self.request.user.profile
                receiver_pk = self.kwargs['profile_pk']
                print(receiver_pk)
                receiver = Profile.objects.get(id=receiver_pk)
                new_message = Message.objects.create(
                    message_by=sender,
                    message_to=receiver,
                    content = form.cleaned_data['content'])
                return JsonResponse({'message': model_to_dict(new_message)}, status=200)
        else:
            return self.form_invalid(form)

    def get_context_data(self, **kwargs):
        context = super(MessageCreateView, self).get_context_data(**kwargs)
        context['profile_pk'] = self.kwargs['profile_pk']
        return context

def messages(request, profile_pk):
    current_user_profile = request.user.profile
    second_profile = Profile.objects.get(pk=profile_pk)
    messages = Message.objects.filter(
        Q(message_to=current_user_profile, message_by=second_profile)|
        Q(message_to=second_profile, message_by=current_user_profile)).order_by('date_of_create')
    context = {
        'messages': messages
    }
    return render(request, 'users/messages.html', context=context)

urls.py

urlpatterns = [
    path('login/', CustomLoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('register/', register, name='register'),
    path('profile/<int:pk>/', ProfileDetailView.as_view(), name='profile_detail'),
    path('profile/follow/<int:pk>', follow_profile, name='follow_profile'),
    path('results/', search, name='search'),
    path('create_message/<int:profile_pk>/', MessageCreateView.as_view(), name='create_message'),
    path('messages/<int:profile_pk>/', messages, name='messages')
]

create_message.html

{% extends 'users/base.html' %}
{% load crispy_forms_tags %}

{% block title %}Chat{% endblock %}

{% block content %}
    <div class="messages">
        {% include 'users/messages.html' %}
    </div>

    <form action="" method="POST" class="messageForm" data-url="{% url 'create_message' profile_pk %}">
        {% csrf_token %}
        {{ form|crispy }}
        <button type="button" class="messageBtn">Send</button>
    </form>
{% endblock %}

messages.html

{% for message in messages %}
    <h6>{{ message.content }}</h6>
    <small>{{ message.message_by }} / {{ message.date_of_create }}</small>
{% endfor %}

1 个答案:

答案 0 :(得分:1)

我认为这是因为messages字典中没有context用于渲染crete_messages页面。我只是通过从您的messages视图复制并粘贴代码来做到这一点,但是您可能希望对其进行重构。

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            if request.method == 'POST':
                sender = self.request.user.profile
                receiver_pk = self.kwargs['profile_pk']
                print(receiver_pk)
                receiver = Profile.objects.get(id=receiver_pk)
                new_message = Message.objects.create(
                    message_by=sender,
                    message_to=receiver,
                    content = form.cleaned_data['content'])
                return JsonResponse({'message': model_to_dict(new_message)}, status=200)
        else:
            return self.form_invalid(form)

    def get_context_data(self, **kwargs):
        context = super(MessageCreateView, self).get_context_data(**kwargs)
        profile_pk = context['profile_pk'] = self.kwargs['profile_pk']
        current_user_profile = self.request.user.profile
        second_profile = Profile.objects.get(pk=profile_pk)
        messages = Message.objects.filter(
            Q(message_to=current_user_profile, message_by=second_profile)|
            Q(message_to=second_profile, message_by=current_user_profile)).order_by('date_of_create')
        context['messages'] = messages
        return context