Thursday, November 23, 2017

Some newbie questions on CBVs and FBVs

Hi everyone,

First of all sorry for the newbie questions it has been a long time since I used Django and I think I have forgotten just about everything I once knew.

I'm working on a user app for a website. I can't use the built in user model as I need a little more flexibility and the ability to grow in the future if required.

Basically I have three problems.

1) I need some views to be limited to the user who created the view. For instance I have an UpdateUser view and I only want the currently logged in user to be able to change their own user model data. So say I have the username "djangouser" and I go to UpdateView the only row in the database that I can change on the database server is the one with the username "djangouser". I'm not sure what the best way to handle this problem is?

I could do it manually in a function based view without any problem but I find CBVs to be really hard to customise when you want to do something that they were not specifically designed to do. At that point I just end up writing a FBV instead and doing it all myself as it is quicker than trying to figure out all the mixins and all the methods of the class.

I must be missing something simple with CBVs. Any help would be appreciated with this :).

2) In FBVs you get passed a variable to the function with the URL conf variables, for instance: (path('/blah/<username>/', view, name='blah') would result in the FBV recieving a username parameter. Where are these variables stored when using a CBV?

3) Is it considered bad practice to use FBVs in Django? I just find them so much easier and quicker to write. I know that CBVs result in less code duplication but I find I constantly need the Django docs open to see what each CBV supports and which methods it has available. Where as with FBVs I just write the code and everything works.

Anyway, thank you for any help :).

Simon.

No comments:

Post a Comment