django11
django11

Reputation: 811

How to get slug for a submit form?

I have form added to SingleStory() view which is processed by AddTask(). But I have a problem, I don't know how to get a slug for this: form.instance.story = Story.objects.get(slug=slug)? Do you have any advices how to do it?

Now I get error: "global name 'slug' is not defined".

Here is my 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',),

Upvotes: 2

Views: 3781

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599628

As with anything in Python, you can't reference a variable that is not available in the current scope. In this case, there is no local or global variable called 'slug', hence your error.

Django's class-based views put strings extracted from the URL into the instance's args list or kwargs dictionary. For this to work in your AddTask view, you would need to capture the slug in the URL for that view, as you do for the SingleStory view:

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

and then use it in the view:

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

Upvotes: 3

Related Questions