Note that there are some explanatory texts on larger screens.

plurals
  1. POcelery task cannot open a model instance after passing a pk or id to the task after saving it in the django view
    primarykey
    data
    text
    <p>I have a django view that creates a user then sends the user.pk to a celery task (.delay) in order to email the user and add the user to a mailing list via some API calls I don't want in the view. </p> <p>After I save the new user instance <code>user.save()</code>, I send the <code>user.pk</code> to the celery task <code>email_user_task.delay(user.pk)</code>, but the celery task blows up with the error that the user does not exist. </p> <p>I have tried adding a try except block in the celery task with a sleep to wait for the view to finish, which works but will cause other problems when the site is busy and tried using a manual transaction commit, but am getting other errors and feel this should work.</p> <pre><code>@render_to('signup.html') def signup(request): if request.method == "POST": form = SignupForm(request.POST, request=request) if form.is_valid(): new_user = form.save(commit=False) new_user.email = form.cleaned_data["email"] new_user.fist_name = form.cleaned_data["first_name"] new_user.last_name = form.cleaned_data["last_name"] new_user.save() email_user_task.delay(new_user.pk) # this cannot get the User from the pk HttpResponseRedirect(reverse("signup_complete")) else: form = SignupForm(request=request) return locals() </code></pre> <p>This celery task blows up:</p> <pre><code>@task def email_user_task(user_pk): user = User.objects.get(pk=user_pk) # this yeilds a User.DoesNotExist error </code></pre> <p>My first fix which works unless 5 seconds isn't enough:</p> <pre><code>def email_user_task(user_pk): try: user = User.objects.get(pk=user_pk) except User.DoesNotExist: import time time.sleep(5) user = User.objects.get(pk=user_pk) # this works I'm guessing after the view finishes </code></pre> <p>What am I missing? i.e. Why isn't the <code>new_user.save()</code> writing to the DB before calling the celery task?</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