如何获取提交表格的slug?

时间:2014-09-24 12:23:59

标签: django

我将表单添加到SingleStory()视图中,该视图由AddTask()处理。但我有一个问题,我不知道如何得到一个slu :: form.instance.story = Story.objects.get(slug = slug)?你有什么建议吗?

现在我收到错误:"全球名称' slug'未定义"。

这是我的views.py:

class SingleStory(View):
    model = Story

    def get(self, request, slug):
        story = Story.objects.get(slug=slug)
        tasks = Task.objects.filter(story=story)
        form = AddTaskForm
        total_time = 0
        for task in tasks:
            total_time += task.iteration
        return render(request, 'single-story.html', locals())


class AddTask(CreateView):
    model = Task
    form_class = AddTaskForm
    template_name = 'add-task.html'
    link_name = 'add-task'
    success_url = reverse_lazy('all-stories')


    def form_valid(self, form):
        form.instance.story = Story.objects.get(slug=slug)
        form.save()
        return super(AddTask, self).form_valid(form)

urls.py

url(r'^add-story/', AddStory.as_view(), name='add-story'),
url(r'^add-task/', AddTask.as_view(), name='add-task'),
url(r'^(?P<slug>.*)/$', SingleStory.as_view(), name='single-story',),

1 个答案:

答案 0 :(得分:1)

与Python中的任何内容一样,您无法引用当前范围中不可用的变量。在这种情况下,没有名为'slug'的本地或全局变量,因此您的错误。

Django基于类的视图将从URL中提取的字符串放入实例的args列表或kwargs字典中。为了在AddTask视图中工作,您需要捕获该视图的URL中的slug,就像对SingleStory视图一样:

url(r'^(?P<slug>.*)/add-task/', AddTask.as_view(), name='add-task'),

然后在视图中使用它:

form.instance.story = Story.objects.get(slug=self.kwargs['slug'])