Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to show a specific customers balance in a panel
I want to show a specific customers balance in a panel for that I want to fetch the specific customers balance and want to show it in a page or somewhere else.Like this example: user 1 has 100$ and user 2 has 200$ so when user 1 will login the page will show 100$ and when user 2 login he will be shown 200$.But I am confused here to complete this task.How can I do this ? I have a coin var which is working as a balance. Here is my Model for Customer : class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100) coin = models.FloatField(null=True, blank=True) def __str__(self): return self.phone_number def register(self): self.save() def get_customer(phone_number): try: return Customer.objects.get(phone_number=phone_number) except: return False -
Django-import-export export also related field of a model
In my project i have a model like this: models.py class e_cart(models.Model): e_uid = models.ForeignKey(User, on_delete=models.CASCADE, ) e_prodid = models.ForeignKey(p_prodotti, on_delete=models.CASCADE, verbose_name="Product") e_qta = models.IntegerField(default=0, verbose_name="Quantita") e_datain = models.DateTimeField(auto_now=True, verbose_name="Insert Data") .... I use django-import-export for export my data in admin panel and in admin.py i do: from import_export.admin import ImportExportModelAdmin class OrderAdmin(ImportExportModelAdmin): search_fields = ('onum',) list_display = ('onum', 'date', 'paid', 'onotes', 'totord', 'obank') ordering = ('-date', 'onum') Now for example the e_uid field is exported as just an id (1,2 ecc) bu i would export the select_related() filds for example e_uid.firstname, e_uid.lastname ecc How can i modify my code for export also related field of my model? so many thanks in advance -
Django-React Axios request breaks token
Everytime I do an axios request in the ComponentDidMount() for example: axiosInstance.get('/user/profile', { headers:{ "Authorization": "JWT " + localstorage.getItem('access_token') } }).then(res => { return res; }).catch(err => { console.log(err) }) OR THIS axiosInstance.get('/user/profile').then(res => { axiosInstance.defaults.headers["Authorization"] = "JWT " + localstorage.getItem('access_token'); return res; }).catch(err => { console.log(err) }) I am running a Django-React project with postgresql as my DB. I followed the guide by Toruitas on Hackernoon on how to use simple-JWT to issue my access_token and refresh_token. Everytime the axios request runs, my refresh_token becomes undefined and It just renders my whole other requests useless as my refresh_token is missing My axiosAPI - axiosInstance : import axios from "axios" import jwt from "jwt-decode" import history from "./utilities/history" const baseURL = 'http://127.0.0.1:8000/api/' const axiosInstance = axios.create({ baseURL: baseURL, timeout: '5000', headers: { 'Authorization': localStorage.getItem('access_token') ? "JWT " + localStorage.getItem('access_token') : null, 'Content-Type': "application/json", 'accept': "application/json" } }); axiosInstance.interceptors.response.use( response => response, error => { const originalRequest = error.config; // if (error.response.status === 401 && originalRequest.url === baseURL +'token/refresh/') { // history.push('/login') // return Promise.reject(error); // } if (error.response.data.code === "token_not_valid" && error.response.status === 401 && error.response.statusText === "Unauthorized") { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { // const tokenParts = … -
Deploying Serverless Django with Zappa through Terraform
I want to deploy my django project through terraform, catch is I need it to be serverless so I need to use Zappa one way or another. So far I've figured I should only use Zappa for zipping up the project for Lambda but I have no idea what else to do. I know I should basically reflect what Zappa does in deployment to terraform but I can't figure out all the things it does. Creates IAM Role Creates Permission Policy Uploads zip to s3, creates lambda Schedules keep_warm callback Uploads Gateway API Settings ? I've got the Gateway API settings in a JSON file but I do not know how to use it for deployment with terraform. What should the lambda handler be in terraform? How do I even do this in terraform? -
How to create a "field group" in django-filter to a searchbar
Good morning, I'm working on a Django site and I'm making a search bar for my site with django-filter library. It's working well but it works only with one model field. I would have a search bar that works with more field (in this case text, desc and title), how is it possible to do? Filters.py import django_filters from django_filters import CharFilter, DateFilter from .models import * class PostFilter(django_filters.FilterSet): text = CharFilter(lookup_expr='icontains') class Meta: model = Post fields = ('text', 'date') Models.py class Post(models.Model): # Post core title = models.CharField(max_length=299) author = models.ForeignKey(User,default=ANONYMOUS_USER_ID, on_delete=models.CASCADE) category = models.CharField(max_length=50) image = models.ImageField(blank=True) desc = models.TextField() text = RichTextField(blank = True, null = True ) date = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField(null = True, blank = True, unique=True) Thanks for all. -
html select value from database record in django not working
This question is asked many times, but I think I am having issues with strings in the Django template I have a select tag <select name="category" class="form-control" required="" id="id_category"> <option value="" >--------</option> {% for cat in all_categories %} <option value="{{cat}}" {% if form.instance.category == cat %} selected {% endif %}> {{cat}}</option> {% endfor %} </select> my {{cat}} variable has value 'Django Book' and {{form.instance.category}} also have same value i.e. 'Django Book'. But it doesn't select the desired option however, I am using similar logic in another part <select class="form-control" id="client" required name="client"> <option value=" ">-----</option> {% for customer in all_customers %} <option value="{{customer.pk}}" {% if form.instance.client_id.pk == customer.pk %}selected{% endif %}>{{customer}}</option> {% endfor %} </select> but this time I am comparing ids to select the default option and it works. what is the issue in the above code?? is this issue with strings?? and how can I overcome this. Also, I would like to set strings in the value attribute in the first code example. Thanks for any help. -
Django migration id char column to existing table
I am trying to create an ID charfield column and set it as primary key to an existing table. So because it is an existing table when i generate Migrations django asks me to provide a default value. What can i enter as primary key default for existing rows? If i enter a single string e.x 'abcd' i will get error for existing rows on migrate because of duplicate value -
how fix npm run dev?
Can't configure package.json, this code gives an error: "scripts": { "dev": "webpack --mode development ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend", "build": "webpack --mode production ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend" }, When I do npm run dev: (venv) awan2rist@Vladimir lead_manager_react_django % npm run dev > lead_manager_react_django@1.0.0 dev /Users/awan2rist/Dev/lead_manager_react_django > webpack --mode development ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend sh: webpack: command not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ERR! lead_manager_react_django@1.0.0 dev: `webpack --mode development ./leadmanager/frontend/src/index.js --output-path .leadmanager/frontend/static/frontend` npm ERR! spawn ENOENT npm ERR! npm ERR! Failed at the lead_manager_react_django@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/awan2rist/.npm/_logs/2020-11-24T09_20_20_637Z-debug.log -
Question about graphene-django mutation documentation
While I've been able to make my application work, I have some concerns about doing things the right way. Therefore there is something I "do not understand" : In the documentation, here, in the QuestionMutation class, there is a question attribute. What does that actually mean ? It says that it defines the response and I don't understand what this means. Code from the documentation : class QuestionType(DjangoObjectType): class Meta: model = Question class QuestionMutation(graphene.Mutation): class Arguments: # The input arguments for this mutation text = graphene.String(required=True) id = graphene.ID() # The class attributes define the response of the mutation question = graphene.Field(QuestionType) @classmethod def mutate(cls, root, info, text, id): question = Question.objects.get(pk=id) question.text = text question.save() # Notice we return an instance of this mutation return QuestionMutation(question=question) And in my code I've been able to do this : My type : class UserType(DjangoObjectType): class Meta: model = User fields = ( 'id', 'username', 'password', 'email', 'first_name', 'last_name', 'is_active', 'group_ids', ) full_name = graphene.String() # Python property full_identification = graphene.String() # Python property My mutation : class UpdateUser(graphene.Mutation): # --------> I could comment these and no problem. Why ? <-------- # id = graphene.ID() # username = graphene.String() # email … -
Django is Inserting Record instead Of Updating
I am trying to perform crud operations but when i try to update then django add's a new row in the db with the new pk 'id'. I am using autofield set to primary_key = True(default). @login_required def edit(request,id): note = UserCreatedNote.objects.filter(pk=id,user=request.user) if request.method == 'POST': form = AddNoteForm(request.POST,note[0]) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user //cause i have excluded this field in form. form_data.save() form = AddNoteForm(instance=note[0]) context={'note':note[0],'u_form':form} return render(request,'edit_note.html',context) Models.py class UserCreatedNote(models.Model): user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) note_title = models.CharField(default='',max_length=100,blank=True,null=True) note_tags = models.CharField(default='',max_length=20,blank=True,null=True) note_contents = RichTextField(default='',max_length=1000,blank=True,null=True) creation_time = models.DateTimeField(auto_now_add=True) last_modified_time = models.DateTimeField(auto_now=True) class Meta: ordering = ['creation_time',] def __str__(self): return str(self.user) -
Not able to create Django model in Celery task
@shared_task def create_request(self, par1, par2, par3, par4): print("Task Initiated") urequest = askrequest(par1= par1, par2 = par2, par3 = par3, par4=par4) urequest.save() return urequest Here I am creating and saving my request model instance and returning newly created instance back to the caller. But System throws error of Bad Request always. If i do same without celery task it works fine. -
How to call a function in django views?
def categories_list(request): categories_in_nav = Category.objects.all() return render(request, 'partials/navbar.html', {'categories': categories_in_nav}) def homepage_view(request): categories_in_nav = categories_list(request) # it is returning <HttpResponse status_code=200, "text/html; charset=utf-8"> instead of queryset. ....... return render(request, 'main/home.html', context} In home.html, partials/navbar.html is included because of some reasons. In the navbar.html there will be a list of categories but how can I render them in home.html? I am thinking of using the context_processors which will work but is it a good to use context processors in such cases also ? Is there any other way except context_processors. -
django.db.utils.ProgrammingError: column "Price" of relation "ogs_features_product" does not exist
I am currenltly running django 3.1 I am trying to migrate my models.py file to postgres database. I was able to makemigrations, but when I did python manage.py migrate I got the following error. Previously, I had a "Price" table which included "Product_ID" of "Product" table. After having issues with my models.py id's (I have previously changed my current primary keys names you see to just id, and that caused the whole confusion), I went back to a previous version of my code that did not include "Price" table. I was able to hop on the local server and everything, but I cannot access Customers in admin page because Customer_ID does not exist for some reason (This is in addition to not being able to migrate because of the "Price" table error!) Is their a way to completely clean all the migrations. models.py file from django.db import models from django.contrib.auth.models import User # Create your models here. #strong entities + many-to-one + many-to-many class Customer(models.Model): Customer_ID = models.CharField(max_length = 9, primary_key = True) addressID = models.ManyToManyField('Address') First_name = models.CharField(max_length = 20, null = True) Middle_initial = models.CharField(max_length = 1, null = True) Last_name = models.CharField(max_length = 20, null = True) … -
Save model instance in a variable before save in Django
I am using a viewset where there is a partial_update method that updates the values of a model instance. What I would like to do is to save the old model instance in a variable and then save the model instance with the new values so that I can compare some values after the new values are saved in database. class ModelViewSet(viewsets.ModelViewSet): def partial_update(self, request, *args, **kwargs): oldObj=self.get_object() if self.check_update_permission(request, oldObj): responseObject = super(ModelViewSet, self).partial_update(request, *args, **kwargs) newObj = self.get_object() m2mArgs = {"ModelObject": newObj, "details": request.data} oldObject = Model.objects.get(id = oldObj.id) newObj = self.saveMappedFields(**m2mArgs) serializer = self.readSerializer(newObj) responseObject.data = serializer.data return responseObject else: return HttpResponse('Unauthorized', status=401) def saveMappedFields(self, **args): modelObject = args.get("modelObject", None) details = args.get("details", None) if modelObject and details: # flag = False modelObject.model_attribute.clear() if "model_attribute[]" in details: modelObject.model_attribute.set(details.getlist("model_attribute[]")) return modelObject What I would like is to have the value of oldObject value to be the old model instance values. But it is showing the values of newObj. How can I rectify this error? -
how to upload images in aws lightsail django project via admin page
I wanna upload images along with texts to the database of my Django site through the admin page of my Django project. I have set static and media url and root in settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'myproj/static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and in urls.py: from django.views.static import serve urlpatterns = [ ... url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), ] And I declared my image in any model as follows: some-app-models.py: cover = models.ImageField(upload_to='photos/products/', blank=True) I did it without any problem in development mode on my local machine. to do so, I simply go to localhost/admin and select any table and add a row in that database. In this scenario, I select an image from my local machine to be stored in the path which I defined in models.py. The problem arises when I want to do that routine in production mode. I have deployed my Django project on AWS lightsail. It's working correctly and static files are being loaded too. But, When I go to http://mysite/admin and want to add data to the database to be shown in the site, I select an image from my local machine … -
Using Django .update() with .get()
I have an invoice table # app/models.py class tbl_invoice(models.Model): invoice_id = models.IntegerField(blank=True, null=True) invoice_number = models.IntegerField(blank=True, null=True) quotation_id = models.IntegerField(blank=True, null=True) quotation_number = models.IntegerField(blank=True, null=True) invoiced = models.CharField(max_length=50, default='', blank=True, null=True) this table contains invoice and quotations records, system user has the option to convert any quotation to invoice, but the quotation record will still remain along with the newly generated invoice record and this is my views #views.py obj = tbl_invoice.objects.get(pk='someId') # getting existing record with pk obj.pk = None obj.invoice_id = 'someId' obj.quotation_id = None obj.invoice_number = 'someValue' obj.quotation_number = None obj.invoiced = 'no' obj.type_status = 'invoice' obj.save() above code is working fine, it creates a new invoice record and also maintains the old quotation record however, after converting quotation to invoice I also want to update the invoiced value on the quotation record to yes for that, I tried obj.update(invoiced = 'yes') but .update() doesn't work on .get() how can I create a new record from an existing record and update the old record at the same time or do I have to use multiple queries Thanks for any help. -
Using Q expression in Case When is not returning expected results in Django. Seems like an inner join is used, not left join
I am trying to build a complex filter with the Django ORM and am running into an issue where objects without a foreign key are not being included. This is due to an inner join that is being generated and I believe it should be a left outer join. I have two models Report and Message. Report has a reference to a particular Message but that could also be null. class Report(BaseModel): message = models.ForeignKey( Message, on_delete=models.SET_NULL, related_name="message_reports", null=True, ) created_at = models.DateTimeField() # other fields class Message(BaseModel): should_send_messages = models.BooleanField( default=True ) num_hold_hours = models.IntegerField( default=None, null=True, ) # other fields Here is the filter that I am trying to use. Report.objects.filter( Q(message__isnull=True) | Q(message__should_send_messages=True), created_at__lte= Case( When( Q(message__isnull=True) | Q(message__num_hold_hours__isnull=True), then=ExpressionWrapper( timezone.now() - timedelta(hours=1) * Cast( settings.NUM_HOURS_TO_NOTIFY , output_field=IntegerField()) , output_field=DateTimeField())), default=ExpressionWrapper( timezone.now() - timedelta(hours=1) * Cast( F('message__num_hold_hours') , output_field=IntegerField()) , output_field=DateTimeField()), output_field=DateTimeField()), ) Here is the sql that is generated as a result of that filter block. (I'm not sure why the datetimes look like that ugly) SELECT "report"."message_id" FROM "report" INNER JOIN "message" ON ( "report"."message_id" = "message"."id" ) WHERE ( ( "report"."message_id" IS NULL OR "message"."should_send_messages" = True ) AND "report"."created_at" <= ( CASE WHEN … -
Django StaticLiveServerTestCase cannot TRUNCATE and FLUSH
I try to implement TDD using: django version 3.0 Selenium version 3.141.0 with chromedriver.exe PgAdmin4 (Postgresql 13.0) Here is my test code from selenium import webdriver from selenium.webdriver.common.keys import Keys from django.contrib.staticfiles.testing import StaticLiveServerTestCase class NewUserTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Chrome("D:\chromedriver.exe") def tearDown(self): self.browser.quit() def test_success_login(self): self.browser.get(self.live_server_url) input_username = self.browser.find_element_by_id('id_username') input_password = self.browser.find_element_by_id('id_password') self.assertTrue(input_password.get_attribute('required')) input_username.send_keys('onesinus') input_password.send_keys('123') input_password.send_keys(Keys.ENTER) But when the test executed python manage.py test I have two error: 1. django.db.utils.NotSupportedError: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "my_table_name" references "auth_user". HINT: Truncate table "my_table_name" at the same time, or use TRUNCATE ... CASCADE. 2. Traceback (most recent call last): File "D:\bidboxcms\venv\lib\site-packages\django\test\testcases.py", line 274, in __call__ self._post_teardown() File "D:\bidboxcms\venv\lib\site-packages\django\test\testcases.py", line 1009, in _post_teardown self._fixture_teardown() File "D:\bidboxcms\venv\lib\site-packages\django\test\testcases.py", line 1041, in _fixture_teardown call_command('flush', verbosity=0, interactive=False, File "D:\bidboxcms\venv\lib\site-packages\django\core\management\__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "D:\bidboxcms\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\bidboxcms\venv\lib\site-packages\django\core\management\commands\flush.py", line 65, in handle raise CommandError( django.core.management.base.CommandError: Database test_bidbox-staging couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this … -
Django model datetime is different in template than the database
The date data added is normally added to the database. There is a 3 hour difference in appearance. This is my saved data on admin panel: The view of that data on a template: Settings: LANGUAGE_CODE = 'tr' TIME_ZONE = 'Europe/Istanbul' USE_I18N = True USE_L10N = True USE_TZ = True -
style django-form to save in pdf with wkhtmltopdf
I am developing app in python with django. I have some kind of surveys in my app. I use django-crispy for nice display on the site. I also have an option to download surveys to pdf. I use for that wkhtmltopdf (PDFTemplateResponse). And then, in a pdf, surveys appear a little like screenshots, it is hard to style them, the forms sometimes do not fit on the page. I wish it looked more like here: https://surveytemplates.org/wp-content/uploads/2019/11/pdf-customer-service-survey-form-template-2019-doc-pdf-formatted-free.jpg Are there any other forms besides django-crispy (I tried to find, but failed)? Or can cripsy forms be well divided into pdf pages in wkhtmltopdf? Best regards! -
no filter named 'localtime' [duplicate]
I am using localtime template filter to convert UTC to localtime but I am getting this error.` <td> {{ test.created_at|localtime }} </td>` but I am getting Template Assertion error. created_at is stored in utc in database. In setting.py USE_I18N = True USE_L10N = True USE_TZ = True -
Error while using "python manage.py runserver"
I am getting the following error. I had previously merged a branch but without success. I then used git reset to go back to a previous commit. After that, I tried to run my project but got the following error. Any help is appreciated. (oldenv) C:\New folder\Downloads\TECHTUREPS2\bimscoper-rest-api>python manage.py runserver Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\core\management_init_.py", line 364, in execute_from_command_line utility.execute() File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\core\management_init_.py", line 308, in execute settings.INSTALLED_APPS File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\conf_init_.py", line 56, in getattr self._setup(name) File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\conf_init_.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\New folder\Downloads\TECHTUREPS2\oldenv\lib\site-packages\django\conf_init_.py", line 110, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\New folder\Softwares\Python 2.7\lib\importlib_init_.py", line 37, in import_module import(name) File "C:\New folder\Downloads\TECHTUREPS2\bimscoper-rest-api\bimscoper\settings\dev\dev.py", line 9 <<<<<<< HEAD ^ SyntaxError: invalid syntax -
Django pagination: redirect to specific page after edit (FBV)
I'm listing 300 of customers records using a pagination in Django. Each page contains 20 records. Suppose i'm on page 7 and selected a record to edit . After editing the record, successful url to redirect list view(which is first page). So I want , if I edit in ?page=7, when the edit in done by customer id it will come back to ?page=7. Here is my customer_list view in view.py: def customer_list(request): posts_list = Customer.objects.all() query = request.GET.get('q') if query: posts_list = Customer.objects.filter( Q(invoice__addresses__contact_number__icontains=query) | Q(invoice__addresses__address__icontains=query) | Q(shipping_method__icontains=query) ).distinct() page = request.GET.get('page') paginator = Paginator(posts_list, 20) # 20 posts per page try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = { 'posts': posts, 'page': page } return render(request, "customers/customer_list.html", context) Here is update_customer_list view in view.py: def update_customer_list(request, id): """ Here, update single customer id form customer table :param request: :param id: :return: """ obj = get_object_or_404(Customer, pk=id) form = CustomerForm(request.POST or None, instance=obj) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Customer successfully Updated') return redirect('customer_list') return render(request, 'customers/customerUpdateForm.html', {'form': form}) Here is update_customer_list url in urls.py: path('update_customer_list/<int:id>/', views.update_customer_list, name='update_customer_list'), I am waiting for someones help and help will be highly appreciated... -
How to Convert SQL query to Django ORM?
this is the SQL query which I want to change to Django ORM please help? select 0 'bucket_id', 'Incomplete' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf is null union select 1 'bucket_id', 'Very Poor' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 0 and 1.999 union select 2 'bucket_id', 'Poor' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 2 and 2.999 union select 3 'bucket_id', 'OK' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 3 and 3.999 union select 4 'bucket_id', 'Good' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 4 and 4.599 union select 5 'bucket_id', 'Great' as 'name', count(*) 'user_count' from user_smartreq where job_id = {job_id} and pred_perf between 4.599 and 5 -
Ckeditor in local is not working due to the aws settings for static and media file in settings.py
I have installed the CKEditor package for my CRM backend, it was working perfectly fine. Now, I have put AWS settings in my settings.py file which contains STATIC & MEDIA root and URL settings. Due to this, my CKEditor has stopped working and I cant fill in the text data now. But, if I comment out again, CKEditor starts working again in local otherwise not. My AWS settings: DEFAULT_FILE_STORAGE = 'travel_crm.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'travel_crm.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'bonbonstage' S3DIRECT_REGION = 'ap-southeast-1' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ), } My ckeditor settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" #ckeditor configs #todo CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'width': 1000, 'height': 400 }, } My URLS settings: urlpatterns = [ path('admin/', admin.site.urls), path('', admin.site.urls), path('', include('apps.accounts.urls')), path('', include('apps.blogs.urls')), path('', include('apps.enquiry.urls')), path('', include('apps.packages.urls')), path('', include('apps.booking.urls')), path('ckeditor', include('ckeditor_uploader.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG is True: …