如何“自动填充" CreateView字段 [英] How do I 'Autofill' a CreateView field

查看:48
本文介绍了如何“自动填充" CreateView字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Artist的模型,现在我正在为Artist DetailView构建注释部分.

I have a model called Artist, and now I'm working on building a comment section for the Artist DetailView.

我已经建立了一个名为ArtistComment的模型,创建了一个CreateView并使用模态div将其添加到DetailView中,这样看起来更好.唯一的问题是,当您单击添加评论"时,模式会同时显示艺术家"和评论"字段.演出者字段是一个下拉菜单,用于选择要应用注释的演出者.我希望能够隐藏艺术家"字段,并根据您点击添加评论"链接所依据的页面自动完成此设置.

I've built a model called ArtistComment, created a CreateView and added this to the DetailView using modal divs so it looks nicer. The only issue is that when you click 'add comment' the modal shows both the 'artist' and the 'comment' fields. The artist field is a dropdown menu to select which artist the comment is applied to. I would like to be able to hide the 'artist' field, and have this auto-complete based on the page you follow the 'add comment' link from.

我设法通过'self.request.user'使'User'字段自动完成,但是每当我尝试使用诸如self.request.artist_id之类的方法时,它的模态表单将显示为空白.谁能帮助我指出正确的方向来解决此问题?

I've managed to get the 'User' field to autocomplete with 'self.request.user' but whenever I try anything like self.request.artist_id it makes my modal form show blank. Can anyone help point me in the right direction to fix this issue?

views.py:

class ArtistCommentCreate(CreateView):
    model = ArtistComment
    fields = ['artist', 'message',]

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

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super(ArtistCommentCreate, self).form_valid(form)

urls.py:

url(r'^artist-(?P<pk>[0-9]+)/$', login_required(views.ArtistDetailView.as_view()), name='artistdetail'),
url(r'^artistcomment/add/$', login_required(views.ArtistCommentCreate.as_view()), name='artistcomment-add'),

artistdetail.html:

artistdetail.html:

<a data-toggle="modal" data-target="#artistcommentModal" href="{% url 'events:artistcomment-add' %}">Add A New Comment</a>

<div id="artistcommentModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body"></div>
        </div>
    </div>
</div>

推荐答案

要隐藏艺术家字段,请从字段中删除 artist .

To hide artist field remove artist from fields.

要在 ArtistCommentCreate 视图中获取艺术家,请重写网址,如下所示:

To get artist in ArtistCommentCreate views rewrite url as below:

  url(r'^(?P<artist>\d+)/artistcomment/add/$', login_required(views.ArtistCommentCreate.as_view()), name='artistcomment-add'),

以及您的详细信息html:

and in your detail html:

<a data-toggle="modal" data-target="#artistcommentModal" href="{% url 'events:artistcomment-add' artist= artist.id%}">Add A New Comment</a>

在您的评论视图中,将艺术家pk作为 self.kwargs.get('artist')

in your comment view get artist pk as self.kwargs.get('artist')

这篇关于如何“自动填充" CreateView字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆