Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Plotly Dash Integration with Django : The current path, welcome.html, didn’t match any of these While Applying Navigation on Sidebar
I have followed this Video Tutorial, and successfully applied all the step and executed. It is working fine. I am now trying to add navigation on the side bar like tables on the bottom of this sidebar navigational menu: but it is giving the following error: My master urls.py is as follows: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), ] and my application urls.py is this: from django import urls from django.urls import path from . import views from home.dash_apps.finished_apps import simpleexample urlpatterns= [ path('', views.home, name='home'), path('tables/', views.home1, name='home1') ] While my sidebar.html is as follows: <li class="nav-item"> <a class="nav-link" href="{% url 'home1' %}"> <i class="fas fa-fw fa-table"></i> <span>Tables</span></a> </li> Moreover i am rendering this in the views.py def home1(request): def scatter(): x1 = ['PM2.5','PM10','CO2','NH3'] y1 = [30, 35, 25, 45] trace = go.Scatter( x=x1, y = y1 ) layout = dict( title='Line Chart: Air Quality Parameters', xaxis=dict(range=[min(x1), max(x1)]), yaxis = dict(range=[min(y1), max(y1)]) ) fig = go.Figure(data=[trace], layout=layout) plot_div = plot(fig, output_type='div', include_plotlyjs=False) return plot_div context ={ 'plot1': scatter() } return render(request, 'home/welcome.html', context) I am unable to understand how can I correctly locate the welcome.html so that … -
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited.need
I am facing error that i cant make form with field or exculde attribute please help me out to fix this error code from forms.py is : from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CustomerRegistrationForm(UserCreationForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs= {'class':'form-control'})) password2 = forms.CharField(label='Confirm Password (again)', widget=forms.PasswordInput(attrs={'class':'form-control'})) email = forms.CharField(required=True, widget=forms.EmailInput(attrs={'class':'form- control'})) class Meta: model = User fiedls = ['email', 'username', 'password1', 'password2'] labels = {'email': 'Email'} widgets = {'username':forms.TextInput(attrs={'class':'form-control'})} -
Django Rest Framework permissions outside Rest Framework view
I am using Rest Framework Token authentication. Which means I cannot know if a user is authenticated outside a rest framework view eg:(A regular django view). The Rest Framework token authentication is a custom auth system which can only be used in a rest framework view. In a normal rest framework view, I can restrict the endpoint for authenticated users by using this: class ExampleView(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) But how will I do that for a regular django view. eg: def someDjangoView(request): ''' Note that I cannout use request.user.is_authenticated. It will always return false as I am using rest framework token authentication. Which means the request parameter should be of rest framework's and not django's built-in. ''' content = {"detail": "Only authenticated users should access this"} return JsonResponse(content) I am stuck in a situation where I have to know if a user is authenticated (custom auth) outside a rest framework view. Is there any way to do that? -
How to override a default value with other value django models
I have a problem with django. In my model, I have a JSON-Field which stores as default an empty list. When trying to append a value to that list, this doesn´t work. No matter whether it´s another object or a string. Going to the field, its still empty then. I would appreciate any help. Thanks in advance. models.py followers = models.JSONField(default={ "followers": [] }) (the "followers" field is in the Client class) views.py current_user = Client.objects.get(id=response.user.id) current_user.followers["followers"].append("Some Name") -
Deploying python API in heroku without static files
I'm deploying a django API which does not have any static files, When is deploy it using heroku via GitHub without using heroku CLI, I get an error Error while running '$ python Rest_Api/manage.py collectstatic --noinput'. NB In my settings file i have the default django STATIC_URL = '/static/' How can i tell heroku my app does not have any statics thus should not expect it? -
Top 5 Customers in current month (Django)
I have an Order model as below: class Order(models.Model): order_date = models.DateField() value = models.FloatField(default=0.00) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, related_name='orders') customer_city = models.ForeignKey(CustomerCity, null=True, on_delete=models.SET_NULL, related_name='orders_city') I would like to generate a table of Top 5 Customers in current month (based on value of total orders received) in my templates file with ('Customer', 'City', 'Orders Count' and 'Orders Sum') fields. Was totally confused and clueless about how to get this data. But, tried the following code in my views.py file: today = datetime.date.today() top_five_customers = Order.objects.filter(order_date__year=today.year, order_date__month=today.month).values('customer').annotate(orders_count=Count('customer'), orders_sum=Sum('value')).order_by('-orders_sum',)[:5] Then in my templates file, I have the following: {% for customer in top_five_customers %} <tr> <td>{{ customer.customer }}</td> <td>{{ customer.customer_city }}</td> <td>{{ customer.orders_count }}</td> <td>{{ customer.orders_sum }}</td> </tr> {% endfor %} Thanks in advance. -
Django form doesn't validate when init ModelMultipleChoiceField without data
I want to use ModelMultipleChoiceField with select2 in my Django application. this is forms.py : #forms.py class SymbolForm(forms.Form): symbol = forms.ModelMultipleChoiceField(queryset=Symbol.objects.all(), label='symbol') Everything is ok except one thing. Symbol table has about 5 thousand record and when html rendered all data pass to html template. I don't want it. I did change my form to this: # forms.py class SymbolForm(forms.Form): symbol = forms.ModelMultipleChoiceField(queryset=Symbol.objects.all(), label='symbol') def __init__(self, *args, **kwargs): super(SymbolForm, self).__init__(*args, **kwargs) self.fields['symbol'].queryset = Symbol.objects.none() to init form without any data. A new problem arises: when form submitted, it is n't valid and django says that my chosen symbol doesn't valid choice. In fact, my problem is that I want to create the form without the data and then be able to verify it with the data I get from the select2, but Django does not allow this. What can I do? -
Test Django create_user of an AbstractUser without username
I'm trying to test the creation of an user in Django. But my user model is not the standard one (email is the username). models.py from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager class UserManager(AbstractUserManager): def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractUser): objects = UserManager() username = None first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] tests.py from django.contrib.auth import get_user_model class CustomUserTests(TestCase): def test_create_user(self): user = get_user_model() utilisateur = user.create_user( email='test@tester.com', password='testpass123', ) self.assertEqual(utilisateur.email, 'test@tester.com') Error line 10, in test_create_user utilisateur = user.create_user( AttributeError: type object 'CustomUser' has no attribute 'create_user' Something is missing but I don't know how to test well this... Thanks a lot -
import django_filters in filers.py shows "Import "django_filters" could not be resolvedPylancereportMissingImports"
I have tried looking for the solution in other threads but still stuck to the problem. My python version is 3.9.5; I reinstalled django to a lower version (it was 3.2.0, later installed 3.0) INSTALLED_APPS = [ ... ... 'django_filters', ] error in <module> from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (D:\DJPROJ\FINsite-packages\django\utils\__init__.py) installed as pip install django-filter. In my filters.py I am getting the line import django_filters as yellow underlined and on hover shows Import "django_filters" could not be resolvedPylancereportMissingImports Can anyone please guide me through? Thanks. -
Django WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/8_9/' failed:
I am doing a Django project in which I have added a live chat feature using Django channels. When I finished the messaging part I worked on other parts of the project (like posting, liking posts, and in general parts that have nothing to do with the messaging). However now when I test the messaging page I get the following error in my browser console: 8_9:58 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/8_9/' failed: The error has no further explanation after the colon (which is why I don't even know where to start solving it, I've had similar errors but they always had something else after the colon). I also tried rolling back to an older version of my app using GitHub (I went back to the last version that I was sure was working) and it still didn't work. Here is my js code: const roomName = JSON.parse(document.getElementById('room-name').textContent); var chatSocket = ""; if(document.location.protocol == "https:"){ chatSocket = new WebSocket( 'wss://' + window.location.host + '/wss/chat/' + roomName + '/' ); } else{ chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); } chatSocket.addEventListener('open', function(event) { $.ajax({ url: '/ajax/get_msg/', data: { 'room': roomName }, dataType: 'json', success: function (data) … -
Django order by a field from a related model returns duplicate objects
I have these two models: class Product(models.Model): name = models.CharField(max_length=100) ... class ProductPack(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.PositiveIntegerField(default=0) And I have a queryset of Product model: products = Product.objects.all() # <ProductQuerySet [<Product: first product>]> I want to order products queryset by "productpack__price". So I tried to do this by this code: qs = products.order_by("productpack__price") This works partly correctly. But there is one problem. For each object in the products, This code returns objects to the count of foreignkey that they have with ProductPack. Like this: qs <ProductQuerySet [<Product: first product>, <Product: first product>, <Product: first product>]> How to fix this problem. Have you any suggestions? -
User() got an unexpected keyword argument 'firstname'
Hello I'm creating an API to register but I'm receiving this error User() got an unexpected keyword argument 'firstname' I tried many ways but couldn't fix, I'll be thankful if someone helps me fix this. my code : from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import get_user_model User = get_user_model() # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name' ,'username', 'email', 'is_business') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','first_name' ,'last_name' , 'username', 'brand', 'email', 'is_business', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], firstname=validated_data['first_name'], lastname=validated_data['last_name'], brand=validated_data['brand'], email=validated_data['email'], password=validated_data['password']) return user -
update post via ajax django modelform
there i'm trying to update post via ajax request and django ModelForm i want to check validation form before submitting class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) date = models.DateTimeField(auto_now_add=True) class MainGroupForm(forms.ModelForm): class Meta: model = MainGroup fields = ['main_type'] error_messages = { 'main_type':{ 'required':_('required to fill'), 'unique':_('taken'), } } widgets = { 'main_type':forms.TextInput(attrs={'class':'form-control','placeholder':_('main group')}) } my views.py @login_required def update_maingroup(request): id = request.POST.get('eid') object = get_object_or_404(MainGroup,id=id) form = MainGroupForm(instance=object) if request.method == 'POST': form = MainGroupForm(request.POST,instance=object) if form.is_valid(): form.save(commit=True) return JsonResponse({'success':'success','data':form}) else: return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'}) my templates $("tbody").on("click",".btn-edit",function(){ const id = $(this).attr('data-edit'); const csr = $("input[name=csrfmiddlewaretoken]").val(); mythis = this mydata = { eid:id, csrfmiddlewaretoken:csr } $.ajax({ url:'{% url 'products:update_maingroup' %}', method:'POST', data:mydata, success:function(data){ console.log(data) }, }); }); <table id="maingroupid" class="table table-bordered table-striped text-center"> <thead> <tr> <th>#</th> <th>admin</th> <th>main group</th> <th>date</th> <th>actions</th> </tr> </thead> <tbody id="tableData"> {% for i in lists %} <tr> <td>{{i.id}}</td> <td>{{i.admin}}</td> <td>{{i.main_type}}</td> <td>{{i.date | date:'d-m-Y h:i A'}}</td> <td align="center"> <button class="btn btn-info btn-edit bg-info" data-edit="{{i.id}}"><i class="far fa-edit"></i></button> <button class="btn btn-danger btn-del bg-danger" data-did="{{i.id}}" ><i class="far fa-trash"></i></button> </td> </tr> {% endfor %} </tbody> </tfoot> </table> the console always returns required to fill i want to update it within this modal form but i'm not so good in … -
Change css of element inside safe custom template tag- Django
I use the safe template tag to display texts that represents html in Django, but I can not change the style of the html elements in that text. <div class='safeclass'> {{ description|safe }} </div> In style, I can't set any css to any element of that html: <style> .safeclass h1{ background-color:red; } </style> -
Get User detail by access_token by django-oauth-toolkit and django-rest-framework
I am using Django oauth toolkit with rest-framework according this manual Now, I want to get user detail by access_token. acceess tokens are correctly stored in table Access Tokens So, I tried to this,but in vain curl -H "Authorization: Bearer Ad359hPR93g1q0l1tIrmM6EvK1Q68i" http://localhost:8008/users/ I still confused this access_token is for the api permission, not the user detail itself??? BTW, http://localhost:8008/users/1 http://localhost:8008/users/2 returns first and second user correctly. My goal is to get the user detail according to access_token Thanks for any helps. class UserList(generics.ListCreateAPIView): #permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] permission_classes = [] queryset = User.objects.all() serializer_class = UserSerializer class UserDetails(generics.RetrieveAPIView): #permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] permission_classes = [] queryset = User.objects.all() serializer_class = UserSerializer -
How to force a FilerImageField to convert image format
I'm trying to force certain FilerImageFields to be convert to another format on saving. I've created this model class SearchImage(FilerImageField): def convert_to_webp(self): print("in convert") extension = ['jpeg', 'png', 'jpg', 'img', 'gif'] if any(ext in self.file.name.lower() for ext in extension): #try: img = Image.open(self.file) correggi_nome = self.file.name.split('.')[0] img.save(correggi_nome + '.webp','webp') logger.debug('img.save save another copy of the file not repalced the original!') #except Exception as ex: # logger.error(ex) def save(self, *args, **kwargs): self.convert_to_webp() print("Save search image") super().save() class Organisation(models.Model): .... search_image = SearchImage( related_name='+', verbose_name=_('Search thumbnail image'), help_text=_('Search thumbnail image'), on_delete=models.SET_NULL, blank=True, null=True ) .... def save(*args, **kwargs): print('saving') print("just before search thumbnail save") self.search_image.save() print("just after search thumbnail save") super.save() my SeachImage.save() is never called. When I save an image (or organisation) I see the print statements within the Organisation.save() but not the SearchImage.save(). How to I get this to work? -
What's the best way to create a generic serializer which is able to serialize all the subclasses of the base model in Django Rest Framework?
I'm currently working on a notification system which is going to deliver many different types of notifications through an API. I have a base notification class called BaseNotification. Here is the code: class BaseNotification(models.Model): message = models.CharField(max_length=500) seen = models.BooleanField(default=True) class Meta: abstract = True And I want to subclass this model to create different variations of notifications: class InvitationNotification(BaseNotification): invited_user = models.ForeignKey(User, on_delete=models.CASCADE) campagin = models.ForeignKey(Campagin, on_delete=models.CASCADE) # ... the rest of specific fields class ChatMessageNotification(BaseNotification): contact = models.ForeignKey(User, on_delete=models.CASCADE) chat_room = models.ForeignKey(SomeSortOfChatRoomWhichIsNotImplementedYet, on_delete=models.CASCADE) # ... the rest of specific fields As you can see, each of those variations, has some meta-data associated with it. The front-end developer would be able to create user interactions using these meta data (for example, in the case of a chat message, the front-end developer would redirect the user to the chat room) I want to list all of these notifications through one unified API. For that, I need a serializer to serialize the objects as json but I don't want to have a sperate serializer for each. Ideally I want to have a generalized serializer which is capable of serializing all kinds of notifications and generates different json output depending on the … -
The number of ajax requests increases with each button click
I am creating an application with Django and AJAX and I have a problem ... I have a button that when pressed, makes a call to a view in Django using AJAX, and every time I press that button, the call is made one more time. That is, the first time I press it, it only makes 1 call, but the second makes 2, the third makes 3, and so on. I have read the rest of the questions similar to mine, but they have not worked for me... this one and many others... I have also tried with $("# button_relation").off('click').on('click', function () {...} and it works, but the page reloads, and I don't want it to reload .. . JS file: $(document).ready(function () { analysis_attributes_list(); $("#button_relation").click(function (e) { e.preventDefault(); let relation = $('#input_relation').val(); let selected = $('#selected').text(); $.ajax({ url: '/analysis/save_relation', type: 'POST', data: { csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(), relation: relation, selected: selected, }, success: function (response) { console.log(response); successNotification(response.msg); analysis_attributes_list(); $('#input_relation').val("") }, error: function (error) { console.log(error); errorNotification(error.responseJSON.msg); }, }); }); }); The view: def save_relation(request): if request.method == 'POST' and request.is_ajax(): print('save_relation') relation = request.POST.get('relation') selected = request.POST.get('selected') my_csv= pd.read_csv('my_csv.csv', sep=';', encoding='utf-8', ) my_csv = my_csv.fillna('') index = my_csv.index condition … -
Python AWS S3 Download S3 Files save in ZIP
I have a bunch of files stored on AWS S3. I want to download those find into a single zip Below is my code. import boto3 import zipfile from io import StringIO, BytesIO s3 = boto3.client('s3') s = BytesIO() zf = zipfile.ZipFile(s, 'w') file_name = '%s-files-%s.zip' % (student.get_full_name(), str(datetime.datetime.now())) files_key_list = ['file1.png', 'file3.png'] for f in files_key_list: data = s3.download_file(settings.AWS_STORAGE_BUCKET_NAME, f, f) zf.write(data) zf.close() resp = HttpResponse(s.getvalue(), content_type="application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=%s' % file_name return resp Error stat: can't specify None for path argument -
creating django project just doesnt work right
i create a project folder, than create a venv and do $ django-admin startproject trydjango. now when i try to run runserver it gives me an error that it couldnt find manage.py, so i have to move it to the original project folder (which now has venv, trydjango, and manage.py). this is a problem i have seen online. however, when i try to run runserver now it says "ModuleNotFoundError: No module named 'trydjango.settings'" (full traceback bellow) the weird thing is, i have opened a project file just like this before, but now its not working. i have done it in the exact same way, the exact way that tutorials show. the only thing that changed is the django version - the tutorial said to use 2.0.7 in order to be able to follow the tutorial. full traceback: File "E:\Python\projects\try_django_project\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import … -
Django overriding templates
When I override admin/change_form.html everything works fine except for user info in the upper right corner (logout, change password and view site options). I don't see this message. How can I make it visible? I thought that when I override a template everything works exactly as it does in the parent template except for the particular block I actually override. Am I wrong? Does it work in a different way? My code: {% extends "admin/change_form.html" %} {% load i18n admin_static admin_list %} {% block title %} Apply users to brand {% endblock %} {% block content %} <h1>Select brands</h1> {% for brand in brands %} <li> <a href="http://localhost/admin/user/user/{{brand.id}}/test/">{{ brand }}</a> </li> {% endfor %} {% endblock %} So my question is, how can I make the usertools block visible? Thanks -
How to send some button value while logged in in Django?
I have a problem, I want to submit while logged in and pass value of button (Some_value) further. Without using csrf in form, debug mode suggests me using csrf_token, when I do - like in following code, it gives me HTTP ERROR 405 In HTML <td align="right"> <form action="reg_this" method="post"> {% csrf_token %} <button name="team_reg" value="Some_value">send this</button> </form> In views.py class Confirmation(BaseView): template_name = "my_page.html" @csrf_exempt def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(context) return context In urls.py url('^app/reg_this', views.Confirmation.as_view(template_name="my_page.html")), What am I doing wrong? Thank you for answers. -
How to use pagination for mptt comments in DetailView?
How to paginate mppt comment models correctly? class ProfileDetailView(DetailView, MultipleObjectMixin): model = User template_name = 'modules/accounts/profile/profile.html' context_object_name = 'profile' queryset = User.objects.all() paginate_by = 6 def get_queryset(self): qs = self.queryset.filter(slug=self.kwargs['slug']).prefetch_related( Prefetch('comments', queryset=Comment.objects.all().select_related('created_by').prefetch_related('rating')), Prefetch('rating', queryset=Rating.objects.all().select_related('created_by')), 'following') return qs def get_context_data(self, *, object_list=None, **kwargs): object_list = self.object.comments.all().select_related('created_by').prefetch_related('rating', 'content_object') context = super(ProfileDetailView, self).get_context_data(object_list=object_list, **kwargs) context['title'] = _('Страница пользователя: ') + str(context['profile']) context['form'] = CommentCreateForm return context def post(self, request, *args, **kwargs): view = CommentCreateView.as_view(content_object=self.get_object()) return view(request, *args, **kwargs) template: {% recursetree object_list %}some template{% endrecursetree %} and I get an error on page 2: The <class 'list'> node is at a level less than the first level -
Exclude Logged in User inside forms.py
Inside my forms.py I have a list with users you want to share the upload with. My issue is that I don't know how to pass the information which user is currently logged in from my views.py (request.user I can access there ) to my forms.py In the image below the first entry should vanish forms.py share_with = forms.MultipleChoiceField( choices=tuple(UserProfile.objects.values_list('id', 'full_name')), widget=forms.CheckboxSelectMultiple, ) models.py [...] share_with = models.ManyToManyField(UserProfile) [...] views.py @login_required def upload_dataset(request): form = UploadDatasetForm() if request.method == "POST": print('Receiving a post request') form = UploadDatasetForm() if form.is_valid(): print("The form is valid") dataset_name = form.cleaned_data['dataset_name'] description = form.cleaned_data['description'] # datafiles = form.cleaned_data['datafiles'] share_with = form.cleaned_data['share_with'] instance = Datasets.objects.create( uploaded_by=request.user.profile.full_name, dataset_name=dataset_name, description=description, # datafiles = datafiles, upvotes=0, downvotes=0, ) for i in share_with: print(i) instance.share_with.add(i) return redirect("public:data") print("The Dataset has been uploaded") context = {"form": form} return render(request, "upload_dataset.html", context) -
How to display django queryset values in templates using javascript
I am trying to display list of names from a django queryset using , Here is my code def vfunc(request): context={} bats = Bat.objects.all().order_by('-id') context['bats'] = bats [each.batname for each in bats] # Gives all the batnames. return render(request, 'bat.html', context) I want to display batnames on template $(function() { //This works when I hardcode the values var batData = [{ "bat":"batname1", //hardcoded & displayed in 1st row }, { "bat":"batname2", //hardcoded & displayed in 2nd row }]; $("#CleanDatasNames").dxDataGrid({ dataSource: batData, ... ... } I am tried something like var batData = [{"bat":"{{bats|join:', ' }}"] but it is displaying obj1,obj2 in same row,I also tried to loop through but failed , any help will appreciated.