I've already read the official Django tutorial and many other questions here on stackoverflow.com, but it seems like there is no real answer to my question or I just don't get it. Unfortunately, I could not find an appropriate tutorial with more than one app.
My problem:
A Django project usually consists of multiple apps. What I don't get is how those apps can work together.
Example:
Let's say we build a news website and this news website has blog posts, polls and a comments area etc. So I think it would make sense to create an app called polls, another app called blog and the app comments.
So, when you browse to url.com/news/5 for example, you'll see the blog post with the id 5. Or when you browse to url.com/polls/2 you'll see the poll with the id 2. Everything ok.
Now, however, I don't want it to be separated. What I don't get is when I want to have those parts of a website on a single webpage (like in most of the websites). That means if I browse to url.com/news/5 it should not only display the news but also the poll (because the poll belongs to this news page thematically) and at the bottom of the page the comments to that article.
How do I structure it and "glue" it together?
Normally, when I browse to url.com/news/5 the defined view function within the blog app is run and provides the HttpResponse. With this solution, however, I cannot have the poll and comments at the same page. I hope it's clear to you what my problem is.
What is "best practice" to display different apps on a single webpage? Or is it done completely different?
I am also very happy if you can give me a link to a real-world example or nice tutorial that covers this issue.
Using Class-based generic views and providing extra context. Here is a link from the documentation:
https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-display/#adding-extra-context
and here is the example code:
from django.views.generic import DetailView
from books.models import Publisher, Book
class PublisherDetail(DetailView):
model = Publisher
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(PublisherDetail, self).get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['book_list'] = Book.objects.all()
return context
As you can see the main model is Publisher and with get_context_data you can add another context: context['book_list'] = Book.objects.all() that retrieves also all books from the database. You can combine multiple models with this.
Related
I am making a website running wagtail as the CMS/backend and use Page for things that are actual web pages on the site. In addition to this I will need an Events section and I am unsure whether to make it as a Wagtail Page or Django models.Model.
The way I would like this to work for the user is to have an Events section in the admin panel using ModelAdmin so that the user can easily find and navigate to all Events, and, for those events to be displayed in various sections of the site - Home Page, Events Page, Article Page for example.
I think using Page for this and requiring the user to navigate to it (Home > Events Listing > Event Detail) each time is rather a waste of time and cumbersome as opposed to having it use ModelAdmin paired with Django models.Model and that being 1 or 2 clicks away.
Reading through my question it's obvious I am leaning towards using Django model for this, so my question is: what is the trade-off between the two? Is there a set use case for using one or the other? Would using one mean having more/less functionality over the other and what would those be?
Note: I know my question is almost identical to Guidelines for using Wagtail Pages or Django models? however it's more focused on ecommerce but most importantly it has no answer.
Use models.Model and register as a snippet because it will give you more flexibility.
As a user mentioned above, using a snippet is a great idea for what you're discussing. It's one click on the admin and they're in the event system. Then, you can just pass that model into the context for a page. Here's an example of doing this in Wagtail. See this example on adding snippets as streamfield if you wanted the customer to be able to place the events manually through the CMS.
I am studying Python and Django, my final goal is to create an administration panel that manages 2 things:
"dynamic article / item" (which can create types of forms to enter).
"dynamic taxonomies / tags" (which can create categories or groupers of the data "of the form type").
I have seen the documentation of DjangoCMS but I cannot find the names of these concepts, could you guide me?
thank you
You can do pretty much whatever you want to do. If you want to add to what a page gives you, extend the page;
http://docs.django-cms.org/en/latest/how_to/extending_page_title.html
I've used this to add images to pages, so you could use it to add tags or anything else you'd like.
Here's an example of attributing a colour to pages;
class PageColourExtension(PageExtension):
"""
Extend the page model with a background image field.
"""
page_colour = models.CharField(
_("Base colour"),
max_length=50,
null=True,
choices=COLOUR_CHOICES,
)
def __unicode__(self):
"""
Identify by the page it is tied to.
#return: page name
#rtype: str
"""
return '%s' % self.extended_object
extension_pool.register(PageColourExtension)
I'm not sure if djanog-cms is the right tool for your task. It's main purpose is to manage hierarchical pages, and the content on these pages. You need to keep in mind that this concept is already there, and cannot be changed, only extended.
For your specific case, I would recommend to create an own Article model, and then use the PlaceholderField, on your article model - it allows really dynamic content to be created, in the same fashion as when used on cms pages. See django-cms placeholder outside the cms docs for how to do that.
If you want to use django-cms and your custom application/article app alongside, you can use an app-hook to embed your urls under a cms page. See docs djanog-cms apphooks
I have built a django website, which requires blog functionality. Rather than roll my own, I have decided to use django-zinnia, to provide blog functionality for my site.
I have managed to change the template to integrate more closely, with the pages on my existing site - however, there are still things I haven't managed yet - to do.
I have come come across zinnia template tags, but they are not giving me the full level of access that I need.
Specifically, I need to do the following:
Access to properties of post (i.e. "entries" in Zinnia lingo) and comments so that I can display the following items on my home page:
Show thumbnails of last N posts (or most popular posts for example)
Show last X comments
Programatically create new posts - and specify the state of the post, i.e. draft/published
Restrict viewing certain posts to authenticated users belonging to a specific django user group.
Am I able to get this tight integration between Zinnia and my django website - or am I better of writing my own blog app, with the requested features?
I am working on my first django project which is also my first backend project. In the tutorials/reading I have completed, I haven't come across passing information back to django without a modelform.
My intention is to calculate a value on a page using javascript and pass it to django when a user hits a submit button on that page. The submit button will also be a link to another page. I know I could process the information in a view via the url if I knew how to pass the information back to django.
I'm aware that django uses MVC and as I have my models and views in place, I am lead to believe that this has something to do with controllers.
Basically, I would like to know how to pass information from a page to django as a user follows a link to another page. I understand that this isn't the place for long step by step tutorials on specific topics but I would appreciate any links to resources on this subject. I don't know what this process is even called so I can't search documentation for it.
EDIT:
From further reading, I think that I want to be using the submit button to GET or POST the value. In this particular case, POST is probably better. Could someone confirm that this is true?
Yes, generally POST is a better way of submitting data than GET. There is a bit of a confusion about terminology in Django. While Django is, indeed MVC, models are models, but views are in fact controllers and views are templates. Since you are going to use AJAX to submit and retrieve the data, you don't care about templates. So what you most likely want is something like this
in your urls.py as part of your urlpatterns variable
url(r'mything/$', MyView.as_view())
in your views.py
from django.views import View
from django.http import HttpResponse
class MyView(View):
def post(self, request):
data = request.POST
... do your thing ...
return HttpResponse(results)
and in your javascript
jQuery.post('/mything/', data, function() { whatever you do here })
There're many ways, you can achieve this in django. Following are the two ways, that I generally prefer :-
1) As a query string parameter in the URL
eg. http://localhost/getPatientInfo?patientId=23&name=Sachin
2) Making URL dynamic, to include the information in the view itself.
eg. http://localhost/patientInfo/23/Sachin
In case 1:-
You will have to do,
patientId = request.GET["patientId"]
name = request.GET["patientName"]
In case 2:
Your URL conf will be something like :
urls = [
url("^patientInfo/(\d+)/([^/]+)$", yourViewFunc)
]
And in your view func :-
def yourViewFunc(request, patientId, patientName):
# your logic goes here
pass
For info. related to URLConf, refer to https://docs.djangoproject.com/en/1.10/topics/http/urls/#example
In trying to save as much time as possible in my development and make as many of my apps as reusable as possible, I have run into a bit of a roadblock. In one site I have a blog app and a news app, which are largely identical, and obviously it would be easier if I could make a single app and extend it where necessary, and then have it function as two separate apps with separate databases, etc.
To clarify, consider the following: hypothetically speaking, I would like to have a single, generic news_content app, containing all the relevant models, views, url structure and templatetags, which I could then include and extend where necessary as many times as I like into a single project.
It breaks down as follows:
news_content/
templatetags/
__init__.py
news_content.py
__init__.py
models.py (defines generic models - news_item, category, etc.)
views.py (generic views for news, archiving, etc.)
urls.py
admin.py
Is there a way to include this app multiple times in a project under various names? I feel like it should be obvious and I'm just not thinking clearly about it. Does anybody have any experience with this?
I'd appreciate any advice people can give. Thank you.
What's the actual difference between blogs and news? Perhaps that difference ought to be part of the blog/news app and you include it just once.
If you have a blog page with blog entries and a news page with news entries and the only difference is a field in the database (kind_of_item = "blog" vs. kind_of_item = "news") then perhaps have you have this.
urls.py
(r'^/(?P<kind>blog)/$', 'view.stuff'),
(r'^/(?P<kind>news)/$', 'view.stuff'),
views.py
def stuff( request, kind ):
content= news_blog.objects.filter( kind=kind )
return render_to_response( kind+"_page", { 'content': content } )
Perhaps you don't need the same app twice, but need to extend the app to handle both use cases.
In this case you could create the common piece of code as a Python module instead of a whole new application.
Then for each instance you would like to use it, create an app and import the bits from that module.
I'm not 100% sure I understand your question, so I'm going to list my understanding, and let me know if it is different from yours.
You want to have a "news" and a "blog" section of your website with identical functionality.
You want to have "news" and "blog" entries stored separately in the database so they don't end up intermingling.
If this is the case, I'd suggest making an API to your views. Something like this:
views.py:
def view_article(request, article_slug,
template_name='view_article.html',
form_class=CommentForm,
model_class=NewsArticle,
success_url=None,
):
urls.py:
(r'^news/(?P<article_slug>[-\w]+)/$', 'view_article', {}, "view_news_article"),
(r'^blog/(?P<article_slug>[-\w]+)/$', 'view_article', {'model_class': BlogArticle}, "view_blog_article"),
This makes your app highly reusable by offering the ability to override the template, form, model, and success_url straight from urls.py.