【问题标题】:Django with bootstrap4 and modal带有 bootstrap4 和模态的 Django
【发布时间】:2018-04-09 07:31:09
【问题描述】:

目前我正在研究一个项目,该项目有一个表单,其中一些用户可以添加他们的想法,而其他用户可以评论(在 Django 中,cmet 按用户组划分)。我遇到了一个问题,没有收到模板的 pk 和 django.urls.exceptions.NoReverseMatch: Reverse for 'user3_comment' with 没有找不到参数。尝试了 1 种模式:['posts/cmets/user3/( ?P\d+)/$']。 我的模型是这样的:

models.py

class Post(models.Model):
    post_title = models.CharField(max_length=200)
    author = models.ForeignKey('auth.User', on_delete=models.PROTECT)
    post_date = models.DateField(blank=True, null=True)
    post_time = models.TimeField(blank=True, null=True)
    post_text = models.TextField()

    def __str__(self):
        return self.post_title

class User3_comment(models.Model):
    commented_post = models.ForeignKey(Post, on_delete=models.PROTECT, blank=True, null=True, related_name='user3_comment')
    comment = models.TextField(blank=True)
(some lines skipped)

forms.py 类 User3_comment_form(forms.Form):

class Meta:
    model = User3_comment
    fields = ['comment','commented_post']

views.py

def user3_comment(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = User3_comment_form(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.commented_post = post
            return redirect('post_detail', pk=post.pk)
    else:
        form = User3_comment_form()
    return render(request, 'myapp/user3_comment.html', {'form': form})

urls.py

url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
url(r'^post/comments/user3/(?P<pk>\d+)/$', views.user3_comment, name='user3_comment')

post_detail.html 帖子详情有一个按钮:

{% if request.user|is_authorized:"user3" %}
<div class="modal fade" id="modal"></div>
<button type="button" class="btn btn-primary open-modal" data-toggle="modal" data-target="#modal">Add user3 comment</button>
{% endif %}

还有模态代码:

<script>
$('#modal').on('show.bs.modal', function (event) {
    var modal = $(this)
    $.ajax({
        url: "{% url 'user3_comment' pk=post.initial.id %}",
        context: document.body
    }).done(function(response) {
        modal.html(response);
    });
})
</script>

问题是我得到一个: django.urls.exceptions.NoReverseMatch: 为 'user3_comment' 反转 没有找不到参数。尝试了 1 种模式:['post/cmets/user3/(?P\d+)/$'] 我似乎无法调试它。 模式本身适用于我可以在链接到它时打开一个静态页面,但我无法获得 ajax 应该发送的 pk。

如果与案例相关,我将 bootstrap4 用于我的应用程序。

更新: 我无法使用基于函数的视图对问题进行排序,所以我切换到基于类的视图,它解决了问题,对于任何对解决方案感兴趣的人,这就是我所做的: 我使用了 MultiFormsView(可以在 github https://gist.github.com/jamesbrobb/748c47f46b9bd224b07f 中找到)并创建了一个 MultiFormsView 类:

class Post_Detail(MultiFormsView):
    template_name = 'posts/post_detail.html'
    form_classes = {'post': PostForm,
                            'user3_comment': User3CommentForm}

    def get_success_url(self):
        return reverse('post_detail', kwargs={'pk': post.pk})

    def get_post_form_initial(self):
        post = get_object_or_404(Post, pk=self.kwargs['pk'])
        return { 'post_name': post.post_name, 
        'post_body': post.post_body, }

    def get_user3_comment_form_initial(self):
        try:
            post = Post.objects.get(pk=self.kwargs['pk'])
            comment = User3_Comment.objects.get(mark=post.pk)
            return {'comment_body': post.comment_body,}
        except User3_Comment.DoesNotExist:
            pass

    def get_context_data(self, **kwargs):
        context = super(Post_Detail, self).get_context_data(**kwargs)
        return context

class User3_Comment(CreateView):
    model = User3_Comment 
    fields = ('post_body', )
    template_name = 'posts/user3_comments.html'

    def get_initial(self):
        postx = self.kwargs['pk']
        return {'post': postx}

    def form_valid(self, form):
#save logic
        return redirect('post_detail', pk=self.kwargs['pk'])

    def get_success_url(self):
            return reverse('post_detail', kwargs={'pk': self.object.pk})

【问题讨论】:

  • 关于post.initial.id,它是具有帖子详细视图的模板的一部分:
    {% csrf_token %}

标签: python django python-3.x bootstrap-modal


【解决方案1】:

initial 字段应该是什么?没有提到它。无论如何,你可以试试这个:

{% with post.initial as initial %}
    $.ajax({
        url: "{% url 'user3_comment' pk=initial.id %}",
        context: document.body
    }).done(function(response) {
        modal.html(response);
    });
{% endwith %}

【讨论】:

  • 似乎对我不起作用,完全,模态窗口被调用,但 id/pk 仍然没有传递给视图。
【解决方案2】:

根据您的错误,您在此行中传递的参数 url: "{% url 'user3_comment' pk=post.initial.id %}" 为空。

在您看来,您实际上并没有将Post 作为上下文传递给页面,这可能是没有价值的原因。

return render(request, 'myapp/user3_comment.html', {'form': form, 'post': post})

如果您将{{ post.initial.id }} 或任何其他Post 字段放在页面的其他位置,它会显示值吗?如果不是,那么您的模板标签是错误的。根据您的模型,它应该是{{ post.id }}

<button type="button" name="modal_button" data-toggle="modal" data-target="#modal"
    value="{{ post.id }}" class="Modal">
</button>

$('button.Modal').click(function() {
    var post_id = $(this).val();
    $.ajax({
        url: "{% url 'user3_comment' pk=post_id %}",
        context: document.body
    }).done(function(response) {
        $('#modal').html(response);
    });
})

【讨论】:

  • {{post.initial.id}} 确实显示了一个值,但重定向仍然不起作用。 {{post.id}} 从来没有为我工作过,这就是我选择 {{post.initial.id}} 路线的原因。这一直是问题,我可以得到 post.id,但它永远不会重定向到帖子的评论页面。
猜你喜欢
  • 2020-06-29
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 2020-09-28
  • 2017-09-02
  • 2019-09-23
  • 2020-04-24
  • 2020-07-21
相关资源
最近更新 更多