How to use updateview with a ForeignKey/OneToOneField

时光总嘲笑我的痴心妄想 提交于 2019-12-10 18:37:16

问题


class ModTool(models.Model):
...
issue = models.OneToOneField(Issue)
priority = models.CharField(max_length=1, choices=PRIORITY, blank=True)
status = models.CharField(max_length=1, choices=STATUS, default='O', blank=True)

url

url(r'^moderate/(?P<pk>\d+)', ModEdit.as_view(),name='moderation')

view

class Modedit(UpdateView):

    model = ModTool
    template_name = 'myapp/moderate.html'
    fields = ['priority','status']

At this point I am not able to figure out how to set this view to edit the particular ModTool instance which has the onetoonefield with Issue given in the pk.


回答1:


You can use the slug_field and slug_url_kwarg attributes for this:

url(r'^moderate/(?P<issue_id>\d+)', ModEdit.as_view(),name='moderation')

class Modedit(UpdateView):
    slug_field = 'issue_id'
    slug_url_kwarg = 'issue_id'
    model = ModTool
    template_name = 'myapp/moderate.html'
    fields = ['priority','status']

This will do a lookup on issue_id=<issue_id> where issue_id is the issue's primary key as captured in the url.

I've renamed the keyword argument pk to issue_id to prevent a name clash with the lookup for the primary key. Otherwise an additional filter would take place that filtered on the ModTool's primary key with the value for the Issue's primary key.



来源:https://stackoverflow.com/questions/24367212/how-to-use-updateview-with-a-foreignkey-onetoonefield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!