Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form vs template
My project can register user and set permission in custom page. not in admin page I used custom permission. Implementing with form is best way or Implement with template is best way? I want to know what is the best way to implement this system. If I should use form. How implement this permission list easily? template.html <h2>Register</h2> <form method="post" action=""> {% csrf_token %} {{ form.as_p }} <ul> {% for permission in permissions %} <h1>{{ permission.name }}</h1> {% for pr in permission.list %} <label for="{{ pr.0 }}"> {{ pr.1 }}</label> <input id="{{ pr.0 }}" name="{{ pr.0 }}" type="checkbox"/> {% endfor %} {% endfor %} </ul> <input type="submit" value="submit" /> </form> forms.py class UserPermissoinForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] view.py class PermissionTestView(View): form_class = UserPermissoinForm template_name = 'permission_test.html' def get(self, request): modelList = [Company, AccountManagement,] permissions = [] for model in modelList: tmp = {} tmp["name"] = model._meta.verbose_name.title() tmp["list"] = model._meta.permissions permissions.append(tmp) form = UserPermissoinForm() return render(request, 'permission_test.html', {'form': form, "permissions": permissions}) def post(self, request): form = UserPermissoinForm(request.POST) if form.is_valid(): codenames = (x for x in request.POST if 'can_' in x) new_user = User.objects.create_user(**form.cleaned_data) for codename in codenames: permission = Permission.objects.get(codename=codename) new_user.user_permissions.add(permission) return render(request, 'permission_test.html', {}) … -
Djanogo - Python Social Auth for social media login
I am trying to use python-social-auth to have users login with their facebook or google accounts. After the user gets the google login page and logs in to their account, I have trouble redirecting back to my site. It says This site can’t be reached 127.0.0.1 took too long to respond. I followed the documentation: https://python-social-auth.readthedocs.io/en/latest/configuration/django.html The following is in settings.py: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "xxxxxxxxxxxxxxxxx" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "xxxxxxxxxxxxxxxxx" INSTALLED_APPS = [ ... ... 'social_django', ... ] MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { ... 'context_processors': [ ... 'social_django.context_processors.backends', # <-- 'social_django.context_processors.login_redirect', # <-- ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) In the google OAuth client, under Authorized redirect URIs, I have: https://127.0.0.1:8000/oauth/complete/google-oauth2/ -
Update onChange event and fire onChange event javascript
I have a select element with several options like this: <select onChange="foo(this)"> <option value="ok" selected>..</option> .... <option value="no">..</option> I'm working with django (don't know if that matters honestly..) and in my onChange event of the select tag I should put window.location.href=this.value but it's not what I want since i need to make some changes to this.value.. My idea was to create a foo function passing the select item and then modify the onChange event and fire it afterwards. I searched for some help and I found several options.. 1) How can I trigger an onchange event manually? 2) Trigger "onchange" event and other examples as well that I don't remember but I use down in the example. None of them are working for me. This is what I tried so far in my foo function: <script> function foo(obj) { if (condition) { obj.onChange = "window.location.href="+ obj.value; //obj.onChange(); //1 option I found on the net was to call onChange this way } else { obj.onChange = "window.location.href="+ obj.value.replace('/A/', '/R/'); // this is the update I need to apply based on the condition //obj.fireEvent("onChange"); // another solution // another solution if ("createEvent" in document) { var evt = document.createEvent("HTMLEvents"); evt.initEvent("change", false, true); … -
How to return a id of a external APi in Django urls?
i need one solution to my little "problem" , actually i have a view to list all my events and I got all IDS collected by a 'for' I need to pass to my URLs to handle all the details of each. I'm beginner in Python , if all of you can help me i'll be grateful. I've tried to create a function to set the id, i'm beginner in python Global to Request url = 'https://api.sympla.com.br/public/v3/events' h = SYMPLA_TOKEN r = requests.get(url, headers=h) json_data = r.json() Here's my view: def detalhar_evento(request): template_name = 'evento_detalhe.html' evento_data = dict() ids = [ids['id'] for ids in json_data['data']] for id in ids: endpoint = url+"/%s" % id response = requests.get(endpoint, headers=h, params=params) detalhes = response.json() #id event detail evento = { 'nome': detalhes['data']['name'], 'detalhe': detalhes['data']['detail'], 'criado': detalhes['data']['start_date'], 'final': detalhes['data']['end_date'], 'endereco_nome': detalhes['data']['address']['name'], 'endereco': detalhes['data']['address']['name'], 'num': detalhes['data']['address']['address_num'], 'comple': detalhes['data']['address']['address_alt'], 'cidade': detalhes['data']['address']['city'], 'estado': detalhes['data']['address']['state'], 'cep': detalhes['data']['address']['zip_code'], 'pais': detalhes['data']['address']['country'], 'propietario': detalhes['data']['host']['name'], 'p_descricao': detalhes['data']['host']['description'], 'categoria': detalhes['data']['category_prim']['name'], 'categoria2': detalhes['data']['category_sec']['name'], } context = { 'evento': evento } return render(request, template_name, context) Url path('detalhes/', views.detalhar_evento, name='detalhes'), Ps. I need to pass the external api id belong the view to url like : path('detalhes/int:id', views.detalhar_evento, name='detalhes'), url_example : 'https://api.sympla.com.br/public/v3/events/12345' Actual Error : -
Django 2.2: MySQL full-text search support – where did it go, and how to replace it?
It seems that the __search capability (fulltext search ...) was removed after Django 1.9. Well, I need to be able to do MySQL full-text searches and I really don't want to have to build SQL strings in order to do it. "This facility must still be around here somewhere ..." But, where? (My question is specific to Django 2.2 or later.) -
Displaying fields other than pk in a Django Form with a ModelChoiceField
I am building a website where users can upload files and can attach uploads to projects that they created beforehand. The upload is done with a django form where the user can specify the title, comments, etc... There is also a dropdown list where the user can choose from the existing projects that he created (list of projects is dependent on user) As of now the dropdown only shows the (autogenerated) project id which is the pk of the model Project I want the dropdown to show the names of the projects and not the project ID which is not very meaningful for the user. I have already tried to_field_name='name' but that didn't work I have also tried Project.objects.filter(user=user).values_list('name') or Project.objects.filter(user=user).values('name') the last two options show the project name in {'projectname} but when I select them and submit the form the error "Select a valid choice. That choice is not one of the available choices." This is my code: models.py class Upload(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) upload_date = models.DateTimeField(default=timezone.now) comments = models.CharField(max_length=10000, null=True) title = models.CharField(max_length=10000, null=True) project = models.CharField(max_length=99, default='--None--') forms.py class UploadForm(ModelForm): project = ModelChoiceField(label='Select Project', queryset=Project.objects.all(), to_field_name='name', empty_label='--Select Project--') def __init__(self, *args, **kwargs): user = kwargs.pop('user', … -
I want to read excel file and save excel file data into models in django-rest-framework using pandas(management parsing scripts)
"I want to read excel file and save the excel file data into models in django-rest-framework using pandas(management parser script) with json response". -
Creating a user history API in Django
I am new to Django, I am using it to build a server where a person can create an account, then add online newspaper articles that they have viewed. I want the user to be able to view all of the articles they have viewed and I want ONLY that user to be able to see it. Now the database design has gotten my head pretty confused. My schema: User(id, username, password, email) Article(is, url, title, etc...) History(id, user_id, article_id, last_viewed) I know how to query for specific users history in the shell (History.objects.filter(User=some_user)), but I don't know how to give each user a history field which automatically queries and find their history. Also, do I have to have one big history table that all of the different user's histories are stored in or can I have a different history table per user? I just want each user to have a history of all of the articles that they have viewed. Any advice you can give? I have been using tasty pie to create the REST api. -
Django dynamic model
I'm trying to create budget app and struggling for creating dropdown lists (tables in database) based on each other in admin panel. I want to created a entry model in which you need to choose subcategory based on category. tried with pirmary keys for all of objects of category class but seems that it doesnt work. class Category(models.Model): # category category_type = models.CharField(max_length=150) def __str__(self): return self.category_type class Category_Types(models.Model): parent_category = models.ForeignKey(Category, on_delete='CASCADE') category_type = models.CharField(max_length=150) def __str__(self): return self.category_type class Entry(models.Model): # single entry to budget database entry_date = models.DateTimeField(auto_now_add=True) transaction_date = models.DateField() try: for category in Category.objects.all(): category_type = models.ForeignKey(category,on_delete='CASCADE') except: pass I doesn't show me any possibilities for adding Entry in admin panel -
Dynamic parameter of url django template
Inside an html page I have two radio buttons with values A and B. I also have an url to a view that needs two parameters, one is a parameter that I can easily access through the django context variable but the second parameter should have the value A or B based on which radio button is checked. I don't know how to get this done. I've red this post: Get javascript variable's value in Django url template tag which is kinda what I'm looking for but I don't understand how can this be implemented in my case. Also checked this post: https://www.reddit.com/r/django/comments/39q9lm/url_tag_in_template_with_a_dynamic_parameter/ which is pretty much the same concept. What I tried to do in my template is: <option value="{% url 'view' tmp i %}".replace(/tmp/, 'A');> </option> which is not exactly what I'm aiming for but it was just to check if this is working.. This is not working to me though. Of course my goal is not to replace tmp with 'A' but with 'A' or 'B' based on which radio button is checked by the user inside my html page. Radio buttons have ids radio1, radio2. I could use javascript of course but I'd like to stay … -
Create nested object (1-1 relationship) from flattened POST request
I'm trying to implement two serializer classes which will allow me to create both user and profile objects from a flattened POST request. I tried the implementation described here and it works perfectly fine for updating (and only updating) existing objects. Here is my current implementation: # serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( write_only=True, required=True, style={"input_type": "password"} ) class Meta: model = User fields = ( "username", "password", # ... "date_joined", ) read_only_fields = ("date_joined") class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() def to_representation(self, instance): representation = super().to_representation(instance) representation.update(representation.pop("user")) return representation def to_internal_value(self, data): user_internal = {} for key in UserSerializer.Meta.fields: if key in data: user_internal[key] = data.pop(key) internal = super().to_internal_value(data) internal["user"] = user_internal return internal def create(self, validated_data): user_data = validated_data.pop("user") user = User.objects.create(**user_data) user.set_password(user_data["password"]) user.save() profile = UserProfile.objects.create(user=user, **validated_data) return profile class Meta: model = UserProfile fields = ( "user", "date_updated", # ... "phone_number", ) # views.py class Register(generics.CreateAPIView): serializer_class = UserProfileSerializer name = "userprofile-create" I expect the app to take the flattened JSON and create both user and profile objects. Example POST body: { "username": "test_user", "password": "P@$$w0rd", "first_name": "Foo", "last_name": "Boo", "email": "foo@example.com", "street": "Random Street", "street_number": "11", "flat_number": "11", "zip_code": "11-111", "city": "Some City", "province": 1, "phone_number": … -
How can I get screenshot of an html container, using django?
Consider we have a simple div container inside an html page which has lots of other stuff too. I am seeking to design a button for users, so when clicked, it returns the screenshot image of only that particular container. I am currently working inside a django project and wondered maybe there is a pure html or java solution to this without using python. However in my searches I haven't found anything on python that can help me on this either. For example the div looks something like this: <div class="row" style="height:1200px; overflow-x: hidden;" id="The_chart_that_we_want_its_screenshot"></div> The id is triggered by a java code later in the html script which loads a chart based on some data (which is constantly changing) from database. And since every time the user opens that html page, a different chart is shown in that container, this button is needed for the sake of user's reporting needs. -
Query django foreignkey relationship
I am developing an audit management information system where I can record all finding related to an audit. I have models with foreignkeys relationship. How do I see all findings with a particular assignment and audit_title and unit? See relevant codes below. model.py content class Unit(models.Model): unit_name = models.CharField(max_length=30, blank=True, null=True) def __unicode__(self): return self.unit_name class Assignment(models.Model): assignment_name = models.CharField(max_length=30, blank=True, null=True) def __unicode__(self): return self.assignment_name class Task(models.Model): task_title = models.CharField(max_length=35, blank=True, null=True) return self.task_title class Finding(models.Model): assignment = models.ForeignKey(Assignment, blank=True, null=True) audit_title = models.ForeignKey(Task, blank=True, null=True) auditor = models.ManyToManyField(User, blank=True) unit = models.ForeignKey(Unit, blank=True, null=True) audit_period = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) contact_person = models.CharField('Contact Person', max_length=500, blank=True, null=True) finding = models.TextField('Detail Finding', max_length=500, blank=True, null=True) form.py class FindingSearchForm(forms.ModelForm): class Meta: model = Finding fields = ['assignment', 'audit_title', 'unit', ] -
DateTime range in django rest framework
I am creating an api which returns weather data of particular city for n number of days given.(api definition: weatherdata/city_name/ndays/).I have problem sorting out data for ndays. I sorted out the city name using simple icontains. similarly I want to sort out for ndays. previous ndays data needs to be shown. example: suppose today is 2019-08-29, on providing ndays to be 6, weather data of particular city has to be provided from 2019-08-24 to 2019-08-26. views.py class weatherDetail(APIView): def get_object(self, city_name, ndays): try: x = weatherdata.objects.filter(city_name__icontains=city_name) now = datetime.datetime.now() fromdate = now - timedelta(days=ndays) y = return x except Snippet.DoesNotExist: raise Http404 def get(self,*args,**kwargs): city_name = kwargs['city_name'] snippet = self.get_object(city_name,ndays) serializer = weatherdataserializer(snippet,many =True) return Response(serializer.data) models.py class weatherdata(models.Model): city_name = models.CharField(max_length = 80) city_id = models.IntegerField(default=0) latitude = models.FloatField(null=True , blank=True) longitude = models.FloatField(null=True , blank=True) dt_txt = models.DateTimeField() temp = models.FloatField(null = False) temp_min = models.FloatField(null = False) temp_max = models.FloatField(null = False) pressure = models.FloatField(null = False) sea_level = models.FloatField(null = False) grnd_level = models.FloatField(null = False) humidity = models.FloatField(null = False) main = models.CharField(max_length=200) description = models.CharField(max_length=30) clouds = models.IntegerField(null=False) wind_speed = models.FloatField(null = False) wind_degree = models.FloatField(null = False) urls.py urlpatterns = [ path('admin/', admin.site.urls), … -
Issue with getting argument value form django rest framework url
I have a django project that has an API view. The api view is associated with a url that accepts an argument in the url and a parameter after the ? in the parameters. I am trying to grab the argument that is located within the url which is widget_id to use it as a filter. I am running into an error. view: def put(self, request, pk, format=None): widget_id = self.kwargs.get('widget_id') user_id = self.request.query_params.get('user_id') user_widget = PersonWidgetDefinition.objects.all()\ .filter(widget_definition_id=widget_id, person_id=user_id).count() if user_widget == 0: serializer = PersonWidgetDefinitionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if user_widget == 1: request.data.user_widget = True serializer = PersonWidgetDefinitionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) url: path('widgets/<int:widget_id>/user/', UserWidgetView.as_view(), name='user-widget'), error: TypeError at /api/v2/widgets/1/user/ put() got an unexpected keyword argument 'widget_id' -
Django DRF - how to deserialize an instance that requires a foreign key?
I have a Page model, and a Paragraph model that references its Page. I want to create both modules by deserializing a JSON representation like this: { "page": { "number": 32, "book": "Moby Dick", "paragraphs": [ { "label": "I am a Paragraph within the Page" } ] } } And here are my Paragraph and Page models: class Paragraph(models.Model): page = models.ForeignKey( Page, help_text="Every Paragraph must belong to a Page", related_name="paragraphs", on_delete=models.CASCADE, ) label = models.CharField(max_length=128) class Meta: db_table = 'my_paragraph' class Page(models.Model): # This is not unique! number = models.IntegerField() # This is not unique! book = models.CharField(max_length=128) # but "number" and "book" together are unique. class Meta: db_table = 'my_page' How can I deserialize that representation to instantiate my models? I tried creating these serializers below: class ParagraphSerializer (serializers.ModelSerializer): page = serializers.SlugRelatedField( slug_field="id", queryset=models.Page.objects.all(), ) class Meta: model = models.Paragraph fields = '__all__' class PageSerializer (serializers.ModelSerializer): paragraphs = ParagraphSerializer( many=True, ) # This method never gets called, because PageSerializer validation fails. def create(self, validated_data): paragraphs_data = validated_data.pop('paragraphs') page = models.Page.objects.create(**validated_data) for paragraph_data in paragraphs_data: # We'll need to find some way of adding a `page` field to this paragraph... paragraph_data['page'] = page.id serializer = ParagraphSerializer(data=paragraph_data) serializer.is_valid() serializer.save() class … -
How can load models image with django in css
I'm working on my blog website I want use my post's image in my post page for example my post list has some posts and when the user click in my post card Navigate to post page and this page i want show the post image in the background I know what can do for load image in html I know use /static/img/.../ But I want load image in css like this Background-image : url('') I tried this code but don't work : background-image: url('{{ MEDIA_URL }}/post_image/{{ post.image_url }}'); You know what can i do for this paye attention I import my image from my media folder -
Django session cookie marked as "third party" and blocked by Firefox
When I log in to my Django-based server using Firefox, the cookie passed to the browser gets marked as "Third Party" and thus gets blocked by default, with no option offered to create an exception, even though the cookie shows as being from "https://servername" which is identical to the URL. I found that if I access the server as "https://servername.domain.lol" instead of directly as "https://servername", the cookie gets marked correctly as first-party. I really don't want to force all users to use the FQDN instead of just the server name. Is there some way in Django or in my Nginx reverse proxy to set some header or something such that the browser will recognize that the cookie belongs to this site? -
Django-ratelimit not working in development mode
I am using django-ratelimit package. Everything is working fine and no error but it is not rate limiting my views. -
How to get extra JSON data during a POST request
My goal is to receive a JSON with all the information necessary to create a user, along with something extra that I'll use to create another object all in one go, using the recently created user and the additional information sent through the JSON. For context, my JSON currently looks like this: { "first_name": "John", "last_name": "Doe", "username": "newuser", "email": "johndoe@hotmail.com", "password": "somepassword", "profile_image": null, "type": 2 } type is the information not necessary for the creation of the user. My custom create function is looking like this, currently: def create(self, validated_data): new_user = User.objects.create_user(**validated_data) types = self.request.data.get("type") create_user_type = UserType.objects.create(user=new_user, type=types) return create_user_type It suffered a lot of changes after looking into the Django Rest Framework documentation, stackoverflow questions, and debugging. If I run the code the way it is now, This is what I get: AttributeError at /user/ 'UserSerializer' object has no attribute 'request' So I assume this happens because you can't get request through doing self.request. I tried placing this create in the viewset because I realized things worked slightly different there, but then this happens: TypeError at /user/ create_user() argument after ** must be a mapping, not Request I can edit my question to add any … -
How do you translate the slug value of a page?
I'm trying to implement a language switcher, for which I'm using the Django recommended form: <form action="{% url 'set_language' %}" method="post">{% csrf_token %} {% get_current_language as LANGUAGE_CODE %} <input name="next" type="hidden" value="{{ redirect_to }}"> <input name="language" type="hidden" value="{% if LANGUAGE_CODE == 'en' %}es{% else %}en{% endif %}"> </form> My urls.py is set up like so: urlpatterns = [ # Wagtail urls re_path(r'^cms/', include(wagtailadmin_urls)), re_path(r'^documents/', include(wagtaildocs_urls)), # Django urls path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path(r'', include(wagtail_urls)) ) When I click to change my language, I am correctly forwarded to /en/slug or es/slug, depending on the language I have selected. However the actual slug value is not being translated. Since I have Spanish slugs for the Spanish pages, I am getting a 404 when I switch languages, because I am directed to the English slug value paired with the Spanish locale prefix (es). I also tried using the slugurl_trans template tag, but that didn't seem to work (maybe because I'm not explicitly defining any URLs in my i18n_patterns call?). Any guidance on this would be really helpful, as I've spent way too many hours on this! -
Django 2.2.4 - “No migrations to apply” when run migrate after makemigrations
I am trying to do a migration in django 2.2.4 in python 3.7. First I try to make do makemigations: python3 manage.py makemigrations I get: Migrations for 'main': main/migrations/0001_initial.py - Create model TutorialCategory - Create model TutorialSeries - Create model Tutorial But then I try the second step: python3 manage.py migrate I get: Operations to perform: Apply all migrations: admin, auth, contenttypes, main, sessions Running migrations: No migrations to apply. Even though a migration should happen. I tried deleting my migrations folder and then remaking it (with the empty __init__.py file inside) but it still doesn't work. (Note: I have been following along the tutorial: Linking models with Foreign Keys - Django Web Development with Python p.9 by sentdex) -
django-ratelimit not rate limiting my signup view
Everything is working but it is not rate limiting. @ratelimit(key='ip', rate='5/m') def signup(request) No error just not rate limiting. Development mode. Windows. Cache setting is django default cache Any example program how to use Django-ratelimit. -
How to implement authentication against a model which inherits AbstractBaseUser in Django?
I want to develop an endpoint that accepts user's data and stores it in databases. I want to develop another endpoint that accepts phone_number and password and if the user is authenticated it will return a token for the user. So I created a model named Person that inherits AbstractBaseUser in order to use phone_number not username for authentication. and I created a function that use django.contrib.auth.authenticate method to authenticate user. the problem is the method authenticate() always returns None for any user even if the user is in the database. I tried to build a custom authenticate method but the problem is still existing. -
first and last value is not displaying in chart.js used with django
i want to display the employee and salary in a graph, i used chart.js and django. but i cannot display the salary of first and last employee..any suggestion is appreciated. #views if request.method=="GET": return render(request, 'upload_pandas.html') else: file=request.FILES['myfile'] file_read=pd.read_excel(file) column_selection=file_read['Salary'] salary=[] salary=list(column_selection) print(salary) name=[] name=list(file_read['First Name']) print(name) lis=[salary,name] data={ 'salary_data': salary, 'label_data': name, } return render(request,'map.html',{'data':data}) #url.py urlpatterns=[ path('upload/',views.view_panda), ] the problem is here, when i print in console it prints all the value but it was not loading in the graph.enter image description here #map.html <html> <head> <title>Chart.js</title> </head> <body> <div > <div> <canvas id="genderchart" width="1000"></canvas> </div> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script> <script> var label={% autoescape off %} "{{ data.salary_data }}" {% endautoescape %}; var label1={% autoescape off %} "{{ data.label_data }}" {% endautoescape %}; var lab=label1.split(',') console.log(lab) console.log(label) console.log(label1) new Chart(document.getElementById("genderchart"),{ type:'bar', data:{ labels:label1.split(','), datasets:[ { label:"employee", backgroundColor:"rgba(62,149,205,1)", borderColor: "rgba(62,149,205,1)", pointBackgroundColor:"rgba(62,149,205,1)", data: label.split(','), }, ] }, options:{ legend:{ labels:{ fontSize:18 } }, title:{ display : true, text : "Salary Wise", fontSize : 22.0 }, scales:{ yAxes:[{ offset: true, ticks:{ suggestedMin: true, fontSize:15.0, }, scaleLabel: { display:true, labelString:'Salary', fontSize:20.0, } }], xAxes:[{ desplay: true, offset: true, ticks:{ beginAtZero: true, fontSize:15.0, }, scaleLabel: { display:true, labelString:'Employee', fontSize:20.0, } }] }, responsive: …