0

I am using django development environment to develope an app while trying to execute view function i am getting raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

i have configured the django app using asgi mode and running the daphne via command daphne myproject.asgi:application. there is a signup form in my app where user put his name,company_id,email as username and password. i want to store the username,password in user model and the company_id against that user in userprofile model. signup view is failing to execute the django orm queries and i am unable to store the data as expected.

```

async def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
    
        if form.is_valid():
            user = form.save(commit=False)
            user.email = user.username
            user.first_name = request.POST.get('first_name')
            user.last_name = request.POST.get('last_name')
            user.save()
        
            customer_id = request.POST.get('customer_Id')  # Get the customer_id from the form
            print(customer_id)
            try:
                customer = await sync_to_async(Customer.objects.get)(customer_id=customer_id)
            except Customer.DoesNotExist:
                return render(request, 'core/signup.html', {'form': form, 'error_message': 'NA'})
        
            userprofile = await sync_to_async(Userprofile.objects.create)(user=user, customer=customer)
            await sync_to_async(userprofile.save)()
        
            await sync_to_async(login)(request, user)  # Using sync_to_async for login
            return redirect('landingpage')
    else:
        form = UserCreationForm()
    return render(request, 'core/signup.html', {'form': form})
```
Arif Khan
  • 1
  • 3

0 Answers0