Note that there are some explanatory texts on larger screens.

plurals
  1. POKeep code from running during syncdb
    primarykey
    data
    text
    <p>I have some code that throws causes syncdb to throw an error (because it tries to access the model before the tables are created).</p> <p>Is there a way to keep the code from running on syncdb? something like:</p> <pre><code>if not syncdb: run_some_code() </code></pre> <p>Thanks :)</p> <p><del><strong>edit</strong>: PS - I thought about using the post_init signal... for the code that accesses the db, is that a good idea?</del></p> <h2>More info</h2> <p>Here is some more info as requested :)</p> <p>I've run into this a couple times, for instance... I was hacking on django-cron and determined it necessary to make sure there are not existing jobs when you load django (because it searches all the installed apps for jobs and adds them on load anyway).</p> <p>So I added the following code to the top of the <code>__init__.py</code> file:</p> <pre><code>import sqlite3 try: # Delete all the old jobs from the database so they don't interfere with this instance of django oldJobs = models.Job.objects.all() for oldJob in oldJobs: oldJob.delete() except sqlite3.OperationalError: # When you do syncdb for the first time, the table isn't # there yet and throws a nasty error... until now pass </code></pre> <p>For obvious reasons this is crap. it's tied to sqlite and I'm there are better places to put this code (this is just how I happened upon the issue) but it works.</p> <p>As you can see the error you get is Operational Error (in sqlite) and the stack trace says something along the lines of "table django_cron_job not found"</p> <h1>Solution</h1> <p>In the end, the goal was to <strong>run some code before any pages were loaded</strong>.</p> <p>This can be accomplished by executing it in the urls.py file, since it has to be imported before a page can be served (obviously).</p> <p>And I was able to remove that ugly try/except block :) Thank god (and S. Lott)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload