Django web interface components - python

I am using python and django and like it a lot. But than i use it, I catch myself thinking
what i do a lot of work to render result data and write specific actions for it. For example than i pass result set of objects to template
i must render all data and write all possible actions such as sorting by columns,filtering,deletion,edit etc, for each of this i need
to write code in urls.py and views.py, sometimes helps generic view but it's has poor functions.
Is there some solutions to automate this work?
i mean use some interface compontents (such as "model list renderer with column filter and pagination") to wich i need only
"bind my model", all other routing work for drawing common interface action must be allready implemented in these components.
i think i need something like configurable components for fast building html web interface for models (such as model forms do fast generation forms for models).
What do you think can help in this case?

must render all data and write all
possible actions such as sorting by
columns,filtering,deletion,edit etc
Like django.contrib.admin? But I guess it's way to complicated and bloated for your needs.
sometimes helps generic view but it's
has poor functions
And that's the way, I think, you should be going. If you write same views over and over again, just make your own generic views. As an example of more robust views and a source of inspiration I recommend you to look at class-based generic views.
Also consider using model inheritance and custom managers.

Related

Django logic and where to put it?

I am new to Django, but I recently created my first application. I am wondering if I put my logic in the wrong places. From the Django book, I got that logic should but put into the views and data in models. But I have recently read that views should be as small as possible and let models handle the logic. My problem is my views handle all my logic while my models only handle data going to and from my database. Have I messed up when creating this app, and if so, how would I fix it?
Django's philosophy / best practices encourage "fat models thin controllers" (controllers being Views in Django). Having tried both ways, it definitely works better with the "fat models" approach. Keeping the logic as close to the data models makes it more reusable and you can there are many features in Django that work better that way.
One example would be returning a paginated list view. If you need to calculate something for every object in a queryset, you could
loop over it in the view doing the calculation
or you could add a model method then call it on every iteration in the template.
Looping over the queryset in the view will do the calculation on the whole queryset - not good if you are only showing 10 objects from a list of 1000.
Calling a model method from the template, the calculation will only be done on the 10 objects on that page.
Obviously you can add some more code to the view to only do that calculation on the objects on that page, but then thats extra code that isn't needed if you go the other route. If you need the same calculation on another page, keeping the logic in a model method will be reusable without any alteration, while you will need to cut and paste it in the view, or create a new method. While its not a huge difference, lots of small things like this start to add up.
It is better to have "Fat Models, Skinny Views." Many of Django experts will give you this tip. Google this phrase and you will find some resources that are saying "Fat Models, Skinny Views," or "Fat Models, Skinny Controllers." By the way, Django creators named Controllers as Views, and Views as Templates which maybe will cause some misunderstanding while reading articles about MVC which is MTV in Django.
No you haven't mess it up. You can find your solution through experience (years of developing).
So, either using fat models and thin views or the opposite its up to you and your application requirements.
As you learn you'll discover new techniques and methods that will help you extend your "logic" and your app implementation.
At the beggining you'll make mistakes, but that's alright. We need them to become better developers, coders etc.
So my advice is: keep calm and learn (good practices)!
The way to do it is simple. And I would say that it is not actually messed up if your logic lies in views mostly.
The most repetitive functions and logic which you have used in views in multiple functions, you can create a function defined in model and then call that function in views. (you can do it step by step)
For example if it is a social network and you are setting the city of the user. Now as your app grows, possibly there will be many functions and many places through which city is being set. If you are doing it all in views repitively then you would be stuck at some point of time because to make smallest of changes, you might have to edit all the functions.
The good way would be to define set_cities(self, cities) in user model and call it whenever needed like user.set_cities(cities_list). So if you have to trigger other functions everytime city is being set (maybe like sending notifications or updating other tables), you have to define it once only in set_cities().
In any case, all logic cannot be only in models so do not worry much about it. Just keep on trying to simplify the views and keep on shifting any repetition of logic to models.

Pyramid: simpleform or deform?

For a new (Python) web application with the Pyramid web framework, I'd like to use a form binding and validation library and so far found simpleform and deform. Does anyone have experience with these, and can tell me why I should pick one or the other? I am not using an ORM, just POPO's so to say.
I think I would prefer the easiest for now.
I've not had extensive experience with either, but so far this is what I've learned.
They both use colander (which I very much like) for definition and validation of forms. In my opinion what really sets them apart is their rendering mechanisms. In this regard, deform is the most straightforward in the sense that it allows you render the whole form by just doing form.render() in your template. On the other hand, with simpleform you must render each field manually. This could be either a good or bad thing depending on what you need.
A drawback with simpleform is currently there is no clear way to handle sequence schemas in templates.
edit: Also, in my opinion, deform has better documentation available.
I haven't used simpleform yet, but I have been using deform for a project I'm currently working on. deform allows you to render templates from a colander schema, which is very handy. Also, if the schema is violated you can simply call ValidationFailure.render() (after catching the ValidationFailure exception) and a message that you can customize is rendered with the form. I'm currently grappling with the choice between rendering the entire form and rendering it piece by piece. It would be really nice if you could group components together for rendering.
Though it's a third alternative, but have you considered ToscaWidgets2?
From a quick glance on simpleform and deform, it seems to me that Toscawidgets2 is the golde middle between those two in case of features and simplicity.
There's even a tutorial for using it with Pyramid, just drop the database part and supply the form values as a dict.
For your information, deform is used by :
Kotti : http://kotti.readthedocs.org/en/latest/
Substance D : https://substanced.readthedocs.org/en/latest/

Django AdminSite - Difficult or Easy Implementation?

Has anyone implemented their own AdminSite? How easy/hard was the basic implementation?
I'm in the midst of building a "cms" that's going to be quite large and decently complex in some areas and I'm wondering if using something like AdminSite would save some time. I'd rather not have to make my own implementation for admin actions and inlines and the like (I know I can just use inline forms but that's not as simple as inlines = [Foo]).
When using a custom AdminSite, is further customization equivalent to customizing the standard Django admin?
You've read the admin site docs. It's a lengthy document, but two main hooks for adding custom functionality is through custom urls and modified standard views in your own AdminSite and ModelAdmin objects. Once you hook those in and the urls get mapped, it's just like building any other Django application, only that the templates aren't yours, so they're are a bit hard to manage and take getting used to. But it allows you to do additional gymnastics, like adding a form wizard to the admin site or splitting everything into multiple forms and rendering them in a single HTML form element in the templates, doing custom handling of GET/POST requests, etc.
I've used it in the past to create views for displaying custom reports and to create custom editing scenarios for the staff. My opinion is that you should KISS as much as possible. The admin site is all about generic views and generic presentation. Do expand, but be cautious if you override template blocks and think twice before you override something that's not wrapped in a block. Certain admin site features have certain presentation assumptions and the JS client app that's shipped with Django makes some too (that's what I've figured when working with adding dynamic inline models way back), so it'd be quite an undertaking if you'd like to roll a completely different presentation.
The answer in any case is YES! The admin site will provide you with more features for managing your model data interactively. I don't know how extensively you'd need to customize the admin, but there are CMSs, dedicated admin apps and admin integrated apps that are a real eye-opener. Django CMS, as I recalled, has been praised as the best open-source Django CMS out there and from what I can see it rolls it's own cust change/list views. Rosetta is an admin site only app that allows you to edit your translation files interactively and has an exhaustive admin interface! If you shop around on bitbucket and github you'll find many more examples, it should help you figure out best how much effort you'd need to put into it.
Both
If you are OK with it not doing exactly what you want its pretty much done for you automatically. If you need fine grain control over certain things it can be hard to customize without knowing the internals of the admin code.
the django admin is more of a one size fits all kind of ui which may not be intuitive for use in some cases ..
customizing its look is easy but extending it is some how hard. you are better off designing your own views in that case.

Using classes for Django views, is it Pythonic?

I'm currently learning Python and coming from a strong C# background. I keep hearing about doing things in a Pythonic way to take advantage of the dynamic nature of the language and some of it I get and some I don't.
I'm creating a site with Django and my approach to views is to use classes. My current thinking is to have a base class that has some stuff about the template and the model to use. This will have a default funky 404 type page with site search and stuff on then base all the other pages off this. So each area of the site will have its own EG News and all the model related functions and filtering will be in that class with a further class on top of that for HTML or AJAX requests. So you would have something like this:
\site\common\ViewBase
--\news\NewsBase(ViewBase)
--\news\HtmlView(NewsBase)
--\news\AJAXView(NewsBase)
URLs would be mapped like http://tld/news/latest maps to site.news.htmlview and http://tld/news//to/ will be also be mapped site.news.htmlview but the class will figure out what to do with the extra params.
This is pretty much what I would do in C# but the Django tutorial only shows using methods for views, making me wonder if this is not a very pythonic solution?
Thoughts?
Edit: After S.Lott comment about thread safety, Is it better to leave the functions as they are and have them create an instance of a class and call a method on it?
What I am looking for is a place to put common code for each section of the site for filtering the model, authentication for the site, etc
Certainly there's nothing wrong with using a class for a view, provided you route the URL to an actual instance of a class and not just a class directly.
The Django admin does exactly this - look at the source code in django/contrib/admin.
The advantage of classes is that they are much easier to customize, for example you can add hooks for permission checking.
There is a proposal to move all existing generic views over to classes, it was supposed to get into 1.2 but failed to meet the deadline.
As the above poster points out, be very careful about handling instance variables - if you look at the admin classes, you see the request being passed to the various methods instead of relying on "self".
Setting aside other concerns (such as thread-safety issues), it feels like there's a real possible danger here to cross the bright lines between Model / View / Template.
Or maybe it feels like a replacement for url dispatching (not that there's anything wrong with that :-). I'm not sure, but it just feels slightly off.
While class-based views are useful, inheritance may not be the right tool for this particular job. Helper functions and decorators are two great ways to factor out common code from your views. They also tend to be be more familiar/natural to other (python) coders who might work on your code.
I'm not sure what the best approach is in your case as I don't know how much you ultimately want to factor, just keep in mind that there are other ways to factor in python besides inheritance.
p.s. kudos for seeking out a pythonic solution.

MVC and django fundamentals

Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before. Any insight / help would be greatly appreciated!
"data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before"
Django imposes best practices on you. You don't have a lot of choices and can't make a lot of mistakes.
MVC (while a noble aspiration) is implemented as follows:
Data is defined in "models.py" files using the Django ORM models.
urls.py file maps URL to view function. Pick your URL's wisely.
View function does all processing, making use of models and methods in models
Presentation (via HTML templates) invoked by View function. Essentially no processing can be done in presentation, just lightweight iteration and decision-making
The model is defined for you. Just stick to what Django does naturally and you'll be happy.
Architecturally, you usually have a stack like this.
Apache does two things.
serves static content directly and immediately
hands dynamic URL to Django (via mod_python, mod_wsgi or mod_fastcgi). Django apps map URL to view functions (which access to database (via ORM/model) and display via templates.
Database used by Django view functions.
The architecture is well-defined for you. Just stick to what Django does naturally and you'll be happy.
Feel free to read the Django documentation. It's excellent; perhaps the best there is.
first, forget all MVC mantra. it's important to have a good layered structure, but MVC (as defined originally) isn't one, it was a modular structure, where each GUI module is split in these tree submodules. nothing to use on the web here.
in web development, it really pays to have a layered structure, where the most important layer is the storage/modelling one, which came to be called model layer. on top of that, you need a few other layers but they're really not anything like views and controllers in the GUI world.
the Django layers are roughly:
storage/modelling: models.py, obviously. try to put most of the 'working' concepts there. all the relationships, all the operations should be implemented here.
dispatching: mostly in urls.py. here you turn your URL scheme into code paths. think of it like a big switch() statement. try hard to have readable URLs, which map into user intentions. it will help a lot to add new functionality, or new ways to do the same things (like an AJAX UI later).
gathering: mostly the view functions, both yours and the prebuilt generic views. here you simply gather all the from the models to satisfy a user request. in surprisingly many cases, it just have to pick a single model instance, and everything else can be retrieved from relationships. for these URLs, a generic view is enough.
presentation: the templates. if the view gives you the data you need, it's simple enough to turn it into a webpage. it's here where you'll thank that the model classes have good accessors to get any kind of relevant data from any given instance.
To understand django fundementals and the django take on MVC, consult the following:
http://www.djangobook.com/
As a starting point to getting your hands dirty with ...
"...trying to find some comparable data / architectural models"
Here is a quick and dirty way to reverse engineer a database to get a models.py file,
which you can then inspect to see how django would handle it.
1.) get an er diagram that closely matches your target. For example something like this
http://www.databaseanswers.org/data_models/product_catalogs/index.htm
2.) create an sql script from the er diagram and create the database,
I suggest Postgre, as some MySQL
table type will not have forgien key constraints, but in a pinch MySQL or SQLITE
will do
3.) create and configure a django app to use that database. Then run:
python manage.py inspectdb
This will at least give you a models.py file which you can read to see how django attempts
to model it.
Note that the inspect command is intended to be a shortcut for dealing with legacy
database when developing in django, and as such is not perfect. Be sure to read the
following before attempting this:
http://docs.djangoproject.com/en/dev/ref/django-admin/#ref-django-admin

Categories

Resources