nnic
nnic

Reputation: 17

Django how to create different view

I write some createview in my views.py file just like UserCreateView,DeptCreateView.

class UserCreateView(CreateView):

    model = User
    form_class = UserForm
    template_name = 'add.html'
    success_url = '/member/'

    def get_initial(self):
        return { 'date': datetime.date.today }

class DeptCreateView(CreateView):
    model = Dept
    form_class = DeptForm
    template_name = 'add.html'
    success_url = '/member/'

I want to add a MyCreateView to choose which UserCreateView or DeptCreateView to add.

def MyCreateView(request):
    table = request.POST['table']
    create = { 'User': UserCreateView,
            'Dept': DeptCreateView,
            }
    p = create[str(table)].as_view()
    return HttpResponseRedirect(reverse(p))

I get a error message

Reverse for 'oa.views.UserCreateView' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

Thank you in advance for any help.

Upvotes: 0

Views: 89

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

That isn't the way to do it at all. There's no point in using the view classes in your dispatch dictionary.

Instead, give each URL pattern a name, and use that in your reverse call:

url(r'/url/for/user_create', UserCreateView.as_view(), name='user_create')
url(r'/url/for/dept_create', DeptCreateView.as_view(), name='dept_create')

...

create = { 'User': 'user_create',
           'Dept': 'dept_create',
         }
p = create[table]
return HttpResponseRedirect(reverse(p))

Upvotes: 1

Related Questions