Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are the caching methods using rabbitmq in Django?
I am Django developer and I know about Redis caching method and technique. But my project is big, and I develop the project in RabbitMQ with celery. I want to put some caching technique to make my project fast. Can anyone help me find some good website or tell me stuff like Redis default caching? I am using Django, celery, RabbitMQ, nginx and Postgres database. -
Cannot assign "'75f37671bac8'": "Results.prescription" must be a "Prescription" instance
I'm trying to add a patient to my result form, but it says Cannot assign "'75f37671bac8'": "Results.prescription" must be a "Prescription" instance. Models.py class Patient(models.Model): uniqueId = models.CharField(null=True, blank=True, max_length=100) slug = models.SlugField(max_length=500, unique=True, blank=True, null=True) date_created = models.DateTimeField(blank=True, null=True) last_updated = models.DateTimeField(blank=True, null=True) class Results(models.Model): title = models.CharField(null=True, blank=True, max_length=100) number = models.CharField(null=True, blank=True, max_length=100) dueDate = models.DateField(null=True, blank=True) status = models.CharField(choices=STATUS, default='CURRENT', max_length=100) notes = models.TextField(null=True, blank=True) #RELATED fields patient = models.ForeignKey(Patient, blank=True, null=True, on_delete=models.SET_NULL) views.py if request.method == 'POST': doc_form = DoctorForm(request.POST) inv_form = ResultsForm(request.POST, instance=results) patients_form = PatientSelectForm(request.POST, initial_patient=results.patient, instance=results) if doc_form.is_valid(): obj = doc_form.save(commit=False) obj.results = results obj.save() messages.success(request, "Results Doctor added succesfully") return redirect('create-build-results', slug=slug) elif inv_form.is_valid and 'paymentTerms' in request.POST: inv_form.save() messages.success(request, "Results updated succesfully") return redirect('create-build-results', slug=slug) elif patients_form.is_valid() and 'patient' in request.POST: patients_form.save() messages.success(request, "Client added to Results succesfully") return redirect('create-build-results', slug=slug) traceback line elif patients_form.is_valid() and 'patient' in request.POST: -
How do I add custom error messages in the Django Rest Framework API Key library?
I have implemented the Django Rest Framework API Key library for Authentication in my project and it is working well, however I noticed that "403 Forbidden" with { "detail": "Authentication credentials were not provided" } is given whenever there is any issue. For example, if the key has expired then these details are given, if the key has been provided but is invalid then these details are given, and so on. I want to be able to tell the client what exactly is wrong - because for an expired key: "credentials were not provided" is not correct - because credentials were provided, it's just that they're expired! Is this possible - or even safe to do? This is the library: https://florimondmanca.github.io/djangorestframework-api-key/ -
The CreateView page doesn't take into account the form
I tried to create in Django an create view , to use form and it doesn't work. The program doesn't use form. I don t understand why the form doesn t work. urls.py from django.urls import path from .views import ( ItemListView, ItemDetailView, ItemCreateView ) urlpatterns = [ path(r'', ItemListView.as_view(template_name='item_list.html'), name='ListView'), path(r'create/', ItemCreateView.as_view(), name='create'), path(r'<int:pk>/', ItemDetailView.as_view(), name='s'), ] models.py class Item(models.Model): #associations user =models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) article =models.ForeignKey(Article, on_delete=models.CASCADE) #item stuff name =models.CharField(max_length=120) description =models.TextField(blank=True, null=True, help_text='Separate each item by comma') exceptions =models.TextField(blank=True, null=True, help_text='Separate each item by comma') bl =models.BooleanField(default=True) timestamp =models.DateTimeField(auto_now_add=True) updated =models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('menus:s', kwargs={'pk':self.pk}) class Meta: ordering = ['-updated','-timestamp'] def get_description(self): return self.description.split(',') def get_exceptions(self): return self.exceptions.split(',') views.py class ItemCreateView(CreateView): template_name = 'menus/form.html' form_class = ItemForm def get_queryset(self): return Item.objects.filter(user=self.request.user) def get_context_data(self,*args, **kwargs): context=super(ItemCreateView, self).get_context_data(**kwargs) title='Add Item' context={ 'title' : title } def form_valid(self, form): instance = form.save(commit=False) instance.user = self.request.user return super(ItemCreateView, self).form_valid(form) forms.py from django import forms from .models import Item class ItemForm(forms.ModelForm): class Meta: model = Item fields = [ 'name', 'description', 'exceptions', 'bl', ] form.html {% extends 'main\base.html' %} {% block content %} <html> <body> <p>{{ title }}</p> {% if form.errors.non_field_errors %}{{ form.errors.non_field_errors }}{%endif%} <form method="POST"> {% csrf_token %} {{ form.as_p … -
Add Content-Disposition header to drf-yasg
I have a django APIView with swagger documentation using drf-yasg. Anytime I make a post request to the API i get this error response { "detail": "Missing filename. Request should include a Content-Disposition header with a filename parameter." } When I add the Content-Disposition header to the postman request it I am able to get the right responses. Content-Disposition: attachment; filename=<insert-your-file-name> My question is how do I add the Content-Disposition to the drf-yasg swagger_auto_schema decorator if possible. This is how my APIView looks like class ReceiptsUploadView(APIView): parser_classes = (FileUploadParser, MultiPartParser) params = [openapi.Parameter("file", openapi.IN_FORM, type=openapi.TYPE_FILE)] @swagger_auto_schema(operation_description="file", manual_parameters=params) def post(self, request): file_obj = request.FILES.get("file") if file_obj: fs = FileSystemStorage() file = fs.save(file_obj.name, file_obj) file_url = os.path.join(settings.BASE_DIR, fs.url(file)[1:]) receipt_blocks = Receipt(blocks=extraction_data(file_url)) receipt_blocks.save() return Response( extraction_data(file_url), status=status.HTTP_200_OK, ) else: return Response( {"error": "file not selected"}, status=status.HTTP_400_BAD_REQUEST ) -
Django Graphene Custom Error not showing extensions
I am using graphene_django and I am interested in having custom errors being raised What I am trying is: class CustomGraphQLError(GraphQLError): def __init__(self, message, extensions, nodes=None, source=None, positions=None, path=None, original_error=None): super().__init__(message, nodes, source, positions, path, original_error, extensions) and then raising an error like this raise CustomGraphQLError Despite I have made extensions mandatory, they don't seem to appear in the response Example response { "errors": [ { "message": "Custom error", "locations": [ { "line": 2, "column": 3 } ], "path": [ "traces" ] } ], "data": { "traces": null } } Can't understand whats wrong here -
How to divide Daphne requests on mutiple processors?
I use a Daphne server for my ASGI Django application. When I run htop on my Ubuntu server it shows all the load on only one processor and the app gets slow, so I'd like to know what is the easiest way to speed up my server. App is inside a Docker container. I run Daphne with command: daphne WBT.asgi:application --bind "0.0.0.0" --port "8000". I use Nginx as a proxy. I tried using uvicorn server with multiple workers but then I get problems with layout. Ie. let's say that I have 4 workers when I visit my web app, it loads it on only one worker correctly, so in 25% cases I get no layout. -
Django restframework-simple-jwt: Could not deserialize key data
I'm trying to use django-simplejwt & restframework with RSA256. I generated my keypair by following this gist. The public & private keypair are being saved in a .env file: JWT_SIGNING_KEY='-----BEGIN RSA PRIVATE KEY-----\\n keydata\\n -----END RSA PRIVATE KEY-----' JWT_VERIFYING_KEY='-----BEGIN PUBLIC KEY-----\\n keydata\\n -----END PUBLIC KEY-----' My jwt configuration settings.py looks like this (additional info is for compatibility with Auth0): REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } SIGNING_KEY = os.getenv("JWT_SIGNING_KEY") VERIFYING_KEY = os.getenv("VERIFYING_KEY") SIMPLE_JWT = { 'USER_ID_FIELD': 'user_id', 'ACCESS_TOKEN_LIFETIME': timezone.timedelta(minutes=10), 'REFRESH_TOKEN_LIFETIME': timezone.timedelta(hours=6), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM' : 'RS256', # Default would be HS256 'SIGNING_KEY' : f'''{SIGNING_KEY}''', #config("JWT_SIGNING_KEY"), # Must be private key 'VERIFYING_KEY' : f'''{VERIFYING_KEY}''', #config("JWT_VERIFYING_KEY"), # Must be public key 'AUDIENCE' : config("JWT_AUDIENCE"), 'ISSUER': config("JWT_ISSUER"), 'JWK_URL': f'{config("JWT_ISSUER")}/.well-known/jwks.json', 'USER_ID_CLAIM': f'{config("JWT_AUDIENCE")}/email', 'JTI_CLAIM': None, 'TOKEN_TYPE_CLAIM': None, 'AUTH_HEADER_TYPES': ('Bearer',), } When restricted views that need a user object are being called, a function for decoding the jwt token and returning the corresponding user object is being executed: def token_user(request): s, token = request.META["HTTP_AUTHORIZATION"].split(" ") decoded = jwt.decode(token, settings.VERIFYING_KEY, algorithms=["RSA256"]) username = decoded["username"] user = get_user_model().objects.filter(username=username) return user Here are my Login view & LoginSerializer (I cut out most of the validation process since this worked before implementing jwt. … -
How does set_group_by works in Django?
I was writing the following query: claim_query = ClaimBillSum.objects.filter(claim__lob__in = lobObj)\ .annotate(claim_count = Count("claim__claim_id", distinct=True))\ .annotate(claim_bill_sum = Sum("bill_sum"))\ .values("claim__body_part", "claim_count", "claim_bill_sum")\ .order_by("claim__body_part") When I checked the query property, it was grouped by all properties of the tables related in this query, not only the ones selected in the values() function, when I only wanted to group by claim__body_part. As I searched for a way to change the group by instruction, I found the query.set_group_by() function, that when applied, fixed the query in the way I wanted: claim_query.query.set_group_by() SELECT "CLAIM"."body_part", COUNT(DISTINCT "claim_bill_sum"."claim_id") AS "claim_count", SUM("claim_bill_sum"."bill_sum") AS "claim_bill_sum" FROM "claim_bill_sum" INNER JOIN "CLAIM" ON ("claim_bill_sum"."claim_id" = "CLAIM"."claim_id") WHERE "CLAIM"."lob_id" IN (SELECT U0."lob_id" FROM "LOB" U0 WHERE U0."client_id" = 1) GROUP BY "CLAIM"."body_part" ORDER BY "CLAIM"."body_part" ASC But I couldn't find any information in Django documentation or anywhere else to better describe how this function works. Why the default group by is selecting all properties, and how .set_group_by() works, selecting exactly the property I wanted? -
NoReverseMatch: Reverse for 'account_confirm_email' not found. [dj-rest-auth]
I am new to Django. I'm trying to implement jet authentication along with social authentication. I'm following this tutorial https://jkaylight.medium.com/django-rest-framework-authentication-with-dj-rest-auth-4d5e606cde4d I tried to implement the same but its not working. I'm getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'account_confirm_email' not found. 'account_confirm_email' is not a valid view function or pattern name. My project level urls.py from drf_spectacular.views import ( SpectacularAPIView, SpectacularSwaggerView ) from django.contrib import admin from django.urls import path, include urlpatterns = [ # path('account/', include('allauth.urls')), path('admin/', admin.site.urls), path('api/user/', include('user.urls')), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path( 'api/docs/', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs' ), ] My App level urls.py from django.urls import path, re_path from dj_rest_auth.registration.views import RegisterView, VerifyEmailView, ConfirmEmailView from dj_rest_auth.views import LoginView, LogoutView from user import views app_name = 'user' urlpatterns = [ path('account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), path('register/', RegisterView.as_view()), path('login/', LoginView.as_view()), path('logout/', LogoutView.as_view()), path('verify-email/', VerifyEmailView.as_view(), name='rest_verify_email'), path('account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), path('listusers/', views.ListUsers.as_view(), name='list-users'), ] When I try to register a user. It causes this error. I'm using dj-rest-auth package to implement authentication. -
how to solve unusual logical error in django
So I made this transaction process that will pass with the help of phone number. But the logic is not working properly. sender side is deducting way more numbers that i want to send. for example, if i want to send 100, it's deducting 500 and receiver is not receiving the amount. can anyone help me with this? models.py class extenduser(models.Model): ID= models.IntegerField(null=True, default=None) FirstName= models.CharField(max_length= 50) MiddleName= models.CharField(max_length=50) LastName= models.CharField(max_length=50) phone= models.CharField(max_length=20) user= models.OneToOneField(User, on_delete=models.CASCADE) class Status (models.Model): user_name = models.CharField(max_length=150, default=None) account_number = models.IntegerField() balance = models.IntegerField() phone_number= models.CharField(max_length=20,default=None) class MoneyTransfer(models.Model): enter_your_user_name = models.CharField(max_length = 150, default = None) enter_the_destination_account_number = models.IntegerField() enter_the_destination_phone_number=models.CharField(max_length=20, default=None) enter_the_amount_to_be_transferred_in_INR = models.IntegerField() views.py def randomGen(): # return a 6 digit random number return int(random.uniform(100000, 999999)) def index(request): try: curr_user = Status.objects.get(user_name=request.user) # getting details of current user except: # if no details exist (new user), create new details curr_user = Status() curr_user.account_number = randomGen() # random account number for every new user curr_user.balance = 0 curr_user.user_name = request.user curr_user.phone_number= extenduser.phone curr_user.save() return render(request, "epayapp/index.html", {"curr_user": curr_user}) def TransferMoney(request): if request.method == "POST": form = forms.MoneyTransferForm(request.POST) if form.is_valid(): form.save() curr_user = models.MoneyTransfer.objects.filter(enter_your_user_name=request.user).first() dest_user_acc_num = curr_user.enter_the_destination_account_number dest_phone_num= curr_user.enter_the_destination_phone_number temp = curr_user # NOTE: Delete this … -
How do I create a cookiecutter project for Django 4.x instead of the default 3.x?
I want to start a new django project with cookiecutter and would like to leverage the Django 4.0+ for it. Is this supported with cookiecutter, or is there a reliable workaround for it? -
django nested Prefetch with to_attr not working
so i have this kind of queryset: prods = Product.objects.prefetch_related( Prefetch( 'packs', queryset=Pack.objects.all(), to_attr='my_packs'), Prefetch( 'packs__orders', queryset=Order.objects.all(), to_attr='my_orders') ) pack has a foreign key to product, and pack with order has a m2m relation. so this prods[0].my_packs works. but there is no attribute called my_orders in my qs -> prods[0].my_orders why does this happen? and how can i make this work? -
django objects.create method is too slow How to make faster?
multiple tables are mapped and, when I create post request, it takes about 2~3 seconds. Is there any ways to fix it? I guess it takes a long time on: objects.create for loop product.objects.get however, I am not able to find the better ways.. models: #product, Order, OrderItems, ShippingAddress are mapped class Order(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) order_date = models.DateTimeField(auto_now=True) is_paid = models.BooleanField(default=False) paid_at = models.DateTimeField(auto_now=False, null=True, blank=True) delivery_code = models.CharField(max_length=255, null=True, blank=True) is_delivered = models.BooleanField(default=False) delivered_date = models.DateTimeField(auto_now=False, null=True, blank=True) total_price = models.DecimalField(max_digits=7, decimal_places=2, null=True) shipping_price = models.DecimalField(max_digits=7, decimal_places=2, null=True) payment_method = models.CharField(max_length=255,null=True) def __str__(self): return str(self.user) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete= models.CASCADE, null=True, blank=True) product = models.ForeignKey(Product, on_delete= models.CASCADE) name = models.CharField(max_length=200, null=True) image = models.CharField(max_length=255, null=True) qty = models.IntegerField(default=0, null=True) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) def image_preview(self): if self.image: return mark_safe('<img src="{0}" width="55" height="55" />'.format(self.image)) else: return '(No image)' def __str__(self): return str(self.product) class ShippingAddress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) order = models.OneToOneField(Order, on_delete=models.CASCADE, null=True, blank=True) address = models.CharField(max_length=255, null=False) city = models.CharField(max_length=255, null=False) postal_code = models.CharField(max_length=255, null=False) country = models.CharField(max_length=255, null=False) def __str__(self): return str(self.user) view: @permission_classes(IsAuthenticated) @api_view(['POST']) def OrderCreate(request): data = request.data user = request.user order_items = data['orderItems'] #1.create order order = Order.objects.create( user … -
Django serializers.save() does not use postgres
I have the following function that runs automatically with cronjob, it makes predictions based on an anomaly detection model and it saves the results to a postgres database: def prediction_job(): """ This job will run once every batch_minutes minutes to predict if the IPs appear in these batch_minutes minutes are normal or malicious and save the results to postgres """ ip_estimator = IpStatePrediction() predictions = ip_estimator.predict_ip_state() predictions_dict_final = convert_dict_for_serializer(predictions) serializer_result = PredictionsSerializer(data=predictions_dict_final) if serializer_result.is_valid(): serializer_result.save() else: logger.debug("Error with data {}.".format(serializer_result.errors)) When I run it locally after running the commands python3 manage.py runserver and python3 migrate --database postgres, it saves the results to postgres. However on production I am getting the following error, when the function is executed: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: unrecognized token: ":" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 108, in debug_sql yield File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File … -
module 'django.contrib.admin' has no attribute 'action' this code is copied from the docs
from django.contrib import admin from .models import Post @admin.action(description="Publish selected Posts") def make_publish(modeladmin,request,queryset): queryset.update(status="published") -
Django FileField reading big CSV files effectively
Lets say that I have model that contains csv files: class MyModel: my_file = model.FileField(...) I can read my csv file data like this right now: import csv csv_data = self.my_file.read().decode('utf-8') reader = csv.reader(csv_data.splitlines()) However this method is not effective. It literally loads whole file into memory and tries to work with them. My CSV files are very big (more than 100MB) and they are hosted on S3 service. Is there any effective way to parse CSV data? -
Celery executes the task but not reflects them in the celery logs. Why?
For eg it runs perfect the first time but if we try to run the same thing again so if it ran 3 tasks at first it will show only 1 of them (first or last of the three). But will execute all of them. The command use to run celery here is celery -A project worker -B -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler The logs in the celery looks like for the first time task received 1 task received 2 task received 3 For the second time it may be task received 3 or task recevied 1 #either of these 2 But will still execute all three of them. So what may be the thing preventing them -
Why this signal is not working as expected?
I would appreciate some help. Does anyone know why this signal is only being triggered only when the "xp value" is different from the one that already exist ? so eg. if a UserLeaderboardTracking objects already exist for that user with the value 10 the it won't create it otherwise it will . def create_user_leaderboard_tracking(sender, instance, *args, **kwargs): if instance.xp_collected == 0: pass else: UserLeaderboardTracking.objects.get_or_create(user=instance.user, xp_value=instance.xp_collected) -
Is `python_paths` a correct parameter for pytest.ini
I'm working on an undocumented Django application, as a new team (all previous developper went away , so no help is available) The pytest.ini looks like this : [pytest] python_paths = my_app According to pytest documentation, there is no python_paths option, only pythonpath. The tests are working fine by now, and I don't know what to do : Keep that option, it may somehow be used Rename to pythonpath, like it should always has been Delete, as it is unused anyway (I tested, it works fine without) I know StackOverflow isn't meant for opinions, I'll try to find a lead dev at my company for that. I'm just looking for confirmation that i'm not missing an usage -
I am having problem with installing SSL Certificate on my ubuntu server running on apache2
I have SSL Certificate, namecheap enabled it, and now I am trying to install it on my ubuntu server running on Apache2. I have my django project setup, and logs are showing that is django/Python side problem. logs. When I am running apache2 on port 80 it works completely fine. sites-available SSL config: ssl-config sites-available http config: http-config -
Django: how to override textarea globally with custom class?
I'm trying to override widgets (like textarea) globally in Django. For this, I defined my own django/form/widgets/textarea.html file. First, I wanted to modify the default number of rows. The textarea.html file will looked like this: <textarea rows="3" name="{{ widget.name }}" {% include "django/forms/widgets/attrs.html" %} >{% if widget.value %}{{ widget.value }}{% endif %}</textarea> This example above works perfectly. But what if I want to add a custom class now? <textarea rows="3" class="my-custom-class" name="{{ widget.name }}" {% include "django/forms/widgets/attrs.html" %} >{% if widget.value %}{{ widget.value }}{% endif %}</textarea> This won't work as expected because the attrs.html is supposed to handle extra attributes like class. Hence, defining a class attribute directly in textarea would break this behaviour and would erase existing classes. What is the "clean" way to add extra classes globally? I'd like to do it in HTML, not in Python. For example, I don't want to define a new Widget which would inherit from the base widget when I'm defining my forms, as I think this is pure markup topic, and should not interfere with form definition itself. Thanks. -
Django Meta class abstract changing from True to False
I understand that when a class inherits from an Abstract Django Model, it will not inherit the meta attribute abstract = True, which makes sense. However in the below example nothing has inherited from it, but yet it's Meta.abstract is False even though its defined to be True: from django.db import models from django.db.models.base import ModelBase class MyMeta(ModelBase): def __new__(cls, name, bases, attrs, **kwargs): Class = super().__new__(cls, name, bases, attrs, **kwargs) if not Class.Meta.abstract: print(Class) print('Class.Meta.ordering:', Class.Meta.ordering) # Sanity check print('Class.Meta.abstract:', Class.Meta.abstract) if not hasattr(Class, 'foo'): raise NotImplementedError('Please add a foo attribute') return Class class MyAbstractModel(models.Model, metaclass=MyMeta): name = models.CharField(max_length=250) class Meta: abstract = True Prints: <class 'myapp.models.base.MyAbstractModel'> Class.Meta.ordering: -name Class.Meta.abstract: False -
Django & Authorization Bearer Token
I'm working on Django for an app refrencial on job. I want to get data from an API Pole Emploi. I'm register on the web site, I got a client_id, client_secret etc. I do a get request to get my access_token. def login_explo_metier_pole_emploi(): params = { 'grant_type': 'client_credentials', 'client_id': 'XXX', 'client_secret': 'XXX', 'scope': 'api_explorateurmetiersv1 explojob' } header = { 'Content-Type': 'application/x-www-form-urlencoded' } url_co = 'https://entreprise.pole-emploi.fr/connexion/oauth2/access_token?realm=%2Fpartenaire' req_co = requests.post(url_co, params, header) wb = req_co.json() access_token = wb['access_token'] print('reponse: ', wb) return access_token That's working. After, I want on my view, get datas, but here, it's not working : def get_rome(param): access = login_explo_metier_pole_emploi() print('acces avec: ', access) params = request.META.get('HTTP_AUTHORIZATION', f"Bearer {access}") url = f"https://api.emploi-store.fr/partenaire/explorateurmetiers/v1/explorateurmetiers?libelle={param}&nombre=20&type=metier" req = requests.get(url, params) return req It's returned an 401 error (Unauthorized). Can someone help me please? -
Django how to create a tmp excel file and return it to the browser within the response
I have a process to build a tmp file and then return it to the browser in csv. Now i want to do the same but return a excel file. So what i have for the csv is a view in django that does: def export_wallet_view(request): tmp = tempfile.NamedTemporaryFile(delete=False) with open(tmp.name, 'w', encoding="utf-8-sig") as fi: csv_headers = [ 'Id', 'Name' ] fi.write(';'.join(csv_headers)) fi.write('\n') //here also i save the rows into the file response = FileResponse(open(tmp.name, 'rb')) response['Content-Disposition'] = 'attachment; filename="wallet.csv"' return response So to convert it to excel i try to do something like this using pandas: df = pd.read_csv(tmp.name) df.to_excel('pandas_to_excel.xlsx', sheet_name='new_sheet_name') The problem is that this creates the excel in the server, and i would like to do something like: df = pd.read_csv(tmp.name) df.to_excel('pandas_to_excel.xlsx', sheet_name='new_sheet_name') //this being a tmp file response = FileResponse(open(tmp.name, 'rb')) //this should be the new excel tmp file response['Content-Disposition'] = 'attachment; filename="wallet.csv"' return response Thanks