问题
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