Django: Does it support changes in DOM? - django

I wonder if Django native support changes in DOM. I don't know if it is correct name for it now so I guess I explain it instead. For example if I make an e-shop site with django. I want when I click on a product it should add to the basket, which is in html maybe looks something like this. So for each product I add a new <li></li> is added dynamically. Can I do that with django. Or do I have to use Javascript for it?
<div id="basket">
<ul>
<li>
// some product
</li>
</ul>
</div>

It depends.
1) You may want to make you app very dynamic, so another element apears in your basket without page reload. This will be done by combining ajax requests (your server needs to know what you have in basket) with DOM manipulation (purely JavaScript);
2) You can use more classical approach. Adding element to basket is just a POST request. Django handles the request (stores in session or somewhere else current basket) and generates new HTML for you.
Imho, the first approach is a way faster and it looks better for the end-user. The downside is that you may loose track of some valuable information which automatically updates when user reloads entire page (like for example the price of an item). But this should not be a problem if we're talking about store. After all how often product data changes?

Django does not natively generate javascript for you. The usual way is to import your javascript into your pages in your templates.

Related

Is it possible to make 'cart' with django Class Based View?

I am trying to make a simple e-commerce website and followed some tutorials.
However, the author of the book used complicated function based view to make cart function..
there are bunch of session stuffs.. and I don't understand the logic..
and I am trying to think the other way..
what about using database to store all the cart related data, and
use CBV to build it?
for example,
CartListView to see the contents of the cart, and CartUpdateView to change the quantity..
then are they going to be two different pages? separated page that user should go to the
different page to change the value??
please help me T T
You can access the session in any sort of CBV as self.request.session and a "shopping cart" is normally stored therein.
You'll certainly need to implement a CartListView to see what's in it, or possibly a CartEditView to show the cart with options to edit the quantities and delete anything that shouldn't be in there.
Adding products to the cart may well be an "Add" button on a ProductDetailView or lots of add buttons in a ProductListView. You might add a POST handler method to these views which are otherwise read-only (GET-only) bt default. Or you might make them FormViews, even though the form would be hidden and filled/POSTed by JS rather than the shopper doing anything other than clicking "add".
And then there will be a CheckoutView.
Check https://djangopackages.org/ (put "cart" in the search box). this will throw up several shopping cart things which might be the code you want, or the source of which might be a valuable learning resource before you end up rolling your own.

Advice on WYSIWYG architecture for an Ember app

I'm having a hard time coming up with a solution for this problem.
I'm building a WYSIWYG designer, for micro sites. The templates for these microsites will be supplied by an intermediate user, and the end-user will manipulate these templates. So, there are really two groups of users of the app: template-buiders, and end-users. Think MailChimp.
This means my Ember app will start off with a template from a template-builder, say
<h1>An awesome product</h1>
<h2 contenteditable="true">Subtitle away</h2>
<p>{{#if optionA}} One thing {{else}} Another thing {{/if}}<p>
and the end user, having chosen this template, will then be able to customize it. There are a few requirements:
There will be static, uneditable portions of the page (h1 above)
There will be static, editable portions of the page (h2 above)
There will be options that affect the layout, style, etc. (p above)
So far, my attempts have lead me to build a handlebars helper that takes a string and a context, and returns a rendered template. This is because the above template will actually be coming over from a database, as a string - remember, it's user-generated.
That means, in my application's template, it would look like
<div class="preview">
{{preview-userTemplate template context}}}
</div>
where
template: '<h1>An awesome product</h1><h2 contenteditable="true">Subtitle away</h2><p>{{#if optionA}} One thing {{else}} Another thing {{/if}}<p>',
context: {optionA: true}
Now, this actually works, in the sense that it will update if context is updated, so I can add controls along the sides for the end-user to manipulate those options. So I have those (more of less) under control.
It's the WYSIWYG content editing that is giving me trouble. In the above template (from my template-builder users), I want them to be able to add contenteditable="true" to places in their templates where the end-users can change the content.
Now, these changes need to be saved. Ideally, I would be able to retrieve the instance view's template back from the DOM, after the inline edits have been made. Is this possible? The original {{data}} placeholder would need to be preserved.
Alternatively, I could make a view/component, so the template-builder would do something like this:
<h1>An awesome product</h1>
{{#editable}}
<h2>Subtitle away</h2>
{{/editable}}
<p>{{#if optionA}} One thing {{else}} Another thing {{/if}}<p>
but this seems like it would require a good deal of finagling to get the edits to stick - I'm not even sure right now how I'd go about it.
What do you guys think? Is there an easier solution that I'm overlooking? Thanks for any pointers!

Creating normal forms in Joomla 2.5

I want to create a simple registration form as one of the pages in my Joomla 2.5 website.
Every where on the internet, I see people asking me to use an extension like proforms, ckforms etc.. Most of the have price tags on them and the free ones do not have database and I don't really want a lot of functionality.
I just want the following code to work. So that I can pull the POST variable and insert them in a db.
<form method="post" action="mycreatedpage.php">
<input type="text"/>
<input type="submit">
</form>
Is this not possible in Joomla 2.5?
After a bit more searching, I realized that what I really needed was an ability to make PHP run inside the article. Thanks to a video.
Answer :
Install Sourcerer to enable PHP inside joomla articles
Create an article which take in the POST variable and insert into the database. This is the tricky part. What I did here was take the general PHP code which I would have written in register_do.php and insert it using the Sourcerer plugin.
Now create an menu Item which points to the above article. Save the menu item and copy the alias. This alias will be the action for the form.
From here on on, everything must work fine.
For more detailed instructions, watch the video
When you post a form, you have to have some code to handle the form input and what to do with it. So your options are to write a component to handle that form input or to use a form component that does it for you. If you write your own there is a lot to consider unless you want to open up gaping security holes in your website.
There are plenty of free forms components available. If you want free, I would recommend Chronoforms, if you don't mind paying small fee then RS Forms.

Can I use something like Hyde from within Django?

I have a site with a few hundred pages where maybe 75% of pages are static content and the rest fit the typical "web application" model. My preference is Django, so I've mostly been looking at solutions based on that.
The content is very bespoke -- most pages share little beyond the basic site chrome, and are complex enough that it's simpler to write them in HTML rather than try to wrangle a rich text editor into giving the correct output. So the direction I'm currently going is to just define the content in templates -- I have a single view and use the incoming path as the template path. This keeps each page on the site as a page in the file system (easy to browse, easy to track in revision control), but lets each page share any number of common elements (headers, footers, navigation) and inject its own data into them as needed.
This gets bogged down in a lot of the details, though. For instance:
Sharing of page data with other pages. For example, the title defined by a page should show up in navigation menus on other pages, etc. I found this question about getting a block value from a template, but this seems really convoluted (and not scalable).
Related issue: if I define something as a block I can only use it once. I've seen the example of {% block title %} -- which typically goes in multiple places in a page -- several times in SO without a great solution.
Multiple/flexible inheritance. For a breadcrumb I might want to inherit from a page's ancestor, but for layout I'd probably want to inherit from something else (eg. a one-column vs two-column base template).
I think these specific issues are solvable on their own, mostly by using includes and custom template tags, but looking down that road I see hacks piled on top of hacks, which I'd like to avoid -- this needs to be a fairly simple and easily grokked system.
In the course of looking into these, I came across Hyde, which seems to address a lot of these issues. In particular, I really like that it has a sense of the site structure, and it gives pages some nice tools to navigate.
But I still have all the dynamic pieces, which really need to fit seamlessly. So anything I do for the content pages should really be available for any template that's part of a dynamic application. Also, one thing I really like about the "each page a template" approach is that I can alter the treatment of any particular page just by adding its path to urls.py and specifying a custom view.
Is there a good solution for this type of use case? More generally, is this just something that Django shouldn't be asked to do? It occurs to me that I'm sort of trying to use the file system as a CMS database here, which seems likely to lead to scaling problems, but Django seems to process and cache template content pretty well, and after looking at some existing CMS solutions (django-cms, feincms, fiber) I really don't like the idea of having one solution for static content and a totally different one for interactive content.
Edit
Here's what I got using custom tags to handle page metadata/configuration:
A dictionary for page data is passed in at the top level (so that a tag can write into it and then code higher in the stack can read it back)
A custom data tag allows pages to write data into this page data
Other custom tags read and render structures (navigation, breadcrumbs, etc) from the data
The main piece is a tag that will read data (written as JSON) into the global dict:
class PageInfoNode(Node):
def __init__(self, page_info):
self.title = page_info['title']
self.breadcrumb_title = page_info.get('breadcrumb_title', self.title)
self.show_breadcrumb = page_info.get('show_breadcrumb', False)
self.nav_title = page_info.get('nav_title', self.breadcrumb_title)
self.side_nav = page_info.get('side_nav', None)
def render(self, context):
# 'page_info' must be set someplace higher in the context stack
page_info = context['page_info']
page_info['title'] = self.title
page_info['nav_title'] = self.nav_title
if self.show_breadcrumb:
if 'breadcrumb' in page_info:
page_info['breadcrumb'] = [self.breadcrumb_title] + page_info['breadcrumb']
else:
page_info['breadcrumb'] = [self.breadcrumb_title]
if self.side_nav != None:
page_info['side_nav'] = self.side_nav
return ''
#register.tag
def pageinfo(parser, token):
nodelist = parser.parse(('endpageinfo',))
parser.delete_first_token()
return PageInfoNode(json.loads(nodelist.render(Context())))
Each page sets its data like:
{% block data %}
{{ block.super }}
{% load my_page_tags %}
{% pageinfo %}
{
"title": "My Page Title",
"show_breadcrumb": true,
"side_nav": ["/section1/page.html", "/section2/page.html"]
}
{% endpageinfo %}
{% endblock data %}
This works, but it seems really opaque and fragile:
The global dict needs to be added somehow -- right now I do it in the view, but I guess a custom context processor would be better
This needs to be in an inherited block so that it will actually render
Because we sometimes need the super's data (eg. for breadcrumbs) it needs to call {{ block.super }} but it needs to be in the right order to keep the super's data from overwriting the target page's data.
I just feel like I'm working against the way Django wants to operate, and I was hoping that there was some better way of handling this sort of thing that I was missing.
Stop creating data in your templates. Create it in your views, pass it to your templates. For example, with breadcrumbs, there is no reason whatsoever that the code to add to breadcrumb trails has to live in the template. It could live in a view, or even better, be a context processor.
One solution is to go with a Static site + services model. You use hyde to generate the static site but have your dynamic content dealt with using javascript on the client site and nice REST API on your server.

Is it possible, in a django template, to check if an object is contained in a list

I'm very new to django, about a week into it.
I'm making a site where users enter stuff, then other users can vote on whether they like the stuff or not. I know it's not so novel, but it's a good project to learn a bunch of tools.
I have a many-to-many table for storing who likes or dislikes what. Before I render the page, I pull out all the likes and dislikes for the current user, along with the stuff I'm going to show on the page.
When I render the page, I go through the list of stuff I'm going to show and print them out one at a time. I want to show the user which stuff they liked, and which they didn't.
So in my django template, I have an object called entry. I also have two lists of objects called likes and dislikes. Is there any way to determine if entry is a member of either list, inside my django template.
I think what I'm looking for is a filter where I can say something like
{% if entry|in:likes %}
or
{% if likes|contains:entry %}
I know I could add a method to my model and check for each entry individually, but that seems like it would be database intensive.
Is there a better way to think about this problem?
If you're using latest django version, then it's just
{% if entry in likes %}
Refer django docs
Go here. Very similar to what they're using on trunk. "Save this as smart_if.py in the templatetags folder of one of your apps. Then a simple {% load smart_if %} replaces the boring built-in Django {% if %} template with the new smart one."
If you're not running trunk one of the following should work:
Filter:
Replacement "if" tag, largely the basis for the new functionality in the upcoming 1.2 release: