I'm new to Django and trying to understand the "correct" way to structure my project, in particular when and how to put separate functionality within an application.
The site I am building will include mainly static information (it's for a holiday cottage) which I'm providing with views from the main site project. I also want to include a calender, which will display availability in a sidebar, which I have started to build as an application "availabilityCalender" as it will be reused across most pages and I can see me using it in other projects.
What I can't figure out is how to hook this into a page view from my application. Most tutorials online approach applications as representing the entire page and link into a view from the urls.py of the project. Instead I'm want to add the application as a part of my page. The simplest way to represent what I'm trying to do is below:
from django.shortcuts import render
from django.http import HttpResponse
import availabilityCalender
def index(request):
availabilityCalender.views.monthView()
I was hoping that this would simply add the application's view into the index view. When testing this I get the error "errorAttributeError at /, 'module' object has no attribute 'views'".
Am I trying to use applications is a way the are not designed for or simply using the wrong approach? My apologies for what is almost certainly an incredibly simple question!
Edit -
I got the above code to work by changing my import:
from availabilityCalender.views import monthView
def index(request):
return monthView(request)
One way to do this would be to use template inheritance. Each one of your templates could extended a base template that includes your calendar.
Another way would be to put your calendar in its own template and to use the {% include %} template tag.
If your calendar has data associated with it, the next issue would be getting that data to the templates. If you are including the calendar on every page of your site you could create a custom context processor that automatically adds the calendar data to every request.
If the calendar is only on some pages you could just load the data on a view by view basis. Perhaps you could extract the calendar functionality into a CalendarMixin view that loads the correct calendar data in get_context_data.
first of all your project should have a structure similar to this:
-/myProject
-/myproject
-settinngs.py
-views.py
-urls.py
-/templates
-mange.py
-/availabilityCalender
-models.py
-views.py
Now you need to make sure you add to your settings INSTALLED_APPS the app "myproject.availabilityCalender", Once this is done its quite simple to use and reuse your app in all project and further apps. In this specific case if you want to import and use your app on the myproject/views.py, just do:
from myproject.availabilityCalender.models import <--MODULES YOU NEED FOR YOUR VIEW-->
def monthView(request):
.
.
.
return render(request, 'index.html')
Related
I'm building a website using django-all auth for it's authentication and social authentication functions. The forms that come bundled with the app are hardly great to look at and hence I decided to create my own views.
The problem is: How do I create them while ensuring that the backend of Django all auth is still available to me? I've dug into the source code and found that it uses class based views for rendering and performing CRUD operations.
I want to know if I can subclass those views in my own app/views.py and just change their template_name field to my own templates. Any advice would be most helpful.
Thanks.
You can of course subclass the views, as long as you change your URLs to point to the overridden versions. However, there is no need to do this just to use your own templates; Django's template loader is specifically written with this use case in mind. Simply create your own directory inside your templates folder to match the one allauth is using, and create your own template files inside it; Django will find yours first and use them.
I followed all 42 tutorials on the Try Django Youtube channel, and I'm trying to customize that project to make my own custom app.
My web app only needs two pages for now. One for users (which I only create in the admin) to log in, and another page to use the app. I'm trying to get the hang of the Django dev steps. Correct me if I'm wrong, so if I want to make a single page in a Django web app, I need to set it up in my urls.py, views.py, and make a template html file for it, right?
If I'm getting this order wrong or leaving anything out, any help or advice is appreciated. Can this pattern be found on Django documentation website, too?
Django based on MTV (model, view, template) pattern. More about it here http://aijogja.pythonblogs.com/251_aijogja/archive/1433_django_tutorial-create_a_blog-part_6__mvt_model_view_template_section_1-homepage.html
For adding another page, setup route in urls.py (write regexp), add function in views.py (must return httpresponse) and create template.html
Ok so I am new to Django but not to the MVC world (built a few apps in Grails)...but I seem to be having the same issue as a bunch of people and I am hoping someone can shed some real light on Django's Class based generic views. In the Grails world "templates" or generic views CAN BE generated by the framework and I believe the same thing is true regarding Django but if you follow the 1.7 "Writing your first django app" there seems to be some special magic missing.
I have the following project/app structure:
mysite
->mysite
->settings.py
->urls.py
->_init_.py
->wsgi.py
->polls (my app)
->models.py
->urls.py
->views.py
->templates
->polls
In the tutorial we are asked to created an index.html, details.html, results.html file in the templates->polls directory and we have some simply HTML views within those files. That all works great. Once I get to "Use generic views: Less code is better" in the tutorial is where I get into trouble. Am I wrong in assuming I should simply REMOVE the index.html, details.html, results.html files from the templates folder AND that Django should be generating views on the fly? I assumed that was the point of the generic views but now I am not sure. When I do remove the views I get a templatedoesnotexist error. Do I need to do something to my settings.py to let it know that I want to look to django to generate the views? The following is the standard generated settings (which is what I have) and I assume that should be sufficient to perform default behaviors?
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DEBUG = True
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates/'),]
If you need more from me let me know, but basically I am wondering if I am way off on assuming Django generates the views from a template or not? Thank you!
You're just a bit confused about Django's terminology. Almost all views use a template to render the actual markup (HTML, XML, whatever) that is sent back to the browser.
A Django Generic View is just a Class based version of writing your own functional view. So instead of something like:
def show_template_with_data(request):
template = "myapp/show_data.html"
return render(request, template, {'data1': 1, 'data2': 2})
you would use Python classes and OO and do:
class ShowTemplateWithData(TemplateView):
template_name = "myapp/show_data.html"
def get_context_data(self, **kwargs):
context = super(ShowTemplateWithData, self).get_context_data(**kwargs)
context['data1'] = 1
context['data2'] = 2
return context
These two are equivalent one is just using functions and the other Class Based Views.
In Django, views are the code that determines what action is taken, what data is given to the template (for example based on logged in user), etc. a "template" is just the HTML with placeholders/loops/etc that displays it.
But no, you shouldn't be deleting the template HTML files, both styles of views will need them.
I'm doing a website for my school in Django. The blog part is almost ready, but on every page I want to have a sidebar with planned changes in the timetable (i.e. when a teacher is ill and classes will have lessons with another teachers in another classrooms). What would be the best way to implement that? I've heard about templatetags, RequestContext and other things like that. That is my first Django project and I'm learning new things every day.
Now I have one app in the project which is called blog (it's models are: Posts, Categories and Pages; Page is like a flatpage but it is assigned to a category by a ForeignKey). In project's urls.py every request (beside /admin) is forwarded to blog.urls where the further actions are taken (choosing the appropriate view class). Views are written using generic views and class inheritance. There are: PostListView, PostView, PageView. The PageListView is unneeded because user is able to choose Page from the main navbar.
The 'changes sidebar' should allow the user to choose a date and reload itself without reloading the whole page.
I would be really grateful if someone could help me with an idea on implementing it. If you have any questions - ask.
The 'changes sidebar' should allow the user to choose a date and
reload itself without reloading the whole page.
Ok, so you need AJAX for this part. For more complex projects you can use django-rest-framework or tastypie but for this I reccomend to do an AJAX function that gets a date as parameter and return a rendered template. See this thread and this one too
To include the sidebar, I'll just create a separate template for it and include {% include 'changes_sidebar.html' %} you also need to include the javascript to do the ajax requests.
Basically I have a base template, and the base template is including another template, let's say, latest update. So the structure is like this:
-base.html
|---------latest_update.html
So, I know how to include a simple template, like the template without any data processing (doesn't require interaction with any application view.py). However, how could I attach the included template into a django application view.py so that I could at least show updated data periodically?
I am not exactly sure terms for this, feel free to change the title.
Edit: This question is a bit cloudy, as I don't know how to put the terminology correctly. So, I have this included template. Every page will have it. So, from my limited knowledge, that means I have to render it manually for every page that hits view.py. Is there any easier way of doing this?
You can use Django templatetags. Define a file named latest_update_tags under your Django app templatetags directory and write code like this to define a latest_update templatetags:
from django import template
from app.models import UpdateObject
register = template.Library()
#register.inclusion_tag("latest_update.html")
def latest_update():
update_objects = UpdateObject.all().[:10]
return {"update_objects": update_objects}
And then in your base.html use it like this:
{% load latest_update_tags %}
......
{% latest_update %}