Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
porksmash
Sep 30, 2008
Label is the name of the field, help text is generally more verbose on how to use the field. Like for a create password field, the label would be 'New Password' and the help text might be '8 characters or more, requires at least one number and special character'

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
https://github.com/defrex/django-after-response/issues/6

I am so confused...why can't pip find version 0.2.2 of this module? PyPi page lists 0.2.2: https://pypi.python.org/pypi/django-after-response

Dominoes
Sep 20, 2007

porksmash posted:

Label is the name of the field, help text is generally more verbose on how to use the field. Like for a create password field, the label would be 'New Password' and the help text might be '8 characters or more, requires at least one number and special character'
Thanks

Eleeleth
Jun 21, 2009

Damn, that is one suave eel.

fletcher posted:

https://github.com/defrex/django-after-response/issues/6

I am so confused...why can't pip find version 0.2.2 of this module? PyPi page lists 0.2.2: https://pypi.python.org/pypi/django-after-response

There's no file associated with the 0.2.2 tag on pypi. If you check the previous version: https://pypi.python.org/pypi/django-after-response/0.2.1 you can see the tar.gz file to download. The current version doesn't have that. I'd reckon the package maintainer screwed up the deploy to pypi somehow?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
My head, it explodes!

Python code:
class County(models.Model):
    """ Class that defines a United States county"""
    name = models.CharField(max_length=255)
    geoid = models.CharField(max_length=8)
    state = models.CharField(max_length=3)
    adjacent = models.ManyToManyField('self')
I add a bunch of counties, all is wonderful! Now, let's try and add some relationships!

Python code:
existing = County.objects.get(geoid=a_geoid)
# I can print this, it's found, so good!
# adjacent_geoids is a list of geoids that are adjacent to 'existing'
buddies = County.objects.filter(geoid__in=adjacent_geoids)
# I can print buddies, and get back the counties I expect!
existing.adjacent.add(buddies)
# I have also done: existing.adjacent.add(*buddies)
# and trying to add via pk as well...
That should work, right? It does not:

code:
  File ".../python2.7/site-packages/django/db/models/fields/related.py", line 110, in related_model
    apps.check_models_ready()
  File ".../python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Is there something special I need to do because the relationship is self-referential? Am I doing something impossibly dumb?

EDIT as per usual, I figured it out literally seconds after I posted...

I needed to add this to my script, which I didn't have to when creating models....

code:
import django
django.setup()

Lumpy fucked around with this message at 19:39 on Nov 3, 2015

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I don't use the django admin too much other than just using the most basic functionality. Today, I was wanting to add the ability to add objects on the reverse side of a ManyToManyField. That's not what this post is about, though...I solved that problem. I was amused to find a django ticket that was submitted 10 years ago, has had continual activity in the meantime, and is as of yet not fixed.

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord

Thermopyle posted:

I don't use the django admin too much other than just using the most basic functionality. Today, I was wanting to add the ability to add objects on the reverse side of a ManyToManyField. That's not what this post is about, though...I solved that problem. I was amused to find a django ticket that was submitted 10 years ago, has had continual activity in the meantime, and is as of yet not fixed.

I found that like 3 months ago (same problem) and also laughed at it.

Data Graham
Dec 28, 2009

📈📊🍪😋



God dammit. It's those kinds of things that made me want to dig in my heels on modern tools and resist Java.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've got a custom django admin command and I want to capture the log output for when that command is run and make it available for download in a separate file. Think "Console Output" in Jenkins. This command is invoked using django-after-response and I'm running uWSGI.

At the beginning of the admin command, I do this:
code:
deploy_log = NamedTemporaryFile()
formatter = logging.Formatter("%(asctime)-15s %(levelname)-8s %(message)s")
file_handler = logging.FileHandler(deploy_log.name)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
logging.getLogger('').addHandler(file_handler)
Then at the end of the admin command:
code:
logging.getLogger('').removeHandler(file_handler)
The problem I'm running into is that when there are multiple 'deploys' running simultaneously, the deploy_log for one thread will have entries from other threads. How do I avoid this?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

fletcher posted:

I've got a custom django admin command and I want to capture the log output for when that command is run and make it available for download in a separate file. Think "Console Output" in Jenkins. This command is invoked using django-after-response and I'm running uWSGI.

At the beginning of the admin command, I do this:
code:
deploy_log = NamedTemporaryFile()
formatter = logging.Formatter("%(asctime)-15s %(levelname)-8s %(message)s")
file_handler = logging.FileHandler(deploy_log.name)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
logging.getLogger('').addHandler(file_handler)
Then at the end of the admin command:
code:
logging.getLogger('').removeHandler(file_handler)
The problem I'm running into is that when there are multiple 'deploys' running simultaneously, the deploy_log for one thread will have entries from other threads. How do I avoid this?

I don't know the answer, but it feels like this is a question about the logging module and threading and not Django.

And my gut tells me that its too specialized of a question to get much traction in the Python thread and you'll probably have to ask on StackOverflow.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Thermopyle posted:

I don't know the answer, but it feels like this is a question about the logging module and threading and not Django.

And my gut tells me that its too specialized of a question to get much traction in the Python thread and you'll probably have to ask on StackOverflow.

Roger that. Thank you!

edit: posted it here http://stackoverflow.com/questions/33905999/to-to-prevent-filehandler-logger-from-impacting-other-threads

fletcher fucked around with this message at 00:48 on Nov 25, 2015

Dominoes
Sep 20, 2007

I'm looking for help with forms. It's easy to find instructions on making HTML/js forms, and using Bootstrap etc to make them look nice. I'm having trouble integrating this with Django . I'm using Crispy forms, and am trying to make a search bar with a clickable submit button with a mag-glass icon. Here's the code I'm using to make what I describe, but without the button being clickable; submit works only with enter button:

Python code:
    def __init__(self, *args, **kwargs):
        super(TripForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.layout = Layout(
            AppendedText('cities', '<i class="fa fa-search"></i>',
                         placeholder='search for [s]stuff[/s]'),
        )
How can I turn appended text icon into a submit button? I could use this example code on Bootstrap's site to make it call a JS function, but I don't know how to integrate that with Django.

Dominoes fucked around with this message at 21:48 on Dec 1, 2015

porksmash
Sep 30, 2008
You should use the FieldWithButtons layout object instead:

code:
Layout(
    FieldWithButtons('cities', Submit('search', '<i class="fa fa-search"></i>')),
)

Dominoes
Sep 20, 2007

Thanks. Do you know if there's a way to make FieldWithButtons work with the icon (seems to only work with text), and placeholder text? The documentation only references it via one example, and with only the button text and name.

porksmash
Sep 30, 2008
Oh yeah, crispy renders submit buttons as Inputs by default so you can't use HTML in them. Try replacing the Submit() layout object with this to force it to be an actual button:

code:
StrictButton('<i class="fa fa-search"></i> Search', type='submit', name='Submit', value='submit'),

Data Graham
Dec 28, 2009

📈📊🍪😋



What's the best-practice way of handling sensitive data strings in server configs (like database passwords) that you don't want to publish to version control? I want to store my secrets a) securely, b) privately, and c) only in a single location, such that both the web server and manage.py can use them.

Talking in particular of Apache/wsgi, though I imagine pretty much every server would have similar issues.

I thought I was onto something by using a db.cnf file in DATABASES['default']['OPTIONS']['read_default_file'] -- just put the password in that and chown it 600 -- but then Apache can't read it.

I had to go back to my previous best solution, which is to store sensitive strings in the Apache configuration itself (chmod 600), and pass them in via wsgi.py hackery:

httpd-vhosts.conf
code:
    SetEnv SECRET_KEY (u+6(^0^o!317$!l33aweG23$)au=fqm-l3a)*eg(!!y2f)k#is
    SetEnv DB_PASS BlahPassword
wsgi.py
code:
#application = get_wsgi_application()

env_variables_to_pass = ['SECRET_KEY', 'DB_PASS']
def application(environ, start_response):
    for var in env_variables_to_pass:
        os.environ[var] = environ.get(var, '')
    return get_wsgi_application()(environ, start_response)
And then in settings.py I can pull the strings with os.environ['DB_PASS'] and so on.

But the downside to this is that while it sets the environment variables properly for wsgi, it doesn't help me with manage.py. I can put an export DB_PASS="BlahPassword" into my virtualenv activate script, but that means I'm keeping the pw in two places, which sucks.

I thought of parsing the httpd-vhosts.conf in the activate script, but a) it's bash and b) even the python options for parsing Apache config files are either "use some dude's script from 2008" or "do it myself".

I've now been through at least three recent jobs at high-flying tech companies where the codebase either doesn't give two shits about storing the passwords directly in settings.py, or else they apparently run totally password-less and just rely on firewall rules for security or something.

This can't really be the state of things in tyool 2015, can it?

Data Graham fucked around with this message at 16:46 on Dec 7, 2015

Dominoes
Sep 20, 2007

I'm curious too. I've been making a file called private.py that I put on gitignore. I use an if/else statement based on a server environment var in settings.py to prevent an import error when deployed. It seems like an awkward solution.

porksmash
Sep 30, 2008
You can just make a separate file with your sensitive stuff and import * it in settings.py. Don't commit that file to your repo and you're good.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I think I'm just missing something here, because my question is...why does your web server need to know your database connection information?

I mean, I usually just set the enviornment variables on the server and read them in my django settings and that works...

Data Graham
Dec 28, 2009

📈📊🍪😋



porksmash posted:

You can just make a separate file with your sensitive stuff and import * it in settings.py. Don't commit that file to your repo and you're good.

Unfortunately that doesn't work if it's owned by root and chmod 600.

I can chown it www or chmod it 644 so Apache can see it, but then it's also visible to any other programs on the server that want to try to read it.

I suppose one answer to this is "don't run a server with ~users and critical data at the same time", and maybe that's a fair stance to take nowadays, but I feel like that can't actually be the only right answer in the world of unix permissions.

Data Graham
Dec 28, 2009

📈📊🍪😋



Thermopyle posted:

I think I'm just missing something here, because my question is...why does your web server need to know your database connection information?

I mean, I usually just set the enviornment variables on the server and read them in my django settings and that works...

Where do you set them?


E: It's not that the web server needs to see the info per se, it's that wsgi is being executed as www, and it needs that info to connect. It has to come from somewhere that's either accessible to www or passed down to it from the web server itself (which is launched by root), and the former seems like a non-starter, so I'm back to the latter.

Data Graham fucked around with this message at 20:43 on Dec 7, 2015

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Oh, I wasn't thinking about that...it's been a long time since I deployed to something that wasn't something like Heroku or whatever which all have their own way of setting env variables.

I seem to recall Django recommending setting them in wsgi.py

Dominoes
Sep 20, 2007

Connecting to a Heroku database locally. Or storing API keys.

Gounads
Mar 13, 2013

Where am I?
How did I get here?

Data Graham posted:

Unfortunately that doesn't work if it's owned by root and chmod 600.

I can chown it www or chmod it 644 so Apache can see it, but then it's also visible to any other programs on the server that want to try to read it.

I suppose one answer to this is "don't run a server with ~users and critical data at the same time", and maybe that's a fair stance to take nowadays, but I feel like that can't actually be the only right answer in the world of unix permissions.

I haven't dealt with Apache in a while, so this may be a big steaming pile of nonsense...

We run uwsgi under it's own user, not www or root and the web server proxies to it. Only that uwsgi user can read it's own files. The web server doesn't have to be able to read it and it certainly doesn't have to be world readable.

I like this approach because you can do more (usually in dev) than just credentials without a ton of logic in your settings. Want to enable some middleware for profiling? Drastically change logging config? Turn on debug_toolbar? It's just a python file, have a ball.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Yeah, I was thinking about this last night and trying to remember how I handled this last time I was dealing with Django on something other than heroku or similar, and I'm pretty sure it was something like this:

Gounads posted:

I haven't dealt with Apache in a while, so this may be a big steaming pile of nonsense...

We run uwsgi under it's own user, not www or root and the web server proxies to it. Only that uwsgi user can read it's own files. The web server doesn't have to be able to read it and it certainly doesn't have to be world readable.

I like this approach because you can do more (usually in dev) than just credentials without a ton of logic in your settings. Want to enable some middleware for profiling? Drastically change logging config? Turn on debug_toolbar? It's just a python file, have a ball.

Data Graham
Dec 28, 2009

📈📊🍪😋



Not bad. Proxying sounds pretty solid. It might be overkill for the kinds of things I'm doing right now, but I'll bear it in mind for the next time I get into it. Thanks!

Jo
Jan 24, 2005

:allears:
Soiled Meat
I stumbled into an interesting inconsistency in our unit tests. We're using Nose and sometimes we have factories.MyButtFactory(name='fart') and other times it's factories.MyButtFactory.create(name='toot'). It looks like .create is the only one that supports overriding from the docs, but I find it hard to believe we have as many tests as we do which are functional if this isn't the case. What is the correct or standard way of doing it? .create? What if there are no args? .create()?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe
Why does LocationSerializer keep telling me that I'm passing a null value for company_id?

Python code:
# Make Company
print('Creating Company')
co = CompanySerializer(data={'name': co_name, 'address': co_address, 'shift_type': 'OE'})
co.is_valid(raise_exception=True)
co.save()
print('company: {0}'.format(co.instance.id))

# Make Location
print('Creating Initial Location')
loc = LocationSerializer(data={'title': loc_title, 'company': co.instance.id, 'stations': []})
Here's the exact error message:

quote:

django.db.utils.IntegrityError: null value in column "company_id" violates not-null constraint
DETAIL: Failing row contains (12, Main Office, null).

I know the co object has an id because I see a number in the print() after co.save() so I'm not sure why the proceeding serializer isn't recognizing it when I try to create a Location object. I've even tried changing 'company' to 'company_id' but that didn't help. Besides, I'm pretty sure when I feed in data to the serializer via an API call I pass in a 'company' key in the JSON, so it should work the same way here, right?

Jo
Jan 24, 2005

:allears:
Soiled Meat

Karthe posted:

Why does LocationSerializer keep telling me that I'm passing a null value for company_id?

Python code:
# Make Company
print('Creating Company')
co = CompanySerializer(data={'name': co_name, 'address': co_address, 'shift_type': 'OE'})
co.is_valid(raise_exception=True)
co.save()
print('company: {0}'.format(co.instance.id))

# Make Location
print('Creating Initial Location')
loc = LocationSerializer(data={'title': loc_title, 'company': co.instance.id, 'stations': []})
Here's the exact error message:


I know the co object has an id because I see a number in the print() after co.save() so I'm not sure why the proceeding serializer isn't recognizing it when I try to create a Location object. I've even tried changing 'company' to 'company_id' but that didn't help. Besides, I'm pretty sure when I feed in data to the serializer via an API call I pass in a 'company' key in the JSON, so it should work the same way here, right?

I believe I've encountered this fuckery before. I'm guessing you're using the Django Rest Framework. Check to make sure the third column of your database table is actually company_id. If it's actually the *stations* attribute that has not null, perhaps the [] is being cast to null?

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

Jo posted:

I believe I've encountered this fuckery before. I'm guessing you're using the Django Rest Framework. Check to make sure the third column of your database table is actually company_id. If it's actually the *stations* attribute that has not null, perhaps the [] is being cast to null?
Yeah, I'm using DRF. And you know what, I must have run into this issue before because after looking over LocationViewSet I noticed that company_id isn't passed in via the JSON my frontend POSTs to the Location endpoint. Instead, I specify it within the serializer's save() function:

Python code:
serializer.save(company_id=self.request.data['company'])
It turns out stations is no longer a field in the Location model (whoops :v:) so it was getting dropped by the serializer anyway. I was able to get things working by tweaking it thusly:

Python code:
# Make Company
print('Creating Company')
co = CompanySerializer(data={'name': co_name, 'address': co_address, 'shift_type': 'OE'})
co.is_valid(raise_exception=True)
co.save()
print('company: {0}'.format(co.instance.id))

# Make Location
print('Creating Initial Location')
loc = LocationSerializer(data={'title': loc_title})
loc.is_valid(raise_exception=True)
loc.save(company_id=co.instance.id)
But I'm still confused because immediately below this code I'm able to specify the location I just created within the data I pass to EmployeeSerializer:

Python code:
emp = EmployeeSerializer(data={'location': loc.instance.id})
EmployeeSerializer saves with no issue. What the hell...

porksmash
Sep 30, 2008
If I'm using a cached_db session store, what's a reasonable amount of data to store in a user's session? Am I just limited by RAM? I'm trying to figure out how to store up to maybe 2000 model instances that were parsed out of an uploaded file. I want the changes to be approved by the user before saving all of them, so the process will be something like:

request: Upload file
response: parsed file and present results
request: Apply or don't apply
response: models updated or changes discarded.


The problem I'm trying to work around is that the upload may contain a mix of new instances and updated instances, so simply saving all the imported data with a 'not yet approved' flag set won't quite work. I don't want new PKs for the updated instances. I think storing the model instances in the session for one page load would be acceptable, but I just wanted to see if I was missing another more obvious method.

Demonachizer
Aug 7, 2004
Do any of you know if there is a way to change the order than django does a clean() on form data? Essentially I have a form in the order I want and it validates email to come from a certain domain. I would like it to skip that validation if the user is from outside as a guest but the 'position' field is must lower in the form. When I do position = self.cleaned_data.get('position') it stores None to position. I have tested tossing position ahead of the email field and everything processes through just fine.

If there is a way to clean() position earlier somehow it would be super helpful.

Jo
Jan 24, 2005

:allears:
Soiled Meat
I have a database trigger which fires when someone modifies the database (we have outside data sources feeding our DB). It looks like the following things happen, in order:

* Foo has something happen in our application.
* Foo's triggers on the database side run, changing a property of foo to, say, "butts".
* Foo is saved, but the cached value of the attributes is used and "butts" is overwritten by old data.

Is there a way to suppress the writing of the specified property? Can I declare it ephemeral/volatile? We can't use Django's DB triggers/hooks/signals because there's no guarantee we're going to be the ones to touch the database.


EDIT: Disregard, there was another trigger which didn't get removed that was causing the data to be overwritten.

Jo fucked around with this message at 02:48 on Jan 22, 2016

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I don't know if I fully understand the issue, but it sounds like you might be looking for something like update_fields?

Jo
Jan 24, 2005

:allears:
Soiled Meat
I'm back with another :suicide: bug, this time with Django Celery.

I have five tasks, A, B, C, D, and E. All of them are supposed to run every ten minutes or so. B, C, D, and E run just fine. A, however, is running three times. It's supposed to run every ten minutes, but I'm seeing three copies of "Received task: A [2678195-1543983-112-abafd]" every ten minutes instead of one. They all fire within a few seconds of each other.

Here's what I've tried:

  • Restarting beat + worker + flower (and in various orders)
  • Flushing the celery queue with "celery flush"
  • Flushing the redis database
  • Zeroing-out the function so it just straight up returns 0. (So that we can rule out something inside re-scheduling the task.)
  • Renaming the function.
  • Removing the function from celeryconfig.

I also tried injecting a stack trace to see if it was possibly another method invoking A. Nope. Same stack trace.

FINALLY, after removing the task from celeryconfig, I noticed it was still being called twice. This says to me that there are other things on the machine running tasks. When I do a `ps aux | grep celery` I only see my tasks. Any way I can track down who is adding the task to celery?

Jo fucked around with this message at 19:36 on Jan 26, 2016

Data Graham
Dec 28, 2009

📈📊🍪😋



Has anyone successfully gotten django-two-factor-auth working with the Django admin?

I've followed the setup instructions in the docs, particularly this part: http://django-two-factor-auth.readthedocs.org/en/stable/implementing.html#admin-site

And I've got this in my urls.py:

code:
otp_admin_site = AdminSiteOTPRequired()

urlpatterns = [
    url(r'', include('two_factor.urls', 'two_factor')),
    url(r'^admin/', include(otp_admin_site.urls)),
    ...
]
And it logs me in fine, using two-factor auth the way it's supposed to. But then, instead of the usual list of registered ModelAdmin models to interact with, it tells me "You don't have permission to edit anything".

Seems like the models aren't getting registered? Any ideas on how to even debug this?

Data Graham
Dec 28, 2009

📈📊🍪😋



Never mind the above, incidentally. Some more loving around and

code:
from django.contrib.auth.models import User, Group, Permission
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from two_factor.admin import AdminSiteOTPRequiredMixin, admin

class AdminSiteOTPRequired(AdminSiteOTPRequiredMixin, AdminSite):
    """
    AdminSite enforcing OTP verified staff users.
    """
    pass

otp_admin_site = AdminSiteOTPRequired()

otp_admin_site.register(User, UserAdmin)
otp_admin_site.register(Group, GroupAdmin)
otp_admin_site.register(Permission)

@admin.register(Widget, site=otp_admin_site)
class WidgetAdmin(admin.ModelAdmin):
     ...
You have to register the auth ones manually as well as any you might want to add yourself, and making the AdminSite subclass with the AdminSiteOTPRequiredMixin allows you to .register() to it directly or call the decorator on two_factor.admin instead of the built-in one.

(Note that AdminSiteOTPRequired already exists in two_factor.admin anyway so I could have imported it from there; but I also wanted to use an existing AdminSite subclass to allow django.contrib.gis.admin.GeoModelAdmin)

Just a documentation thing if anything.

Data Graham fucked around with this message at 23:26 on Jan 27, 2016

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Anybody in here tried to set up and use any of the various solutions out there for Websockets + Django? How'd it go?

It seems like everything is kinda hacky and a lot of effort so I haven't actually tried anything yet...

I'm actually leaning towards just writing something completely separate from my Django project that interacts with its already existing REST API, and serves it out out over its own websocket implementation.

Eleeleth
Jun 21, 2009

Damn, that is one suave eel.

Thermopyle posted:

I'm actually leaning towards just writing something completely separate from my Django project that interacts with its already existing REST API, and serves it out out over its own websocket implementation.

This is what I did, it works a lot better than trying to integrate websockets into django, in my limited experience wrestling with things like swampdragon.

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Okay, because I'm an idiot, I need help grasping something apparently so basic it's embarrassing. I have some code that will run a "long running process" that, if it succeeds, I'd like to create a bunch of Model objects with the results. If it does not succeed (returns no results) I need the user to know that. Obviously, Celery is the thing to use to run the long-running code, and I'd make a task for that:

Python code:
@app.task
def fart(some_id):
    blah = some_long_involved_thing()
    if len(blah) > 0:
        # make some objects!
        return True #??
    else:
        return False  #??
Then in a view, I do something like:

Python code:
task = fart.delay(3)
To check on the state of the task, I need to have configured a Result Backend, which I think django-celery will take care of for me, yes? That stores the ID of the task and it's state and results, which is great, but I want to make sure I understand all this before I start installing stuff and digging myself a hole.

How do I get the ID of task after the fact? For example, if a user wants to check on the status of queries they are running. Do I need to create a new UserTasks model and store the id of task in there? How do I *get* the ID of task to store it? Will the result of the task be the True / False I return from it? In a view that looks up a task status, how do I do that? I see that django-celery has a couple views that will do this for me, which is neat, but what if I want to look at this stuff in my own view?

Sorry for being a dumb-dumb.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply