简体   繁体   English

如何“自动填充” CreateView字段

[英]How do I 'Autofill' a CreateView field

I have a model called Artist, and now I'm working on building a comment section for the Artist DetailView. 我有一个称为Artist的模型,现在我正在为Artist DetailView构建注释部分。

I've built a model called ArtistComment, created a CreateView and added this to the DetailView using modal divs so it looks nicer. 我建立了一个名为ArtistComment的模型,创建了一个CreateView,并使用模态div将其添加到DetailView中,这样看起来更好。 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. 我希望能够隐藏“艺术家”字段,并根据您点击“添加评论”链接所依据的页面自动完成此设置。

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. 我设法通过'self.request.user'使'User'字段自动完成,但是每当我尝试使用诸如self.request.artist_id之类的方法时,它的模态表单就会显示为空白。 Can anyone help point me in the right direction to fix this issue? 谁能帮助我指出正确的方向来解决此问题?

views.py: 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: 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>

To hide artist field remove artist from fields. 要隐藏艺术家字段,请从字段中删除artist

To get artist in ArtistCommentCreate views rewrite url as below: 要在ArtistCommentCreate获得艺术家, ArtistCommentCreate按如下所示重写URL:

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

and in your detail html: 并在您的详细信息html中:

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

in your comment view get artist pk as self.kwargs.get('artist') 在您的评论视图中,将artist pk作为self.kwargs.get('artist')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM