Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to implement python classes in Django?

Tags:

python

django

I'm learning Django on my own and I can't seem to get a clue of where I implement a regular Python class. What I mean is, I don't know where do the Python classes I write go. Like they go in a separate file and then are imported to the views.py or are the classes implemented inside the views.py file?

Example I want to implement a Class Alphabet, should I do this in a separate file inside the module or just implement the functions inside the views.py file?

like image 377
Silvestrini Avatar asked Dec 16 '15 21:12

Silvestrini


4 Answers

I don't know where do the Python classes I write go. Like they go in a separate file and then are imported to the views.py. Example I want to implement a Class Alphabet.

It's just a matter of getting your import statement correct:

django_proj1/
   django_proj1/
   myapp/
      myclasses.py
      views.py

Then in your view:

#myapp/views.py:
from myapp.myclasses import Alphabet

Or, you could do it like this:

django_proj1/
   django_proj1/
      myclasses.py
   myapp/
      views.py

And in your view:

#myapp/views.py:
from django_proj1.myclasses import Alphabet

Response to comment:

And after I successfully imported my class, how do I pass the attributes to an HTML template?

The following is straight from the official django tutorial.

myapp/views.py:

from django.shortcuts import render
from django.http import HttpResponse

from myapp.myclasses import Alphabet  #<*** Import your class.
from django.template import RequestContext, loader  #<*** Import stuff for the template.

# Create your views here.

def index(request):
    alph = Alphabet()
    result = alph.change('hello')  #Your class produces some result here.

    template = loader.get_template("myapp/index.html")
    context = RequestContext(request, {
        'x' : result   #<*** Make a variable named x available in your template.
    })

    return HttpResponse(template.render(context))

The directory structure looks like this:

django_proj1/
   django_proj1/
   myapp/
      myclasses.py
      views.py
      templates/  <***Create this directory 
          myapp/  <***Create this directory
             index.html  <***Create this file

myapp/templates/myapp/index.html:

{% if x %}
<div>The result you requested was: {{x}}</div>
{% else %}
<div>Sorry, couldn't get the result.</div>
{% endif %}

myapp/myclasses.py:

class Alphabet:
    def change(self, word):
        return word + 'Z'

Start the server:

.../my_django_projects/django_proj1$ python manage.py runserver

url in your browser:

http://localhost:8000/myapp/

You should see:

The result you requested was: helloZ

If you comment out the following line in myapp/views.py:

    context = RequestContext(request, {
        #'x' : result   #<*** Make a variable named x available in your template.
    })

Then the template will send the else portion of index.html to the browser:

Sorry, couldn't get the result.

django_proj1/django_proj1/urls.py:

from django.conf.urls import patterns, include, url
from django.contrib import admin

from . import views

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'dj1.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),

    url(r'^myapp/', include('myapp.urls')),

)

django_proj1/myapp/urls.py:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]
like image 146
7stud Avatar answered Oct 18 '22 21:10

7stud


Django is just Python at the end of the day.

You can create new modules anywhere in your project, and import them into your views, models, urls, etc. This is often how you'd organize general utils (utils.py).

You can deliver data to your views in a few ways, for instance:

from your_module import some_object

class MyView(TemplateView):
    template_name = 'some_template.html'

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['my_data'] = some_object.some_method()
        return context

And in some_template.html: {{ my_data }}

like image 39
Patrick Beeson Avatar answered Oct 18 '22 20:10

Patrick Beeson


It depends on the scope of the Alphabet class. If it is a utility class then I would suggest to put in a utils.py file, for example. But it is perfectly fine to have classes in the views.py file, mainly those dealing with UI processing. Up to you.

like image 35
eribeiro Avatar answered Oct 18 '22 20:10

eribeiro


Distinct to similar frameworks, you can put your Python code anywhere in your project, provided you can reference them later by their import path (model classes are partially an exception, though):

  1. Applications are referenced by their import path (or an AppConfig import path). Although there's some magic involving test.py and models.py, most of the times the import / reference is quite explicit.
  2. Views are referenced by urls.py files, but imported as regular python import path.
  3. Middlewares are referenced by strings which denote an import path ending with their class name.
  4. Other settings you normally don't configure are also full import paths.

The exception to this explicitness is:

  1. models.py, test.py, admin.py : They have special purposes and may not exist, providing:

    1. You will not need any model in your app, and will provide an AppConfig (instead of just the app name) in your INSTALLED_APPS.
    2. You will not rely on autodiscovery for admin classes in your app.
    3. You don't want to make tests on your app, or will specify a non-default path for your app-specific test command run.
  2. templates and static files: your project will rely on per-app loaders for your static files and for your templates files, and ultimately there's a brute-force search in each of your apps: their inner static/ and templates/ directories, if exist, are searched for those files.

Everything else is just normal python code and, if you need to import them from any view, you just do a normal import sentence for them (since view code is imported with the normal Python import mechanism).

like image 36
Luis Masuelli Avatar answered Oct 18 '22 20:10

Luis Masuelli