Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display text in html from Django as it is typed in textbox
I want to display the text in HTML from Django in proper format. i.e. Proper space, line break, etc. I used <p>{{blog.main_content}}</p> This is the screenshot of data added The text displaying in webpage Please help me to figure it out. How can I display this text in a proper format? -
Not allowed to load local resource in Django (Images)
I'm trying to load multiple images using Django rest API but getting the error as - Not allowed to load local resource. the setting of app is - STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have checked multiple solution on google but is this due to chrome or Django? Can anyone help here please. NOTE: The call of the API is giving 200 response but only rendering is not happening. Thanks!! -
DRF+Axios: some requests fail with `ERR_NETWORK` or `ERR_BLOCKED_BY_CLIENT`
This is not a question, more like an answer to this common problem. I have a Dashboard built with NextJs and Django+DRF and i am using axios as a HTTP Client. i have noticed that some of my requests go through, and some do not (mainly the requests that fetch for example monthly/yearly payments/expenses of the company). Down below you'll find the solution to this problem. -
Django SetPasswordForm heritage doesn't work
I want to inherit from the built-in Django SetPassWordForm which is class SetPasswordForm(forms.Form): """ A form that lets a user change set their password without entering the old password """ error_messages = { "password_mismatch": _("The two password fields didn’t match."), } new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get("new_password1") password2 = self.cleaned_data.get("new_password2") if password1 and password2: if password1 != password2: raise ValidationError( self.error_messages["password_mismatch"], code="password_mismatch", ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user by providing a custom class to the fields: class CustomSetPasswordForm(SetPasswordForm): def __init__(self, *args, **kwargs): super(CustomSetPasswordForm, self).__init__(*args, **kwargs) new_password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) new_password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) But the template doesnt render it: # user/authentication/password_reset_new.html <div class="password-wrapper field-wrapper mb-4"> <div class="tag pl-1">{{ form.new_password1.label }}*</div> <div class="input text-woys-purple">{{ form.new_password1 }}</div> </div> <div class="password-wrapper field-wrapper mb-4"> <div class="tag pl-1">{{ form.new_password2.label }}*</div> <div class="input text-woys-purple">{{ form.new_password2 }}</div> </div> # urls.py # Set new password path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(template_name='user/authentication/password_reset_new.html', form_class=CustomSetPasswordForm), name='password_reset_done'), -
How to send variables from view.py to a signal in Django
i want django to create a ServerModeratorPermission object just after the user has been set as the moderator of the server views.py: class ModeratorSettingsView(LoginRequiredMixin, View): form_class = AddModeratorForm ... def post(self, request, server_tag): form = self.form_class(request.POST) user = User.objects.get(pk=request.POST.get('user')) server = Server.objects.get(tag=server_tag) moderators = server.moderator_of.exclude(user=server.creator) ServerModerator.objects.get_or_create(user=user) moderator = ServerModerator.objects.get(user=user) moderator.server.add(server) return render(request, 'servers/moderator-settings.html', {'moderators':moderators, 'server':server, 'form':form}) signals.py: @receiver(post_save, sender=ServerModerator) def give_default_permission(instance, *args, **kwargs): # i need server_tag for this query # server = Server.objects.get(tag=server_tag) moderator = ServerModerator.objects.get(pk=instance.id) ServerModeratorPermission.objects.create(moderator=moderator, server=server) is there anyway to send server_tag that being used in the view class to the signal? -
Avoid serializer from returning double titles for relation serializer
I have these serializers serializer 2 has a relational field to serializer 1 serializer 1 class ExerciseSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) subject = serializers.SlugRelatedField(read_only=True, slug_field="title") topic = TopicSerializer() class Meta: model = Exercise fields = ["id", "subject", "topic", "questions"] serializer 2 class ExerciseTokenSerializer(serializers.ModelSerializer): exercise = ExerciseSerializer() class Meta: model = ExerciseToken fields = ["exercise", "completed", "score"] this results in a nested "exercise" were I have to access the data by "exercise.exercise", looking at the results below will better explain the issue: { "etoken": 30, "exercise": { "exercise": { ... "completed": false, "score": 0 } } this is how I want it to output { "etoken": 30, "exercise": { ... "completed": false, "score": 0 } } How is this achievable? I couldn't a solution in the docs or here in stack overflow. Thanks. -
Create an API server using Django/FastAPI/Flask and create the following APIs that return this data as JSON in various different ways
https://docs.google.com/document/u/0/d/1BYRJAEI-5aSsQSlHB4BBmvCnKCORPwCGr0ewLvr1f_o/edit?usp=sharing create an API server using Django/FastAPI/Flask and create the following APIs that return this data as JSON in various different ways. All the details of project are given in link. -
Filter model assigned to user , ManyToManyField - Django
new to django and I am finding it hard to know what to search and what questions to ask sooo....here it goes... I have a model named Obiectiv to which I have assigned users in the admin panel using manytomanyfield. models.py: class Obiectiv(models.Model): numeObiectiv = models.CharField(max_length=250) color = models.CharField(max_length=6, choices=COLOR_CHOICES, default='green') user = models.ManyToManyField(User) I want that when the user is logged in, he is able to see only the models that have been assigned to him: views.py @login_required def home(request): obiective = Obiectiv.objects.all() return render(request, 'home.html', context={"obiective":obiective}) With the code in the views.py it display all the Obiectiv models. home.html {% for obiectiv in obiective %} <div class="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="card rounded-0 shadow border-primary text-start summary-card my-3"> <div class="card-body"> <div class="d-flex w-100"> <div class="col-8 pe-2"> <div class="summary-title fs-5 border-bottom">Total Categories</div> <div class="summary-count text-end fw-bolder mt-3 px-4">{{ obiectiv.numeObiectiv|intcomma }}</div> </div> <div class="col-4"> <div class="summary-icon p-3 rounded border text-center bg-gradient bg-light"> <i class="fa fa-list"></i> </div> </div> </div> </div> </div> </div> {% endfor %} thank you in advance. -
Design DB to calculate prize based on distance of cities
I am working on a side project to calculate the prize of the service based on the city distances. In my prize table I have values like below: CATEGORY DISTANCE VALUE Category A < 100 km 10EUR Category A From 100 km to 300 km 50 EUR Category A > 300 km 100 EUR My idea is to prepare a DB structure like below: CATEGORY DISTANCE_FROM DISTANCE_TO VALUE Category A 0 100 10 Category A 100 300 50 Category A 300 x 100 Is this the right approach? I am also wondering how to later get the correct value if for example distance is 150 km? The project will be build in Django, any help appreciated. -
IIS django static files not showinvg
i try to deploy my Django app on IIS for work but is not serving my static files. i watched this tutorial: https://www.youtube.com/watch?v=APCQ15YqqQ0. Right now my Django app looks like this, the CSS is not appearing I added a virtual directory as well and have set the physical path to the static file in the project. In my my settings.py i have STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] I have no idea what i am missing. please tell me if you need more information. -
Django login_required doesn't work with multiple gunicorn workers
So I have a project which contains multiple micro-services, the entry point is the Django micro-service(with user login & authentication). All other Apis are wrapped with the @login_required decorator by Django. I've deployed it using ngnix, gunicorn inside a kubernetes pod. Everything works fine with 1 worker(sync) but I obviously want multiple workers, so when I increase my number of workers and threads(gthread), it doesn't let me login redirects to login/?next=/login/5/. After spending some time, I figured out the following: Since the default value of keepalive of a worker is 2s, the worker closes connection and a new worker is assigned & since they don't share common memory,my session cookie isn't carried forward. I tried increasing the keepalive time to 10s , now it lets me login but if someone tried to login when the worker is about to expire(around 10s), same, doesn't login & redirects to login/?next=/login/5/. Another direction I found was about fixing the secret key as in this post, but I just using the default standard value which I even hardcoded in settings.py, but no luck. I'll attach my gunicorn config/logs below: config: ./gunicorn.conf.py wsgi_app: None bind: ['0.0.0.0:8000'] backlog: 2048 workers: 2 worker_class: sync threads: 4 worker_connections: … -
How to gain specific field value manually in django admin fieldsets
I'm overriding admin/includes/questions/fieldset.html to change the behavior of some fields using the JavaScript. In the orignal fieldset.html by django theres a loop to display the fields, But I want to pick the value of first field for some usecase. How can I do that {% for line in fieldset %} <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} {% for field in line %} <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} {% if field.is_checkbox %} {{ field.field }}{{ field.label_tag }} {% else %} {{ field.label_tag }} {% if field.is_readonly %} <div class="readonly">{{ field.contents }}</div> {% else %} {{ field.field }} {% endif %} {% endif %} {% if field.field.help_text %} <div class="help"{% if field.field.id_for_label %} id="{{ field.field.id_for_label }}_helptext"{% endif %}> {{ field.field.help_text|safe }} </div> {% endif %} </div> … -
The form for UpdateView for editing the user profile is not displayed. Django
I'm trying to make an UpdateView to edit user profile without pk or slug using get_object() with self.request.user. But when I run my settings, the form is not shown. Here is my code: urls.py: urlpatterns = [ path('settings/', UserSettings.as_view(), name='settings'), path('<slug:profile_slug>/', ShowUserProfile.as_view(), name='profile'), ] views.py: class UserSettings(LoginRequiredMixin, DataMixin, UpdateView): template_name = 'users/user_settings.html' form_class = UpdateUserForm def get_object(self, *args, **kwargs): return self.request.user def get_success_url(self): return reverse_lazy('profile', kwargs={'profile_slug': self.request.user.userpofile.slug}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context(title='Settings') forms.py: class UpdateUserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password') widgets = {'username': forms.TextInput(attrs={'class': 'form-control form-input form__input'}), 'password': forms.TextInput(attrs={'class': 'form-control form-input form__input'})} user_settings.html: <form class="form" method="post"> {% csrf_token %} {% for item in form %} <div class="row"> <div class="col-sm-4"> <label class="form__label" for="{{item.id_for_label}}">{{item.label}}: </label> </div> <div class="col-sm-8"> {{item}} </div> </div> <div class="form__errors">{{item.errors}}</div> {% endfor %} <button class="button" type="submit">Set settings</button> </form> It doesn't even throw an error. What I need to do? -
why django displaying inconsistant migration history error while migrating?
hope you are doing well, i am beginner to the django and python, encountered the error while practicing projects from the github which is the custom user model project. i have posted a code below. feel free to ask if you have any questions. i have posted a question in this StackOverflow website to find the solution to the issue. please solve the issue. Thanks a lot for your help. temp/settings.py """ Django settings for temp project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-&ttc6c6nmvo(t0j-@0=ybd$61t(k#yo)*-e2%*5!xm@29+rfv=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tempapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'temp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
How to properly bind a Django form?
I am working on a form that picks a Sale id and submits it to the server. When i submit it to the server a bind it using form = DeleteSalesForm(request.POST) and check it form.is_bound returns False. This is my views.py def delete_sales(request): if not request.user.is_authenticated: return redirect('/login') if request.method == 'GET': form = DeleteSalesForm() print("GET") return render(request, 'inventorymanagment/delete_sales.html', {'form': form}) form = DeleteSalesForm(request.POST) print("checking if form is valid", request.POST, form.is_bound, form) if form.is_valid(): form.delete_sale() # redirect return redirect('/') else: print("sale not deleted") # why is the form invalid? print(form.errors) return render(request, 'inventorymanagment/delete_sales.html', {'form': form}) Here is the traceback: [31/Aug/2022 15:38:36] "POST /delete_sales HTTP/1.1" 200 932 checking if form is valid <QueryDict: {'csrfmiddlewaretoken': ['q3aga7bySuscQ6bb9zrh3pFUlfoIoRoGQnHvQQ8LlbiEfUl1XDSGp2fk3nCj5KJk'], 'id': ['16']}> False <tr> <th><label for="id_id">Sale:</label></th> <td> <select name="id" id="id_id"> <option value="16">id: 16, iphone 6 quantity: 50 price: 30.00 day: 2022-08-31</option> <option value="17">id: 17, Iphone 8 quantity: 70 price: 80.00 day: 2022-08-31</option> </select> </td> </tr> sale not deleted why isn't the form validating? -
Python: Update dictionary with multiple variables?
I've got this code: def update_amounts(self): container = {} a = {'a': self.a_amount} if self.a_mount or self.a_amount is None else {'': ''} container.update(a) b = {'b': self.b_amount} if self.b_amount or self.b_amount is None else {'':''} container.update(b) c = {'c': self.c_amount} if self.c_amount or self.c_amount is None else {'':''} container.update(c) return container And I wanted to know if its possible to do the dict update more efficient than calling the update function three times? Thanks in regard! -
It is shown that value error.. how to figure it out?
@csrf_exempt def login(request): if 'email' in request.session: return redirect(home) if request.method=="POST": email = request.POST["emailOrPhone"] password = request.POST["password"] user=authenticate(email=email,password=password) if user is not None: request.session['email'] = email if (User.objects.filter(email=email).exists()): request.POST.get(User.objects.get(password).only()) if password==User.objects.get(password): return JsonResponse({'statuscode':200}) else: return JsonResponse({'statuscode':400,'message':'password mismatch'}) else: return JsonResponse({'statuscode':400,'message':'not enrolled'}) else: print('invalid credentials') else: return JsonResponse({'statuscode':200}) -
Converting a static HTML website into a fully fledged Django project
I am just getting started with Django. I have a situation where I have a project consisting of a large number of static HTML Pages compiled over time. Now I am in a situation to use a framework and I have opted for it. However I can't just write the whole project in Django because the large number of pages is being a problem for me and my team. As you know maintaining each one is a tedious task and not practical at all for me. So if anyone could suggest a tool or a script to convert entire static website into a Django project will save me a lot of time. Every solution is appreciated. -
Azure B2C : Error in the callback after the edit profile when it tries to get a new token
I try to implement an azure B2C authentication in Django. Unfortunately, there is not much documentation in Django on this topic. However, I managed to write the functions and views to get an id_token and store the user's information in the session. I wanted to integrate the edit profile with the specific authority. The page is perfectly redirected to update the user information. However, after the validation of the new data, I get an error message in the callback when I try to get a new token (function _get_token_from_code). {'error': 'invalid_grant', 'error_description': 'AADB2C90088: The provided grant has not been issued for this endpoint. Actual Value : B2C_1_signupsignin_20220810 and Expected Value : B2C_1_profileediting\r\nCorrelation ID: xxxxxxxxxxx nTimestamp: 2022-08-31 14:58:54Z\r\n'} So it implies the following error in the python execution : _store_user(request, result['id_token_claims']) KeyError: 'id_token_claims' However the new information of the user are correctly saved in the azure. Since I am newbee in this authentication process ? Do we need to generate a new token for the edit profile user flow ? Where does come from this mistake ? Here is the code in djnago : load_dotenv() def initialize_context(request): context = {} # Check for any errors in the session error = request.session.pop('flash_error', … -
How to compute cumulative sum of a count field in Django
I have a model that register some kind of event and the date in which it occurs. I need to calculate: 1) the count of events for each date, and 2) the cumulative count of events over time. My model looks something like this: class Event(models.Model): date = models.DateField() ... Calculating 1) is pretty straightforward, but I'm having trouble calculating the cumulative sum. I tried something like this: query_set = Event.objects.values("date") \ .annotate(count=Count("date")) \ .annotate(cumcount=Window(Sum("count"), order_by="date")) But I'm getting this error: Cannot compute Sum('count'): 'count' is an aggregate -
for loop in html gives me the same id
When I click the span on html I cant make variable span id with id="mylink-${i}" I couldn't get this with var mylink = document.getElementById("mylink-"+id) in javascript part. and also at onclick="theFunction(i)" console gives me i is not defined error but it should be defined because of {% for i in data %} i is one of the elements of data how can ı solve this <div class="row sideBar"> {% for i in data %} <div class="row sideBar-body"> <div class="col-sm-9 col-xs-9 sideBar-main"> <div class="row"> <a href= "{% url "start_chat" i.room %}" onclick="theFunction(i)" > <div class="col-sm-8 col-xs-8 sideBar-name"> <span class="name-meta" id="mylink-${i}"> {{i.name}} </span> </div> </a> </div> </div> </div> {% endfor %} </div> const rooms = JSON.parse(document.getElementById('data').textContent) function theFunction(id) { var mylink = document.getElementById("mylink-"+id) } -
Django date events
I have this model: class Prognose(models.Model): Benutzer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) Lehrer_Vorname = models.CharField(max_length=255, null=True, blank=True) Lehrer_Nachname = models.CharField(max_length=255, null=True, blank=True) von_Datum = models.DateField(null=True, blank=True) Status = models.CharField(max_length=20, null=True, blank=True) Stunden = models.CharField(max_length=20, null=True, blank=True) bis_Datum = models.DateField(null=True, blank=True) Erstellt_Datum = models.DateField(null=True, blank=True) def __str__(self): return '{}'.format (self.Benutzer) The idea is to schedule an event or a task from one date to another date, and filter those out Like so Employee Name, from 2022-2-2 do this to 2022-3-3 else default (something else without date) and then when I user a filter, I want that it shows either past events within given date or default in future events if date is greater then the event date. Or the current event within given date I saw a lot of examples but have no clue how to implement it into my thing my view class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' my template {% for Ansicht in Ansicht.prognose_set.all %} {{Ansicht.Lehrer_Vorname}} {{Ansicht.Lehrer_Nachname}} {{Ansicht.von_Datum}} {{Ansicht.Status}} {{Ansicht.Stunden}} {{Ansicht.bis_Datum}} {{Ansicht.Erstellt_Datum}} thought about ifs and so on but there must be something more efficient -
How to send email using smtp django rest framework after google policies are updated [closed]
I used the old techniques it did'nt work because gmail disabled Less secure apps features i am trying to send an verification email with django rest framework by smtp if there are any alternatives please help This is the old method in django to send email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_USE_TLS=True EMAIL_HOST_USER=os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD=os.environ.get('EMAIL_HOST_PASSWORD') -
POSTing large number of many-to-many relatedfields in django rest framework
I am building an inventory-like system using Django Rest Framework where I have two models (Category and Location) that I want to allow Users to add to their Filters to keep an eye of them. #models.py class Category (models.Model): code=models.CharField(max_length=10, unique=True) name=models.CharField(max_length=50) class Location (models.Model): code=models.CharField(max_length=10, unique=True) name=models.CharField(max_length=50) class Filter (models.Model): categories = models.ManyToManyField(Category) locations = models.ManyToManyField(Location) name = models.CharField(max_length=50) user = models.ForeignKey(User) I am using ModelSerializers and built-in ModelViewSets. #serializers.py class UserFilterSerializer(serializers.ModelSerializer): categories = serializers.SlugRelatedField( queryset=Category.objects.all(), many=True, slug_field='code', allow_empty=False) location = serializers.SlugRelatedField( queryset=Location.objects.all(), many=True, slug_field='code', allow_empty=False) user = serializers.HiddenField( default=serializers.CreateOnlyDefault(default=serializers.CurrentUserDefault())) class Meta: model = UserTenderSelection fields = ['id', 'categories', 'locations', 'name', 'user'] #views.py class UserFilterView(ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = UserFilterSerializer pagination_class = None def get_queryset(self): return self.request.user.filter_set.prefetch_related("categories", "locations").all() I would like the users to be able to CRUD their filters using REST methods. However, rather than using ids, I needed at some point to use the codes of Category and Location when both on GET responses and POST/PUT requests. e.g. //Example GET Response: { "id": 55, "categories": [ "88-9", "72-3", ], "locations": [ "BE0", "BE1", "DE12" ], "name": "Filter1" } //Example POST request: { "categories": [ "87-9", "77-1", ], "locations": [ "SP75", "DE20" ], "name": "Filter3" } My … -
Django httpResponse open pdf then print window in navigator
I'm running a django app in which i created a view to open a pdf file in the browser for printing purpose. Until this, everything works fine. For a better UX, i'm trying to automatically open the print window (specific to each computer). However, i'm struggling to do so. Aas long as the new window open a pdf but not a html file , i cannot insert JS in my code... Any idea to do so ? Here is my code (i deleted the intermediate steps where i combine some pdfs or add blank page for recto/verso printing...) class CombinePdf (View): def post(self, request, *args, **kwargs): response = HttpResponse(content_type='application/pdf') response['Content-Transfer-Encoding'] = 'binary' file = open("my_pdf.pdf", 'rb') # generate pdf in response try: file.write(response) except Exception as e: return e #open pdf in new window return response Thanks for your help !