Do I need another views file for my classes? - django

I am trying to make a calendar application. So I would need to make some classes to display the calendar and add events to it. Do those classes still go in my views file or do I have to make a separate directory and import it to my views file and make then make an instance of it?

Most people put view classes into the views.py file.
If it becomes unmanageable or you need further organization, split them as necessary.
You don't need to import it into views.py - they are ultimately only used by the urls.py which don't require views live in any particular place.
If you're talking about application logic, if it's a huge class that's not necessarily related to the web HTTP response cycle, then it makes sense to place it in another file.

Related

Django, where should the code go? views or models

I have a bunch of REST views and a bunch of data transfers posted from templates that needs to be cleaned. I am wondering where to put all the sanitizing code and processing code should go: views.py or models.py ? Am I missing some secret tricks that I don't know about? (like usage of model.manager) ?
Currently I kept the models clean with object creation and update. Views is nicely organized with strictly REST views. But as the project grows, more and more code, especially handling of data that has accumulated. (views.py file had grown in size to 150lines) Should I put them in another file. If so, is that ok to pass the whole "request" to that file? (along with having to import models and possibly sessions and messages)
I have implemented my django apps like this:
In models.py: just add the definition of the models and some code usefull for the Signals because in my application will work with other models
In view.py: here i add the code usefull for manage the form for the frontend and create the json necessary for the API call to external app
of course you can split the code in other files and call the functions when needed like fuctions.py or options.py
from .functions import calc
External app with Rest Framework: here is the CORE of the application, where i'll call the models, where all the logic is available
This is how i use it, by the way is always better use the view.py for write the code.
Some Tips about The Model View Controller pattern in web applications

How can I automate urls for django generic views?

I have subclassed Django's generic views for my project. I use them extensively to create basic CRUD views on our front-end site. Some models have just a create view, some have a read and update, etc.
This works well but I still write a line of code for each URL. ie:
url(r'^referrer/create/$',ReferrerCreateView.as_view(), name='referrer_create'),
url(r'^referrer/$',ReferrerListView.as_view(), name='referrer_list'),
url(r'^referrer/(?P<pk>\d+)/update/$',ReferrerUpdateView.as_view(),
name='referrer_update'),
I then do this for every model and the views that model has. This doesn't seem to be a very DRY approach to me. Is there a good approach to automating these urls for any generic view that has been created for a model?
The solution is to create a method that will return a list of url() calls given a set of views. Something like
views = {
'base_name': 'referrer',
'create_view': ReferrerCreateView,
'list_view': ReferrerListView,
'update_view': ReferrerUpdateView,
}
def generate_urls(views):
return [
url(r'^%s/create/$' % views['base_name'], views['create_view'].as_view(), '%s_create' % views['base_name'],
# and so on
]
Then you just need to do
urlpatterns = patterns('', *generate_urls(views))
For every set of views you have.
That being said I believe you shouldn't do this. This solution (or any different implementations) is over complicated and will add an extra layer you'll need to go through if things go wrong.
There's nothing wrong of having some boilerplate code, especially configuration code, because it makes your life much easier to debug in the future.
I have the same very concern and I shared it here before
One answer was the use of django rest framework as it implements such url patterns on its own!?! I didn't experience this solution yet.
My workaround is to have a dedicated file for crud operations for every model.
By that solution I decreased the matching time , and grouped related model pattern in one file.
BUT I understand that wont fully solve your question

how to make interaction between different django apps in a single site?

I have just learnt about Django apps. I want to know that within one site, if I make different apps. like, users, profiles, polls, blogs,comments, jobs , applications then how can I manage them to make them intereactive? And is it how the concept of app should be? I want to have things loosely coupled that's why asking? Rails work on the way of REST, so do Django support that also with the use of apps? May be my questions seems a bit ambiguous because I am new to django and some of my concepts are still messed up.
Please tell what ever you know.
The general idea is that apps should be as loosely coupled as possible. The goal is to have completely self-contained functionality. Now, of course, that's not always possible and many times it even makes sense to bring in functionality from another app. To do that, you simply import whatever you need. For example, if your "blogs" app needed to work with your Comment model in your "comments" app you'd simply add the following to the top of the python file you're working in:
from comments.models import Comment
You can then use Comment as if it were defined right in the same file.
As far as REST goes, Django's views are much more fluid. You can name your view whatever you like; you need only hook it up to the right urlpattern in urls.py. Django views can return any content type, you just prepare the response and tell it what mimetype to serve it as (the default is HTML).

How to add multiple views to one template in django?

How to add multiple views in one template of django ?
Is it possible to add more than one view in template .
I have view A that deals with file uploads , and view B that deals with file permissions . How do I put them in one template ? Both are in different apps .
I don't think this is really the best way to go about things. Views are not really meant to be used that way. They should map to requests on a one to one basis.
You might, in fact, need to write a third view which does all the things that the two other views do. Situations like this are where the class based views become very handy. I would try to break out the code that handles all the forms and processing in to separate functions, and just import those when needed.
Another Solution is to do this via ajax somehow. Load those portions of the page separately either after load, or on submit.
You should use custom middleware for that kind of things, so there's no need for different views.

Front-end prototype/skeleton in Django

Often I create a static html prototype/skeleton for back-end developers I work with. This helps to find mistakes in the UI/IA and costly re-writes before the site is implemented.
I would like to take this a step further and create these prototypes/skeletons in Django. By a prototype/skeleton I mean linked static pages that can be easily hooked up to back-end later.
I would like to get some suggestions/ideas how I should set up my templates/links so they are easy to work with later during the implementation stage.
Short list of requirements that come to my mind:
Organization of templates while the entire project will consist of multiple apps
Clean URL dispatcher and link creation
Ability to display logged-in/ logged-out states
I guess in a more traditional approach, the UI designers and back-end developers work on two ends of the development spectrum and hopefully converge somewhere in the middle in a gracious manner. If you'd be willing to get your hands dirty with writing a few lines of code, you could lay out the whole application architecture for the developers because you have the upper hand—your immediately concerned with the users, the data they consume and the interactions they need to perform. That would take out much of the guesswork for the developers, now with only having to fill in the holes, connect the dots or what have you.
The first thing you should do is get together and set some common grounds. Typically, that includes performing modularization at the very beginning. Take all the major features and break them into several Django apps that are going to wrap template, view and model triads relevant to a certain feature the application provides. The more the better holds true here, so don't worry if you end up with a lot of applications, because you never want to have a single application providing too many features/hosting too many components. Commonly you start with apps such as registration, authentication, profiles (user) and work you way outwards. As an example, you could cram the three into a single application, but you end up with a lot of templates, a lot of views, two or three models perhaps, but the tests are really going to be a real choking point. So, break everything into these app buckets until you feel that every part of the system naturally falls into place on a conceptual level. If your ever find yourself thinking where something should be placed, or your looking at a module that's several pages long and feel tempted to break the module (models.py, views.py, test.py) into a package with many intra-package modules, you should probably refactor the architecture immediately. Always remember that your efforts here are to strike simplicity with your architecture.
Once that's done, you've really done half of the work. Great thing about Django is that you have loose coupling between URLs and views. The views themselves provide the application behavior and streamline the presentation. If you can properly pave out the main URLs and stub out the views to just churn out static templates, you've just done some fine work.
This is how it's accomplished. You can abstract URLs and the views they're mapped to by naming your patterns, such as authentication:login, authentication:logout, registration:register, registration:confirm, registration:activate, etc. This is how you tie your internals to all the behaviors that are provided and these shouldn't be subject to change. You can then always change the URL pattern for authentication:login, change the view that pattern maps to, but your referencing it by an internal name, so you can, say, swap out the views that just churned out static templates with a full blown view without having to do any additional modifications to your code.
So here's how it works in real life:
Brainstorm, decide on the apps and the features they'll provide and review your decisions.
Start of with a core application that's going to host some project specific features, such as base templates and the root / view.
Create a /core/templates/core/base.html that's going to load all the common CSS/JS files that are going to be used site-wide, that'll define the header, contents and footer sections (template blocks) and that's going to use context variables for page metadata, such as title, description, keywords and robots. Your typical "One Template To Rule Them All", the bits that are going to be present in structure/presentation for all of your pages.
Create a simple /core/temaplates/core/welcome.html, that extends the core template and prints "Hello world!" in the content area.
Add the following to /core/urls.py:
from django.conf.urls.defaults import *
from django.views.generic import TemplateView
urlpatterns = patterns('',
# Welcome
url(
r'^$', TemplateView.as_view(template_name='core/welcome.html'),
name='welcome'
),
)
Hook it up in the main /urls.py:
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(ur'^', include('core.urls', namespace='core')),
url(ur'^admin/doc/', include('django.contrib.admindocs.urls')),
url(ur'^admin/', include(admin.site.urls)),
)
Hit http://localhost:8080/, see the "Hello World!", revel in the warm fuzzy feeling.
Repeat the same for the rest of the apps: create the app, create the patterns, name them, map them to a static template, hook it to a namespace in the main urlconf.
You can push the views even further to production readiness for the developers. It might depend on the devs and their style guidelines, but I like to keep my /urls.py clean of everything else but patterns, names and view mappings. Your /core/urls.py could look like:
from django.conf.urls.defaults import *
from core import views
urlpatterns = patterns('',
# Welcome
url(
r'^$', views.Welcome.as_view(),
name='welcome'
),
)
Edit /core/views.py with the following:
from django.core.views.generic import TemplateView
class WelcomeView(TemplateView):
template_name='core/welcome.html'
extra_context={
'page_title': 'Welcome!',
'page_keywords': 'relevant,page,keywords',
'page_description': 'Something equally relevant',
}
def get_context_data(self, **kwargs):
context = super(WelcomeView, self).get_context_data(**kwargs)
context.update(self.extra_context)
return context
And that's one sturdy stubbed-out view, packed with page metadata! Definitely the stuff that'll earn you a beer from the devs. Keep on doing this for all of the views to pump out static templates. When someone approaches to finalizing the views, they'd just have to inherit from a different view class, add the missing features, extend the context, modify the template and voila--it's ready for production.
There's not a lot of upfront learning you'd have to do to make this possible, but it really takes out a lot of the guesswork for devs, which are naturally more concerned with building the rest of the application. It's also simple enough to get really good at, I would guess no one would mind letting you do all of this work. As added beef, you'll probably not be kept in the dark as to how the template context gets populated in the views, so even you can start rolling out more complex views, or at least be able to read them.
When I start an application, I usually make a prototype version as well in Django. I just use direct_to_template generic views, which can later be replaced with the views that the developers create. Since you have multiple apps, you can store app specific templates in a folder in your templates folder that has the same name as the app.
The end result is that you have all the screens displaying at the right urls and can link between them. All developers need to do is replace each url with the custom view they create. Makes it easy.
You may have to do a bit of code if you want the logged in/out status to display, but it is definitely doable.