This is a more-general question – just hoping to find someone who already knows.
("To save my forehead," y'know.) ;-)
I want to use CKEditor in conjunction with Machina forums, and I specifically want to be able to "drag and drop" images. I've found the right CKEditor feature to do that, but I'm getting "Incorrect Server Response" messages from CKEditor when I try to accomplish the drop. (This also happens on my development box.)
(Note that my concern is quite-particular to Django ("django-ckeditor"), and to the Machina forum software ("django-machina"). I need answers that are very tightly focused upon this use-case.)
So is there anyone out there who might say – "oh yeah, that happened to me, too, and the way to fix it is ...?"
Well, what do you know? I figured it out.
The problem was – and, as the django-ckeditor documentation clearly states, the default urlpattern entries (in the include file) specify a "staff-only" decorator for uploads. So, ckeditor was getting an error-message response and of course it didn't know what to do.
To solve the problem:
First, of course, be sure that ckeditor_uploader (as well as ckeditor) is installed on your system and is in your INSTALLED_APPS list in settings.py.
Now, in your urls.py, first add this line near the top:
from ckeditor_uploader import views as uploader_views
Next, insert the urlpattern entries that you find in the package's urls.py file, but referencing the uploader_viewsalias, viz:
url(r'^ckeditor/upload/',
uploader_views.upload, name='ckeditor_upload'),
url(r'^ckeditor/browse/',
never_cache(uploader_views.browse), name='ckeditor_browse'),
If you erroneously attempt to specify ckeditor_uploader.views. in the url() entry, you will be rewarded with:
NameError: name 'ckeditor_uploader' is not defined
Now you know! :-)
Also, don't forget what the Machina documentation told you to remember: ;-)
MACHINA_MARKUP_WIDGET = 'ckeditor_uploader.widgets.CKEditorUploadingWidget'
If you're doing "drag and drop," you're necessarily doing "file uploads," so you must use the provided field-types or (equivalently ...) the provided widgets from the ckeditor_uploader app.
Related
I was following Django tutorial, and got stuck where it asked me to replace the default template for administrative part of the site with my own. The problem was a typo in the template's name. I suspected there must be a problem like that, but to troubleshoot the problem it'd be very helpful to see some kind of report from Django on what template it used to render a particular page. Is there any way to do this?
First if you have set DEBUG = True django automatically gives you information about where django was looking for templates (in general and especially in case it didn't find one)
You should see something like this:
second you can add the popular django plugin django-debug-toolbar. It can show you for each request what templates were used and what their context was.
see: https://django-debug-toolbar.readthedocs.io/en/stable/panels.html#template
Still, not exactly the answer, but something to get me closer. One could start Django shell, and then try this:
>>> from django.template.loader import get_template
>>> get_template('template/name').origin.name
to find out what template was actually used. This is still not enough to see though which templates were considered while resolving the template.
Django official documentation and other tutorials on the web always use a trailing slash at the end of url. ex:
url(r'^accounts/login/', views.login) # login view in turn calls login.html
# instead of
url(r'^accounts/login', views.login)
Since accounts is the directory and login (login.html) is the file, shouldn't we be using second url? This will also make GET parameters look more structured:
accounts/login?name='abc' # login is a file that is accepting parameters
vs.
accounts/login/?name='abc' # login directory (maybe index) is accepting parameters??
One of Django’s core design philosophies is URLs should be beautiful.
So some url like accounts/detail?name='abc' should be mapped as accounts/detail/abc/. You can capture it using regex at your url configurations. Here the URL is pretty neat and user friendly. This will help the search engines to index your pages correctly (now you can forget about rel=canonical) and will help in seo.
Now the reason for a trailing slash, consider a view (in any framework) which relatively resolves about.html for a user at path, users/awesomeUser
since users/awesomeUser and users/awesomeUser/ are different,
If the user is at users/awesomeUser, the browser will resolve it as users/about.html because there ain't a trailing slash which we don't want
If the user is at users/awesomeUser/, the browser will resolve it as users/awesomeUser/about.html because there is a trailing slash
child relative to family/parent/ is family/parent/child.
child relative to family/parent is family/child.
Django Design philosophy on Definitive URLs reads,
Technically, foo.com/bar and foo.com/bar/ are two different URLs, and search-engine robots (and some Web traffic-analyzing tools) would treat them as separate pages. Django should make an effort to “normalize” URLs so that search-engine robots don’t get confused.
This is the reasoning behind the APPEND_SLASH setting. (APPEND_SLASH lets you force append slashes to a URL)
Still not convinced?
Since django observes both the urls as different, if you are caching your app, Django will keep two copies for same page at user/awesomeUser and user/awesomeUser/.
You gotta have issues with HTTP methods other than GET if you don't append slash to a URL (If you ever plan to build a REST API).
Update
You can't make POST/PUT/PATCH/DELETE methods to work with rest_framework unless you explicitly define APPEND_SLASH=False in settings and trailing_slash=False for each and every router you gotta use(if you use Routers). It is like you basically gonna skip this most times and you gotta waste a hell lot of time debugging this. Django recommends append slashes and doesn't force it.
Its up to the developer to append slashes or not.
From the docs for the middleware that uses APPEND_SLASH
a search-engine indexer would treat them as separate URLs – so it’s best practice to normalize URLs.
Its not required by django, its just trying to help your SEO by suggesting a standard way of doing urls.
Yes, I know that the slash has nothing to do with this middleware but this is the best explanation I could find as to a possible reason
This helps define the structure of your website. Although django can support anything entered after the domain that is passed to the server doing it in this way allows you to easily add "subpages" to the url without it looking like accounts/loginreset?id=alkfjahgouasfjvn25jk1k25
That being said in the case above it may make sense to leave it out.
"URLs should be beautiful"!!!
I want to be able to control URLs. It's nothing nice when everything is about to be overwritten. Under circumstances, I make a redirect loop which is not funny.
from django.http import HttpResponseRedirect as rdrct
url(r'^sitemap.xml$', 'my_app.views.custom_sm'),
url(r'^sitemap.xml/$', lambda x: rdrct('/sitemap.xml')),
Usually I have the opposite problem, Django can't find the templates.
Lastly, I change a template of mine called custmber_view.html, but Django didn't notice the chagnes.
I tried flushing all caches, without success. In my dispair, I completely removed the template
hoping to see the familiar TemplateDoesNotExist exception.
To my surprise, Django keeps rendering the template! Although it is not found on the hard-drive.
Can someone suggest a solution to this mystery?
ARGH, legacy projects, I am doomed to fix them for ever. Somewise guy put the following in settings.py:
TEMPLATE_DIRS = (
os.path.join(project_dir, u'templates'),
u'/var/www/venv2.7/lib/python2.7/site-packages/backoffice/templates',
)
I feel like this now ...
So, conclusion, If you are working on a project which was not made as a Django App, always make sure you read the variable TEMPLATE_DIRS.
But for your colleagues future (and for better moral) always follow How to write reusable Django app
I'm a beginner to Python and Django.
When starting a new project what do you do first before diving into the code?
For example, one could take the following steps:
Configure the settings.py file first
Configure models.py to lay out data structure
Create template files
Define the views/pages
Syncdb
etc
So my question is, what is a good workflow to get through the required steps for a Django application? This also serves as a checklist of things to do. In the definitive guide to Django, the author talks about approaching top down or bottom up. Can anyone expand further on this and perhaps share their process?
Thanks.
Follow the Agile approach. Finish one small case, from the start to the end. From the models to the tests to user experience. Then build on it. Iterate.
Thats the right way to software development.
To do it efficiently, you need: (don't bother right away, you will need it.)
Automated schema migration, automated build system, auto updating and deployment. - None of these, django has got anything to do with. Use pip, fabric, hudson, twill and south appropriately.
Take care not to over burden yourself with all these right away, particularly since you say, you are beginning.
the required steps for a Django application?
There are two required steps.
Write the settings. Write the urls.py
The rest of the steps are optional.
This also serves as a checklist of things to do.
Bad policy. You don't need a checklist of Django features. You need a collection of use cases or user stories which you must implement.
For some reason, you've omitted the two most important and valuable features of Django. Configure the default admin interface and write unit tests. The default admin interface is very high value. Unit testing is absolutely central.
You do it like this.
Gather use cases.
Prioritize the use cases.
Define the actors. The classes of actors becomes groups in the security model.
Define enough "applications" to satisfy the first release of use cases. Define the url structure. Cool URL's don't change.
Build the first use case: models (including security), admin, urls, tests, forms, views and templates. Note that these are the file names (models.py, admin.py, ...) except for templates. Also note that forms and admin should be defined in separate modules even though this isn't required. Also note that templates will be split between a generic templates directory for top-level stuff and application-specific templates.
Build the second use case: models (including security), admin, urls, tests, forms, views and templates.
...
n. Package for release. Tweak up the settings. Configure database and mod-wsgi
I personally can't make a template without writing the views (unless it's a photoshop draft) but in general that's the way I go after I have a plan.
What's extremely important for me is that I don't dive head-first into the code, and that I spend time mocking up the model structure based on the "screens" or "pages" that the user will see.
Once I have a user experience defined, I make sure the backend is robust enough to handle that experience. If I don't visualize the user experience, details get left out that are certainly accomplishable in the shell but not ideal for the website, default django admin, etc.
There are always tradeoffs between agile development and a huge spec: I think there's an important balance. Agile is good: there's no point planning every detail before writing your first line of code, as your needs will change by the time you get to the end. You don't know how your users will really use the site.
On the other hand, without a plan, you can end up with a messy foundation that affects all future code.
An educated guess is a good start. Don't think or assume too much, but definitely have a clear idea how your users will interact with your site for stage 1.
Always try to remember about a DRY rule. For example, why to write RequestContext every new view is defined, where you can simply write a function once, which will add it for you. Good description is here in another topic.
Try to keep a code written one way. Each time you upgrade a schema of your view, edit it in all already written views. That will help keep your code clear and save a lot time for you in future.
Generally good rule, and how do I write my applications is the rule of small steps. Start with writing a settings and urls, then add one model and one view. When it works, modify - add another models or another views. You won't even notice, when your project becomes bigger and bigger.
And the last useful rule for clarity of all the source. Keep files in folders. If you have two subsites based one one (for example "accounts" and "blogs") create two directories names the same. Remeber to put init.py file in each directory. It's really easy to forget. With this practice it's easy to write models and views dedicated to each category. By the way it's a good practice to keep urls like in a tree structure. Main urls.py should contain only links like this one:
(r'^accounts/', include('your_main_name.accounts.urls')),
and of course all media, static, css and so on. In accounts directory urls keep:
urlpatterns = patterns('your_main_name.accounts.views',
url(r'^$', 'index', name='index'),
)
with all views subdirectories.
Last one - keep code clear with actuall django version. Remeber, that the 3.0 release is comming soon.
Hope this will help.
I find that my process varies depending on a lot of variables, mainly whether I know something will work or if I'm experimenting and also whether I'm developing on my production server or in a development environment.
For example, I often do my development directly on the deployment server (most of my work is for intranet projects so there isn't any security risk, etc). But when I do this I really need to make sure the settings and urls are setup first and that gunicorn and nginx are configured.
If I know something should work, or am setting up a generic base set of code, sometimes I'll do all that coding for views and models before I even get enough setup to even run the development server. But when experimenting with new code I find it's good to be able to test every step of the way, so in that case you need your servers running.
In general I do settings, models, syncdb, views, urls, templates, collectstatic, graphics/aesthetics
In general I leave my base.html very plain until the everything else is working, then I add css/js etc.
I guess my point here is that there isn't really a wrong answer for how you do it, and there isn't even only one best practice (as far as I'm concerned). When you do more work, you'll find what you are comfortable with and it'll even vary from project to project.
Good luck, hopefully you learn to love django!
here is something I do in general,
configure basic settings
configure root url.py
configure settings, url.py for static (media) files
create model
sync db
write views (use simple template, if needed)
once you are done with back end implementation
think about UI
prepare styles, scripts
start working on template implementation
We recently launched a new Django-powered website, and we are experiencing the oddest bug:
The site is running under Apache with mod_fastcgi. Everything works fine for a while, and then the URL tag and reverse() functionality stops working. Instead of returning the expected URL, they return "".
We haven't noticed anything in Apache's log file; there are no errors being generated by Django. And (the kicker) the problem only occurs in production mode; we can't reproduce it when DEBUG=True.
Any thoughts on where we should be looking for the problem?
Update: It turned out to be a problem with settings.LANGUAGES, although we haven't determined exactly why that broke things.
This has happened to me before. Normally it's due to a 'broken' urls.py file. There are two things that make this kind of bug really hard to fix:
It could be the urls.py file in any of the apps that breaks the reverse() function, so knowing that reverse() breaks for app X doesn't mean the error is in that particular application's urls.py.
Django won't even notify you of errors in the urls.py file, unless you somehow manage to crash the site by doing something really, really nasty in the urls.py file.
Debugging: The way I go around fixing this is by manually disabling all applications (just comment out their line in INSTALLED_APPS) and checking reverse() works. If it still works, then I enable the next app, until it breaks. I know, very rudimentary stuff, but it works :)
Django has a odd behaviour when matching urls in a environment that isn't under debug mode.
For example, with DEBUG=False, Django will ignore urls such as:
url(r'^', include('someapp.urls')),
specifically in the case above, you could let the string empty:
url(r'', include('someapp.urls')),
In other words, check your regexes.
Can you put your urls.py here to be analyzed?