Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django postgres migration issues when adding fields to existing models
I currently have a project in development. When trying to add new fields to existing models I am having issues with migrations which is causing me to worry about data loss. The errors I'm getting is that it says the fields don't exist when I can clearly see in the latest migrations file it has been added. I have never had this issue before when adding new fields and then pushing to the remote repository and then pulling it into production where I would then do the migrations. -
I need to prevent showing previous pages from my django app
Even after I logged out I'm still able to see my previous pages how to prevent the browser from showing this? I tried this piece of JavaScript code . Note: I used template inheriting and templates statically imported. function preventBack() { history.pushState(null, null, location.href); window.onpopstate = function () { history.go(1); console.log("worked") }; } window.onload = function() { preventBack(); console.log("worked call ") }; when I tried this "console showed worked call" but the 'worked' is not yet printed in console means wins=down.onpopState not worked what's the cause of this problem. I'm quiet new in Django feels like I tarped here!! -
django-keycloak refresh openID connect .well-known error
Hello everyone i really need help in a issue i faced while working on django-keyclock: you can see here the documentation thet I'm following: https://django-keycloak.readthedocs.io/en/latest/ I did the initial setup and I setup for remote user , then i configured the server and the realms in the django admin panel and everything looks good. but when i try to Refresh OpenID Connect .well-known I got this error in the image. And i think that /auth is the problem because when I remove it I got a json response. please if anyone can help me. and thank you in advance. [enter image description here][1] [enter image description here][2] [1]: https://i.stack.imgur.com/g09Jc.png [2]: https://i.stack.imgur.com/Bv1E1.png -
How can I deploy an app on Heroku that is not located in the root directory?
I've got a project that has a directory structure as such: ├── backend │ ├── backend-files.py │ └── procfile ├── docker-compose.yml └── frontend I want to be able to deploy the Python backend (Django) on Heroku. As you can see it is located in it's own directory. However, Heroku does not allow me to specify a subdirectory when pointing to a github repo. This means that I would need my backend code to be at the root level in order to use their CD pipeline features. Does anyone know of a way to modify my configuration in Heroku so that I can keep the directory structure as is? -
Django-allauth Redirect any unauthenticated user to login page
I’m developing a django project and my veiws are function based and using django-allauth for authentication. Now, I’m searching for a pattern to work on all project so that any unauthenticated user is redirected automatically to login page. An alternative way is to add @login_required() decorator over every view function but I don’t see that as logical method. -
Custom OrderingFilter Django REST + Vue
I'm working on backend part of project (Django REST). I have a task - to do sorting for the front (Vue). The frontend sends a key for sorting and a parameter for sorting. Example: GET /api/v1/stocks/?sort_key=FBS&sort_type=ascending GET /api/v1/stocks/?sort_key=FBS&sort_type=descending I guess it can be done with OrderingFilter and DjangoFilterBackend. Any suggestions will be helpful. my models.py class Stock(models.Model): class Meta: verbose_name_plural = "Stocks" verbose_name = "Stock" ordering = ("-present_fbs",) store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, verbose_name="Store") fbs = models.PositiveIntegerField(default=0, verbose_name="FBS") my views.py class StocksApi(ListModelMixin, GenericViewSet): serializer_class = StocksSerializer permission_classes = (IsAuthenticated,) pagination_class = StocksDefaultPagination def get_queryset(self): return Stock.objects.filter(store__user_id=self.request.user.pk).order_by("-fbs") -
TK to run django server on windows
I have windows server running Django as a CMD process. Some workers mistakenly closing it. I want to switch to TK running the Django server and put output on screen. How safe is that ? How do I close the django properly ? class TextRedirector(object): def __init__(self, widget, tag="stdout"): self.widget = widget self.tag = tag def write(self, str): self.widget.configure(state="normal") self.widget.insert("end", str, (self.tag,)) self.widget.see(tk.END) self.widget.configure(state="disabled") class TkApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) toolbar = tk.Frame(self) toolbar.pack(side="top", fill="x") # set window size self.geometry("500x200") self.title("DJANGO") self.text = tk.Text(self, wrap="word") self.text.pack(side="top", fill="both", expand=True) self.text.tag_configure("stderr", foreground="#b22222") self.text.yview("end") self.iconbitmap("activity.ico") sys.stdout = TextRedirector(self.text, "stdout") sys.stderr = TextRedirector(self.text, "stderr") self.protocol('WM_DELETE_WINDOW', self.on_close) self.run() def on_close(self): response = tkinter.messagebox.askyesno('Exit', 'Are you sure you want to exit?') if response: try: # KILL THE DJANGO PROCESS .... finally: sys.exit(0) def run(self): # RUN THE DJANGO PROCESS .... if __name__ == '__main__': app = TkApp() app.mainloop() will this work ? I also need to tell the django to close nicely (same as I would click the X button on command line) Instead: I want: -
Scan python link and iframe it?
i want to execute one python code and try to get output in browser import os tools=os.popen('pip list | seashells').read() output is this link serving at https://seashells.io/v/rWXx9XvF how to iframe the link generated in terminal ? i try to store this seashell generated link in python veriable and iframe in html code but cuould not do it? i neeed help!! -
ModuleNotFoundError: No module named 'phone_verify.views'
I am using django-phone-verify in my drf project to send otp and phone call for sign in. When i want to import start_verification from phon_verify.views this error is showing"ModuleNotFoundError: No module named 'phone_verify.views" views.py from rest_framework.decorators import api_view from rest_framework.response import Response from phone_verify.views import start_verification @api_view(['POST']) def sign_in_sms(request): phone_number = request.data.get('phone_number') if not phone_number: return Response({'error': 'Phone number is required'}, status=400) start_verification(phone_number, method='sms') return Response({'success': 'Verification started'}) @api_view(['POST']) def sign_in_phone_call(request): phone_number = request.data.get('phone_number') if not phone_number: return Response({'error': 'Phone number is required'}, status=400) start_verification(phone_number, method='call') return Response({'success': 'Verification started'}) urls.py from django.urls import path, include from phone_verify.urls import urlpatterns as phone_verify_urls from django.urls import path from sms.views import sign_in_sms, sign_in_phone_call urlpatterns = [ path('api/', include('sms.urls')), path('phone-verify/', include(phone_verify_urls)), path('sign-in/sms/', sign_in_sms), path('sign-in/phone-call/', sign_in_phone_call), ] settings.py INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phone_verify', 'sms', ] PHONE_VERIFICATION = { 'FROM_NUMBER': 'my number', 'TWILIO_ACCOUNT_SID': 'my sid', 'TWILIO_AUTH_TOKEN': 'my token', } -
decode PDF from Django BinaryField using Angular / Typescript
I have an issue regarding encoding a PDF file into a BinaryField (MySQL as database) and then retrieving it via endpoint with Angular and decoding it into the file again. My model and save-to-database method looks like this: import os from django.db import models class Report(models.Model): report_file_type: models.CharField = models.CharField(max_length=50, null=True, blank=True) report_file: models.BinaryField = models.BinaryField(null=True, blank=True) def save_report_in_database(self, file_path: str, file_type: str) -> None: with open(file_path, 'rb') as file: content = file.read() self.report_file_type = file_type # type: ignore # PyCharm doesn't like this self.report_file = content # type: ignore # PyCharm doesn't like this self.save() # delete the file from the file system os.remove(file_path) The PDF is generated in a celery task via matplotlib and PdfPages and it's reasonably small (around 60kB) i.e. import matplotlib.backends.backend_pdf with matplotlib.backends.backend_pdf.PdfPages(pdf_out) as pdf: for _idx, fig in enumerate(figs): fig.text( 0.999, 0.005, # bottom right corner f"{_idx + 1}/{len(figs)}", ha='right', fontsize=10, fontweight="bold", ) pdf.savefig(fig) When complete, the save_report_in_database method is called. When I log the output I get: 2023-04-26 05:56:57,539 - project logger - INFO - PDF as bytes: b'%PDF-1.4\n%\xac\xdc \xab\xba\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n8 0 obj\n<< /Font 3 0 R /XObject 7 0 R /ExtGState 4 0 R … -
"User with this email already exists." False Error Upon Signup in Django / React Application with Custom User
I am using redux to manage the state. Email is the username for my custom user model. Here is my django User model. from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils import timezone class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError("Please provide an e-mail") email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) # user.is_superuser = False user.save() return user def create_superuser(self, email, name, password): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) last_login = models.DateTimeField( blank=True, null=True, verbose_name='last login') date_joined = models.DateTimeField( blank=True, null=True, default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.email objects = UserAccountManager() Here is the User Serializer and below auth.js "from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): fields = ['id', 'email', 'name', 'password', ] " Here is the auth.js "export const signup = (name, email, password, re_password) => async ( dispatch ) => { const config = { headers: { "Content-Type": "application/json", }, }; … -
how to solve problem with AJAX requests in django?
script.js: console.log('work') const url = window.location.href const searchForm = document.getElementById('search-form') const searchInput = document.getElementById('search-input') const resultsBox = document.getElementById('results-box') const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value console.log('first module success') const sendSearchData = (product)=>{ $.ajax({ type: ' POST', url: 'search/', data: { 'csrfmiddlewaretoken':csrf, 'product': product, }, success: (res)=>{ console.log('---res ---', res) }, error:(err)=>{ console.log('---error---',err) } }) } searchInput.addEventListener('keyup', e=>{ console.log(e.target.value) if (resultsBox.classList.contains('not-visible')){ resultsBox.classList.remove('not-visible') } if (e.target.value == '') { resultsBox.classList.add('not-visible') } sendSearchData(e.target.value) }) views.py: class ProductListView(ListView): model = Product paginate_by = 10 template_name = 'shop/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() if self.request.headers.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': product = self.request.POST.get('product') return context, JsonResponse({'data':product}) return context after entering something into the search bar, this code is activated and sends Ajax requests that pass this text, but I get an error in the console ''' statusText: "SyntaxError: An invalid or illegal string was specified" ''' -
Write uploaded file by chunks in an async context
I have a Python async function receiving a django.core.files.uploadedfile.TemporaryUploadedFile from an Django API endpoint, as well as from a Django form. Once this function is launched, it needs to write the file, and since the files are larges Django suggests to use UploadedFile.chunks() method to do so. So I have a classical sync method to write the file by chunks to a destination path, looking like this: from pathlib import Path from django.core.files.uploadedfile import TemporaryUploadedFile def write_file(file: TemporaryUploadedFile, destination: Path) -> None: with open(destination, "wb+") as out: for chunk in file.chunks(): out.write(chunk) As said, it is called from an async context, using asgiref.sync.sync_to_async. The main function logic looks like this: from asgiref.sync import sync_to_async from pathlib import Path from django.core.files.uploadedfile import TemporaryUploadedFile async def process_submission(file: TemporaryUploadedFile) -> None: ... do stuff ... await sync_to_async(write_file)(file=file, destination=Path("/my_path.mp4")) ... do other stuff ... ...but I get the error ValueError: read of closed file. I believe it might be related to the fact that the file is a stream, but I'm not really sure on what's happening. Any idea on why and how to solve that? -
Django-Allauth Google OAuth get approved scopes
I have added additional Google API scopes to my Django application. I wanted to check if the user has approved the other scopes. I searched online and found references to scopes in the extra_data. But I couldn't find it. Appreciate any help in checking if the user has approved the extra scopes. -
Vercel Deploy Django Raised Sqlite3 Version Exception
I am deploying Django to Vercel. But it raised the error below during running. django.db.utils.NotSupportedError: deterministic=True requires SQLite 3.8.3 or higher How to upgrade the Sqlite3 into 3.8.3 on Vercel server? -
Django using prefetch_related to reduce queries
I am trying to understand how I can improve the following query: class PDFUploadRequestViewSet(viewsets.ModelViewSet): def get_queryset(self): project_id = self.request.META.get('HTTP_PROJECT_ID', None) if project_id: return PDFUploadRequest.objects.filter(project_id=project_id) else: return PDFUploadRequest.objects.all() def get_serializer_class(self): if self.action == 'list': return PDFUploadRequestListSerializer else: return self.serializer_class The issue is that the more PDFPageImage objects are in the DB then it creates separate query for each of them thus slowing down the request. If there is only one value if PDFPageImage related to given PDFUploadRequest then its pretty fast, but for each additional value it is producing extra query and after doing some research I found out that prefetch_related might somehow help with this, but I have not been able to figure out how to use it with my models. This is how the model for PDFUploadRequest looks like: class PDFUploadRequest(models.Model, BaseStatusClass): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) file = models.FileField(upload_to='uploaded_pdf') file_name = models.CharField(max_length=255) status = models.CharField( max_length=50, choices=BaseStatusClass.PDF_STATUS_CHOICES, default=BaseStatusClass.UPLOADED, ) completed = models.DateTimeField(null=True) processing_started = models.DateTimeField(null=True) text = models.TextField(default=None, null=True, blank=True) owner = models.ForeignKey(User, related_name='pdf_requests', on_delete=models.PROTECT, null=True, default=None) project = models.ForeignKey(Project, related_name='pdf_requests', on_delete=models.PROTECT, null=True, default=None) class Meta: ordering = ['-created'] def no_of_pages(self): return self.pdf_page_images.count() def time_taken(self): if self.completed and self.processing_started: return self.completed - self.processing_started And this is the related … -
How to show all messages from gmail who logged in with his google account to my site Django
I used for auth django-allauth. I was able to get some user data with google_account = SocialAccount.objects.get(user=user, provider='google').extra_data but i don't know how to get access_token. I used access_token = extra_data.get('access_token') but this return None I also try without .extra_data google_account = SocialAccount.objects.get(user=user, provider='google') social_token = google_account.socialtoken_set.first() How can i take the token and show all mails and i use: try: service = build('gmail', 'v1', credentials=credentials) # Fetch the user's 10 most recent emails results = service.users().messages().list(userId='me', maxResults=10).execute() messages = results.get('messages', []) # Print the subject line of each message for message in messages: msg = service.users().messages().get(userId='me', id=message['id']).execute() return msg['payload']['headers'][16]['value'] except HttpError as error: return f'An error occurred: {error}' settings.py SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': ['profile', 'email'], 'AUTH_PARAMS': {'access_type': 'online'}, 'SOCIALACCOUNT_QUERY_EMAIL': True, 'APP': { 'client_id': os.environ.get('GOOGLE_CLIENT_ID'), 'secret': os.environ.get('GOOGLE_SECRET'), 'key': '' } }} SOCIALACCOUNT_QUERY_EMAIL=True SOCIAL_AUTH_ENABLED_BACKENDS = ['google', 'google-oauth'] -
Datetiemfield saved to database but showing in adminsite is null
Ordered_date was saved in db But not display in adminsite My code: My code Please help me fix this issue -
Reuse modal implemented in Django
I know this is common to ask but I search for different solutions but couldn't yet find one, Is there any way to reuse the modal? instead of making different modals in each function why not reuse it into just one, is there any way to implement it, especially in Django? should I transfer it into a javascript file? What I've tried is extending the HTML to the main file but it couldn't work modal.html templates/modal.html {% block modal_scripts %} <div class="modal-onboarding modal fade animate__animated" id="onboardImageModal" tabindex="-1" aria-hidden="true" > <div class="modal-dialog" role="document"> <div class="modal-content text-center"> <div class="modal-header border-0"> <a class="text-muted close-label" href="javascript:void(0);" data-bs-dismiss="modal" >Skip Intro</a > <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" ></button> </div> <div class="modal-body p-0"> <div class="onboarding-media"> <div class="mx-2"> <img src="../../assets/img/illustrations/girl-unlock-password-light.png" alt="girl-unlock-password-light" width="335" class="img-fluid" data-app-light-img="illustrations/girl-unlock-password-light.png" data-app-dark-img="illustrations/girl-unlock-password-dark.png" /> </div> </div> <div class="onboarding-content mb-0"> <h4 class="onboarding-title text-body">Test</h4> <div class="onboarding-info"> In this example you can see a form where you can request some additional information from the customer when they land on the app page. </div> <form> <div class="row"> <div class="col-sm-12"> <div class="mb-3"> <label for="roleEx3" class="form-label">Discount</label> <select class="form-select" tabindex="0" id="roleEx3"> <option>Senior Citizen - 20%</option> <option>Business Owner</option> <option>Other</option> </select> </div> </div> </div> </form> </div> </div> <div class="modal-footer border-0"> <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal"> … -
Faile to load resource: the server responded with a status of 500 (Internal Server Error)
my web page runs normally, until i do a javascript AJAX snippet, it starts showing error 500 in cart function at the plus sign, when I click add it just increases the amount in the data and has to reload the page to see the number quantity, the user side won't see it script in html <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="" crossorigin="anonymous"></script> Views.py def add_to_cart(request): user = request.user product_id = request.GET.get('prod_id') product = Product.objects.get(id=product_id) Cart(user=user, product=product).save() return redirect('/cart') def show_cart(request): if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user) amount = 0.0 shipping_amount = 10.0 total_amount = 0.0 cart_product = [p for p in Cart.objects.all() if p.user == user] if cart_product: for p in cart_product: tempamount= (p.quantity * p.product.final_price) amount += tempamount total_amount = amount+ shipping_amount context = {'cart':cart, 'total_amount':total_amount, 'amount':amount,'shipping_amount':shipping_amount} return render(request, 'general/addtocart.html', context) else: return redirect('login') def plus_cart(request): if request.method == 'GET': prod_id = request.GET['prod_id'] c= Cart.objects.get(Q(product=prod_id) & Q(user = request.user)) c.quantity+=1 c.save() amount = 0.0 shipping_amount = 10.0 cart_product = [p for p in Cart.objects.all() if p.user == request.user] for p in cart_product: tempamount= (p.quantity * p.product.final_price) amount += tempamount total_amount = amount+ shipping_amount data={ 'quantity':c.quantity, 'amount': amount, 'total_amount': total_amount }, return JsonResponse(data) Javascript.js $('.plus-cart').click(function () { //console.log("Click") var id … -
"[" was not closed what can i do to fix this
i keep getting this error but the bracket is actually closed i checked the entire work but to no avail. -
docker web container not finding the database from mysql container
i'm using docker and docker-compose for the local development host as we're working in a team of frontend developers and backend developer, using django as the backend with mysql as the sgbd, so the project was running well in docker( only the backend is dockerized), after the last commit everything crashed , so i'm getting the following logs from the web container : File "/usr/local/lib/python3.10/threading.py", line 953, in run 2023-04-25 23:13:25 self._target(*self._args, **self._kwargs) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper 2023-04-25 23:13:25 fn(*args, **kwargs) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run 2023-04-25 23:13:25 self.check_migrations() 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 486, in check_migrations 2023-04-25 23:13:25 executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ 2023-04-25 23:13:25 self.loader = MigrationLoader(self.connection) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/loader.py", line 53, in __init__ 2023-04-25 23:13:25 self.build_graph() 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/loader.py", line 220, in build_graph 2023-04-25 23:13:25 self.applied_migrations = recorder.applied_migrations() 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations 2023-04-25 23:13:25 if self.has_table(): 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 55, in has_table 2023-04-25 23:13:25 with self.connection.cursor() as cursor: 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 33, in inner 2023-04-25 23:13:25 return func(*args, **kwargs) 2023-04-25 23:13:25 File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 259, in cursor 2023-04-25 23:13:25 return self._cursor() 2023-04-25 23:13:25 File … -
Using a pivot table to create a tree-like structure and how to create efficient queries?
In our codebase we have a set of models that represent AI models and their training data. When people train new models they are usually trained off an existing AI model in the database, and we wanted to track a sort of "versioning" of these models, so that people can use prior versions, and create branching revisions. our models look like so: class TrainingRun(models.Model): from_model = models.ForeignKey('api.AIModel', related_name='subsequent_runs') to_model = models.OneToOneField('api.AIModel', related_name='prior_run') hyperparameters = models.JSONField(default={}) # etc. class AIModel(models.Model): save_path = models.URLField(max_length=200, null=True) bookmarked_by = models.ManyToManyField('auth.User', related_name='bookmarks') # etc. we're expecting this data to come out looking something "linked-list"y so that users can create branching revisions to prior models, bookmark ones that they like etc. the data structure might come out to look something like a git revision history, without merge functionality but I'm wondering is this is a good idea inside a relational database with foreign keys etc. Also I am wondering if there is an efficient way to traverse the list of objects in a way where I could, say, get a list of any users inside the tree that have subscribed to a bookmark? It seems like no matter which way you slice it you'll be doing … -
How can I aggregate averages from two models for use in one model's field?
I have two models: class Review(models.Model): artist = models.CharField(max_length=100) album = models.CharField(max_length=200) rating = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10)], default=10, ) content = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) ... class AddedReview(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.ForeignKey(Review, on_delete=models.CASCADE) rating = models.IntegerField(default=10) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(default=timezone.now) ... The Review model is an initial review posted by a user. The AddedReview model is additional reviews users will be able to post on an initial Review The initial Review will have a rating added by the original user, and additional ratings will be added by other users. I want to be able to aggregate all the ratings from both models into an avg_rating field for use in the Review model. I know how to perform this in a Python shell but I'm not very knowledgable about how to create a model method to do this. -
You cannot access body after reading from request's data stream
I keep getting the following error when trying to post to PayPal: shippingData = json.loads(request.body) django.http.request.RawPostDataException: You cannot access body after reading from request's data stream I have tried removing the request.headers, this does nothing. I tried removing CRSF Token altogether and still the same error. I have also tried renaming request.body into a different variable, this also does not remove the error. Replacing with request.data just gives a different error also. This is my view: def create_order(request): customer = Customer.objects.get(user=request.user) shippingData = json.loads(request.body) first_name = customer.first_name last_name = customer.last_name ShippingAddress.objects.create( customer=customer, house=shippingData['shipping']['house'], street=shippingData['shipping']['street'], city=shippingData['shipping']['city'], postcode=shippingData['shipping']['postcode'], ) # assuming you have retrieved the ShippingAddress object for the given customer shipping_address_queryset = ShippingAddress.objects.filter(customer=customer) if shipping_address_queryset.exists(): shipping_address = shipping_address_queryset.first() # extract the necessary fields from the shipping_address object house = shipping_address.house street = shipping_address.street city = shipping_address.city postcode = shipping_address.postcode user_cart = Cart.objects.filter(user=request.user).first() if user_cart: # get cart items and total cart_items = user_cart.items.all() cart_total = user_cart.get_cart_total() # create the items list items = [] for item in cart_items: items.append({ "name": item.product.title, "description": "", "quantity": str(item.quantity), "unit_amount": { "currency_code": "GBP", "value": "{:.2f}".format(item.product.price) }, "tax": { "currency_code": "GBP", "value": "0.00" } }) # calculate the breakdown for the purchase unit item_total = sum(float(item["unit_amount"]["value"]) …