Implementing MVC pattern with Django Rest Framework - django

I was wondering how could I implement a MVC pattern on a Django Api project, when I start a django project it gives me the apps.py, admin.py, models.py and the views.py , I understand the the models, should be the "M", and the views the "V", but as i'm using the project like an api, the view would be an Angular or React App, so where I put the logical ? Where is the right place to put the "C" controller on a django rest framework project, is it on views.py ?

You need to understand that web service (which you are going to implement with Django) and your client app (which you are going to implement with Angular) are totally different apps and they should not depend on each other. These apps will have their own Models, Views and Controllers.
If we are talking about some business logic that you need to store somewhere on a backend then you can use an approach where you will have an additional level (usually, people call it services.py) and you will import code from this layer to views.py and only call it there cause your views should stay clean and simple as much as possible.
In an ideal case, especially, at the start, I guess, you will not have some tricky logic and mostly your API will look like simple CRUD, so for that case, you even don't need to store additional logic somewhere you just can use rest framework ViewSets as is and store some little snippets in utils.py.
The bottom line is - you don't understand fundamentals that's why you asked the wrong question. And you don't need it right now. Just go and write your app and read the docs about frameworks that you are using, eventually, you will understand this topic.

Related

Structuring a large API in a Django Project

Right now I have a large project with an equally large API (done using django rest framework). The current structure is something like this:
api
|-----urls.py
|-----models.py
|
----v1
|-----views.py
|-----serializers.py
|-----permissions.py
|-----tests.py
etc
As you can guess, the views.py file is pretty big and I want to refactor this out. Currently I have a few options in front of me, the one I'm leaning towards is to put an 'api/v1' package into each app and use the api app to tie all the urls together and hold views that don't fall into an app.
Does anyone have any experience with this and could provide guidance?
Yes, that's how we're doing it in the project I'm working on at the moment... have an api module under each app in your Django project

Restful routes and Django

I'm in a process of migrating Rails project into Django. Rails project was built using restful routes and it never touches the database. Instead, it simply redirects to different methods which all call an external service with the specified action method. Now, I have found a number of frameworks for django that provide restful capability plus a bunch of bells and whistles, but it's an overkill for my current case.
As an alternative, I can ignore action method in urls.py by simply providing a regex to validate urls and then parse the request method in views.py, redirecting to the appropriate method. Is this a way to go or are there any other approaches that I can look at?
Class based views look like the idiomatic way to organize restful view functions by request method.
Django snippets has several simple example implementations.

Django Sites - Different urls.py for two sites

I maintain a Django webapp for a client of mine. We built it out in Django and for computer users, it's great. We now want to cater to mobile device users.
On top of a template switch, we also need things to work differently. The application will have views that work in a subtly different way but also the URL structure needs to be simplified.
I realise what I'm about to ask for violates the DRY ethos but is there a good way to split the urls.py so that half of it is for ourdomain.com and the other half is for m.ourdomain.com? If I can do that, I can add a mobile_views.py and write the new views.
Django's Sites is enabled in the project but I'm happy to use a hard-coded request.domain.startswith('m.')-style hack. Seems like that might perform better - but I've no idea how one gets the request from the URLs file.
Use middleware to detect the access to the other site and set request.urlconf to the other urlconf that you want to use.

Using django models across apps?

So in my Django project I have a few different apps, each with their own Models, Views, Templates, etc. What is a good way (the "Django" way) to have these Apps communicate?
A specific example would be a Meetings App which has a model for Meetings, and I have a Home App in which I want to display top 5 Meetings on the home page.
Should the Home App's View just query the Meetings App's Model?
It feels like that is crossing some line and there might be a more de-coupled way to do things like this in Django.
At some point your apps will have to couple in order to get any work done. You can't get around that.
To achieve decoupling as much as possible,
You need to have a Project specific app, that does all the hooking up things between each other.
Using signals from models to create new models in a decoupled apps helps. But doing too much of this, is foolish.
Should the Home App's View just query the Meetings App's Model?
Yep, that's how it's done. If you really want to decouple things, you could make your Home app use generic foreign keys, and some sort of generic template system, but there's not really a good reason to, unless you have grand plans for your home app being pluggable and working with a bunch of other different Django apps.
Writing tightly coupled Django apps is really easy, and writing decoupled Django apps is really hard. Don't decouple unless you have a reason to, and you'll save yourself a lot of work (and happiness!).
If it were me, I would make a template tag in your meeting app that produces the desired output and include that template tag in the home app's template.
That way you are only coupling them in the View portion of the MVC and makes it easier to maintain if you change your models in the meeting app.
For your specific example, I would use a Django templatetag.
Having a templatetag "display_top_meetings" in your Meetings app, and calling it with {{ display_top_meetings 5 }} from your index template, loading it first.
You can read more about templatetags here:
Django Official documentation about TemplateTags
B-List's article on writting 'better template tags'
I hope this help!
yes. I think thats a design feature. All models share a backend, so you'd have to do extra work to have two models with the same name in different apps.
Projects should not share Models

Django and Restful APIs

I have been struggling with choosing a methodology for creating a RESTful API with Django. None of the approaches I've tried seem to be the "silver" bullet. WAPI from http://fi.am is probably the closest to what I would like to accomplish, however I am not sure if it is acceptable in a true RESTful API to have parameters that are resource identifiers be in the querystring instead of in a "clean" URL format. Any suggestions for modifying WAPIs RestBinding.PATTERN to "clean" up the URLs? Another option I've explored is Django-Rest-Interface. However this framework seems to violate one of the most important pieces I need, and that is to include the full resource URL for references to other resources (see http://jacobian.org/writing/rest-worst-practices/ Improper Use of Links). The final option is to use django-multiresponse and basically do it the long way.
Please offer me your best advice, especially people that have dealt with this decision.
For Django, besides tastypie and piston, django-rest-framework is a promising one worth mentioning. I've already migrated one of my projects on it smoothly.
Django REST framework is a lightweight REST framework for Django, that
aims to make it easy to build well-connected, self-describing RESTful
Web APIs.
Quick example:
from django.conf.urls.defaults import patterns, url
from djangorestframework.resources import ModelResource
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
from myapp.models import MyModel
class MyResource(ModelResource):
model = MyModel
urlpatterns = patterns('',
url(r'^$', ListOrCreateModelView.as_view(resource=MyResource)),
url(r'^(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=MyResource)),
)
Take the example from the official site, all above codes provide api, self explained documentation (like soap based webservice) and even sandboxing for testing. Very convenient.
Links:
http://django-rest-framework.org/
I believe the recently released django-piston is now the best solution for creating a proper REST interface in Django. django-piston
Note: django-piston seems to no longer be maintained (see comments below)
django-tastypie is a good way to do it, their slogan: "Creating delicious APIs for Django apps since 2010" is pretty comforting ;)
You could take look at django-dynamicresponse, which is a lightweight framework for adding REST API with JSON to your Django applications.
It requires minimal changes to add API support to existing Django apps, and makes it straight-forward to build-in API from the start in new projects.
Basically, it includes middleware support for parsing JSON into request.POST, in addition to serializing the returned context to JSON or rendering a template/redirecting conditionally based on the request type.
This approach differs from other frameworks (such as django-piston) in that you do not need to create separate handlers for API requests. You can also reuse your existing view logic, and keep using form validation etc. like normal views.
I don't know if this project can be useful for you, but sending a link can hardly hurt. Take a look at django-apibuilder , available from http://opensource.washingtontimes.com/projects/django-apibuilder/ . Perhaps it can be useful?
/Jesper
Have a look at this RestifyDjango.
Somewhat related are Django XML-RPC and JSON-RPC.
https://github.com/RueLaLa/savory-pie
Savory Pie is a REST framework that supports django.
I would suggest you look into Django Rest Framework (DRF), play around with this and see if it suits your requirements. The reason I recommend DRF is because it makes making the API views really simple with the use of GenericAPIView classes, Mixin Classes and Mixed in Generic views. You can easily make use of tried and tested design patterns for making your API endpoints as well as keeping your code base neat and concise. You also DRY when writing your code which is always great. Your API views are literally 2-3 lines long.
You can checkout this tutorial http://programmathics.com/programming/python/django-rest-framework-setup/ that begins from setting up your environment to going through the different ways to make your RESTful API using the django rest framework.
Disclaimer: I am the creator of that website.