Django与bootstrap4和模态

时间:2018-04-09 07:31:09

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

目前我正在研究一个项目,其中有一些用户可以添加他们的想法,其他用户可以发表评论(评论按Django中的用户组分类)。我面临一个问题,即没有收到模板的pk和django.urls.exceptions.NoReverseMatch:反向'user3_comment'与  没有找到参数。尝试过1种模式:['posts / comments / user3 /( 2 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 class 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 / comments / 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})

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

根据您的错误,您在此行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);
    });
})
相关问题