提交表单后未创建Django对象

时间:2020-03-23 21:05:58

标签: python django ajax django-forms django-views

嗨,我正在使用Django和Ajax,以便用户在其网站上创建“帖子”。但是,提交表单后,该帖子不会显示。我不知道是什么原因造成的,因为我没有看到错误。

我对主页和创建帖子的看法是:

@login_required
def home(request):
    posts = Post.objects.all()
    context = {'posts':posts}
    return render(request, 'home/homepage/home.html', context)

@login_required
def post_create(request):
    data = dict()
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():      
            form.save()
            data['form_is_valid'] = True
            posts = Post.objects.all()
            data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts})
        else:
            data['form_is_valid'] = False
    else:
        form = PostForm       
    context = {
    'form':form
    }
    data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request)
    return JsonResponse(data) 

我的post_create.html:

{% load crispy_forms_tags %}
    <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form">
        {% csrf_token %}
            <div class="modal-header">
                <h5 class="modal-title" >Create a Post</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                {{ form|crispy }}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Post</button>
            </div>
    </form>

我的home.html:

{% extends "home/homepage/base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block javascript %}
<script src="{% static 'js/post.js' %}"></script>
{% endblock javascript %}
{% block content %}
<div class="card">
  <div class="card-body">
    <div class="media mb-0 align-items-center">
      <img class="img-create-post rounded-circle my-0 mr-3" style="width: 50px;height: 50px;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg"
        alt="Profile image">
          <span class="text-muted align-middle">What's new?</span>
          <button type="button" class="btn btn-sm btn-primary create-post-btn ml-auto" data-url="{% url 'home:post-create' %}"><i class="fas fa-plus-square"></i></button> 
    </div>  
  </div>
</div>
<div id="post-list">
  <div>
    {% include 'home/posts/home_post.html' %}
  </div>
</div>
<div class="modal fade" id="modal-post">
  <div class="modal-dialog">
    <div class="modal-content"></div>
  </div>
</div>  
{% endblock content %}

我的home_post.html:

{% load static %}
{% block javascript %}
  <script src="{% static 'js/posts.js' %}"></script>
{% endblock javascript %}
{% for post in posts %}
<div class="card  mt-3  mb-3" style="max-width: 36rem !important;">
  <div class="card-body text-dark">
    <div class="d-flex">
      <img class="img-create-post rounded-circle mr-2" style="width: 50px;height: 50px;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg"
        alt="Profile image">
        <span class="align-text-top"><a class="mr-2 text-dark font-weight-bolder" href="#">{{ post.author.first_name }} {{ post.author.last_name }} </a><br><p class="font-weight-light text-muted">{{ post.title }}</p></span>
          <div class="float-right text-right ml-auto">
            <p class="text-muted small" style="font-size: 0.7rem;">{{ post.date_posted|date:"F d, Y" }}</p>
          </div>     
    </div>
    <p class="card-text">{{ post.content }}</p>
  </div>
  <div class="card-footer" style="height: 5rem;">
    <a class="mx-1 small" data-href='{{ post.get_api_like_url }}' data-likes='{{ post.likes.count }}' href='{{ post.get_like_url }}'><i class="fas fa-thumbs-up"></i> Like</a>
    <a class="mx-1 small" href='#'><i class="fas fa-comment-alt"></i> Comment</a>
    <hr class="my-1">
      <p class="text-muted small">
        {% if post.author == request.user %}  
        <button class="btn btn-sm text-muted show-form-delete ml-auto" data-url="{% url 'home:post-delete' post.id %}" style="font-size: small;" style="height: 0rem;">Remove</button> 
        {% endif %}
        <small class="float-sm-right">
          {{ post.likes.count }} Likes, # Comments
        </small>
      </p>
  </div>
</div>
{% empty %}
<div class="align-items-center">
  <h5 class="display-5 my-3 text-muted">No posts to show :(</h5>
</div>
{% endfor %}

这两个函数是我在post.js中的javascript函数

$(function () {
    $(".create-post-btn").click(function () {
      $.ajax({
        url: '/home/post/create/',
        type: 'get',
        dataType: 'json',
        beforeSend: function () {
          $("#modal-post").modal("show");
        },
        success: function (data) {
          $("#modal-post .modal-content").html(data.html_form);
        }
      });
    }); 
});

$("#modal-post").on("submit", ".post-create-form", function () {
    var form = $(this);
    $.ajax({
      url: form.attr("action"),
      data: form.serialize(),
      type: form.attr("method"),
      dataType: 'json',
      success: function (data) {
        if (data.form_is_valid) {
            $('#post-list div').html(data.posts);
            $('#modal-post').modal('hide');
        }
        else {
          $("#modal-post .modal-content").html(data.html_form);
        }
      }
    });
    return false;
  });

我先感谢您的帮助!

0 个答案:

没有答案