Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, POST method, already logged in user
I write an app in django - sth like twitter, i have already log in/log out panel, and form when already logged in user can add a tweet. A tweet has a 3 columns in database: class Tweet(models.Model): content = models.CharField(max_length=140) creation_date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) The form looks like: class TweetForm(forms.Form): content = forms.CharField(label='content') And the view: class TweetCreationView(LoginRequiredMixin, View): permission_required = 'twitter.add_tweet' raise_exception = True permission_denied_message = 'You are not allowed being there!' def get(self, request): form = TweetForm() return render(request, "twitter/add_tweet.html", {"form": form}) def post(self, request): form = TweetForm(request.POST) if form.is_valid(): if request.user.is_authenticated(): username = request.user.username user_id = username.id content = form.cleaned_data.get('content') return render(request, "twitter/add_tweet.html", {"form": form}) How can i obtain an already logged in user in django and add his/her id to form? -
How to apply certain queries only to those that have an Attribute Exception
In my Pinterest clone web app, I have cloned their pin's comment section so far like below: try: pin_comment_info = [{"user": comment.user.email.split("@")[0], "comment": model_to_dict(comment)} for comment in pin_comment] except AttributeError: pin_comment_info = [{"user": comment.user.social_id, "comment": model_to_dict(comment)} for comment in pin_comment] This error handling is there because when I tried Q objects like below, it still did not work: pin_comment_info = [{"user": (Q(comment.user.email.split("@")[0]) | Q(comment.user.socia_id)), "comment": model_to_dict(comment)} for comment in pin_comment] In the User table, there are users that have email address and that don't. I want the comments to have the author(user)'s email prefix if one exists and social_ids if there is no email in the table. Is there any way to circumvent this AttributeError handing? The very first code only returns user's social_id even when there are some users that have email addresses. Thank you so much!!! -
configuring installed apps in setting.py in django
I started a project and created an app using django-admin startproject tutorial django-admin startapp snippets Now, I am adding the "snippets" app to the installed_apps in settings.py. but I m not able to understand the difference between: "snippets" and "snippets.apps.SnippetsConfig" Which line to add in the installed_apps in settings.py file. -
Reverse for 'user-blog' with no arguments not found. 1 pattern(s) tried: ['pages/user/(?P<username>[^/]+)$'] in django
i am trying to create a Userpostlistview in to my blog post,which you can see all post by a specific user i have them created but i get to see this error everytime i go to my blog url i only get to see the error when i identify the user in the template this is my code views.py class CustomUserBlogListView(ListView): model = Blog template_name = 'pages/user_blog.html' context_object_name = 'blog_post' paginate_by = 5 def get_queryset(self): user = get_object_or_404(CustomUser, username=self.kwargs.get('username')) return Blog.objects.filter(doctor=user.doctor).order_by('-timestamp') urls.py path('user/<str:username>', CustomUserBlogListView.as_view(), name='user-blog'), path('blog/<int:pk>/', BlogDetailView.as_view(), name='blog-detail'), path('blog/<int:pk>/update/', BlogUpdateView.as_view(), name='blog-update'), path('blog/new/', BlogCreateView.as_view(), name='blog-create'), path('blog/<int:pk>/delete/', BlogDeleteView.as_view(), name='blog-delete'), path('doctor_info/', user_views.doctor_info, name='doctor_info'), path('patient/', user_views.patient, name='patient'), blog.html {% for blog in blog_post %} <div class="col-md-4 ftco-animate"> <div class="blog-entry "> <a href="{% url 'blog-detail' blog.id %}" class="block-20" style="background-image: url({{ blog.image.url }})"></a> <div class="text d-block"> <div class="meta mb-3"> <div>{{ blog.timestamp|timesince }} ago</div> <div><a href="{% url 'user-blog' blog.doctor.username %}">Written By {{ blog.doctor.user.username }}</a></div> <div><a href="#" class="meta-chat"><span class="icon-eye"></span>{{ blog.view_count }}</a></div> </div> <h3 class="heading"><a href="{% url 'blog-detail' blog.id %}">{{ blog.title }}</a></h3> <p>{{ blog.summary }}</p> <p><a href="{% url 'blog-detail' blog.id %}" class="btn btn-primary py-2 px-3">Read more</a></p> </div> </div> </div> {% endfor %} user_blog.html <h1 class="mb-3"> {{ view.kwargs.username }} has ({{ page_obj.paginator.count }}) Post</h1> {% for blog in blog_post %} … -
Problem while Implementing simple notification system?
Here I am trying to implement simple notification feature. The requirements is : When the task status will be completed then I want to display notification only to the user who has created this task. For this I designed this model. I write context processors to display the notification but using context processor while creating the notification would not work(I suppose not sure). I created notification objects like this under task_list_view but this would work only if we go in this view. I want to create notification on every task complete(shouldn't need to go specific page to create notification) . How can I do this? Any suggestions? models class Notification(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) is_read = models.BooleanField(default=False) text = models.CharField(max_length=500) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Task(models.Model): task_status = ( (1, 'running'), (2, 'completed'), ) name = models.CharField(max_length=255) status = models.IntegerField(choices=task_status) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='task_categories', null=True, blank=True) created_by = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, blank=True, null=True) context_processor def list_notifications(request): notifications = Notification.objects.filter(is_read=False) return {'notifications': notifications} views def task_list_view(request): tasks = Task.objects.order_by('-pk') try: completed_tasks = Task.objects.filter(status=2) for task in completed_tasks: Notification.objects.create(user=task.created_by, text='{} has been completed.'.format(task.name)) except Exception as e: print(e) return render(request, 'crawler/task-list.html', {'tasks':tasks}) -
Python Django Template Block Rendered Twice
js block in page.html is getting rendered twice end of page.html <script src="{% static 'LibreBadge/js/jquery-3.4.1.slim.min.js' %}"></script> <script src="{% static 'LibreBadge/js/bootstrap.bundle.min.js' %}"></script> <script> $(document).ready(function(){ $('.toast').toast('show'); }); </script> {% block js %} {% endblock %} </body> </html> block js is <script> function printRendering(){ $('#badgeTemplateTempWrapper').append( $('#badgeTemplateWrapper>*') ); $(' *').not('.printme *,.printme,body,nav *,head *,style,script,html,visibility:hidden').addClass('hiddenByPrint'); $('.hiddenByPrint').hide(); }; function afterPrintRendering(){ $('.hiddenByPrint').show(); $('#badgeTemplateWrapper').append( $('#badgeTemplateTempWrapper>*') ); }; function replaceAttribute(id,attribute,value){ $("#badgeTemplate").children()('#'+id).attr(attribute, value); } $(document).ready(function(){ $("#tableSearch").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#resultsTable tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); }); function rowClick(row) { document.badgeForm.EmployeeID.value = row; document.badgeForm.submit(); } </script> end of outputted html <script> function printRendering(){ $('#badgeTemplateTempWrapper').append( $('#badgeTemplateWrapper>*') ); $(' *').not('.printme *,.printme,body,nav *,head *,style,script,html,visibility:hidden').addClass('hiddenByPrint'); $('.hiddenByPrint').hide(); }; function afterPrintRendering(){ $('.hiddenByPrint').show(); $('#badgeTemplateWrapper').append( $('#badgeTemplateTempWrapper>*') ); }; function replaceAttribute(id,attribute,value){ $("#badgeTemplate").children()('#'+id).attr(attribute, value); } $(document).ready(function(){ $("#tableSearch").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#resultsTable tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); }); function rowClick(row) { document.badgeForm.EmployeeID.value = row; document.badgeForm.submit(); } </script> <script src="/static/LibreBadge/js/jquery-3.4.1.slim.min.js"></script> <script src="/static/LibreBadge/js/bootstrap.bundle.min.js"></script> <script> $(document).ready(function(){ $('.toast').toast('show'); }); </script> <script> function printRendering(){ $('#badgeTemplateTempWrapper').append( $('#badgeTemplateWrapper>*') ); $(' *').not('.printme *,.printme,body,nav *,head *,style,script,html,visibility:hidden').addClass('hiddenByPrint'); $('.hiddenByPrint').hide(); }; function afterPrintRendering(){ $('.hiddenByPrint').show(); $('#badgeTemplateWrapper').append( $('#badgeTemplateTempWrapper>*') ); }; function replaceAttribute(id,attribute,value){ $("#badgeTemplate").children()('#'+id).attr(attribute, value); } $(document).ready(function(){ $("#tableSearch").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#resultsTable tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); }); function rowClick(row) { document.badgeForm.EmployeeID.value = … -
How can I get django jquery formsets to clone and delete correctly?
I want to build a little cookbook with django. For the page with the ingredients I want to use a formset and a jquery solution in order to display an "add one more" link and at the end of each row a "delete thins one" link. However, I do not know how to get the jquery part to work correctly. My problem is: When I want to add one more entry then the entire table will be cloned, no matter if the original has one row or four rows or whatever. And when I want to delete a row from the table the entire table will be deleted. I tried to give the id "zutaten-forms" to other elements like the tr instead of the table, but then it did not work at all. Here comes my template snippet: <br> <br> <table class="table table-bordered table-striped"> <thead> <tr> <th>Zutat</th> <th>Menge</th> <th>Einheit</th> <th>&nbsp;</th> </tr> </thead> </table> <div class="accclass"> <table id="zutaten_forms" class="table table-bordered table-striped"> {% for form in form_zutat %} {{ form.non_field_errors }} {{ form.errors }} <tr class="dccclass"> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} … -
Can I return JSON Web Token (JWT) through django-rest-auth login and registration?
I am trying to return JWT from my rest API through django-rest-auth but it gives a different type of token like for eg. 9054f7aa9305e012b3c2300408c3dfdf390fcddf. I have my own TokenObtainPairSerializer for JWT like this: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): email = user.email token = super(MyTokenObtainPairSerializer, cls).get_token(user) # Add custom claims token['first_name'] = user.first_name token['last_name'] = user.last_name token['email'] = user.email return token I would like the django-rest-auth to return my custom JWT through the login. Any help will be greatly appreciated. P.S: I searched through google and other stack-overflow questions, but couldn't find what I'm actually looking for. -
No warnings in VScode
I am using VScode for django web devlopment(beginner) ,as you can see ,I have not imported 'include'function but have used it in the path function...I should get a warning at least but there is none..and there is no app declared as calc and it is also not showing any warnings. -
Why do I keep getting django.core.exceptions.ImproperlyConfigured: Specifying a namespace although I added app name in urls.py
I have recently created a new app called newsletters, I have included it in the settings base.py and add it in the Main urls.py along with the app urls.py and added the app name as well, but i keep getting django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked I am not sure the reason here is the settings base.py INSTALLED_APPS = [ 'newsletters', ] Here is the main urls.py urlpatterns = [ path('newsletters/', include('newsletters.urls', namespace='newsletters')), ] Here is the newseltters app urls.py from .views import newsletter_signup, newsletter_unsubscribe app_name = 'newsletters' urlpatterns = [ path('signup/', include(newsletter_signup, namespace='newsletters')), path('unsubscribe/', include(newsletter_unsubscribe, namespace='unsubscribe')), -
How to add mention feature to a comment box in django
I am trying to create a comment box for my django app with user mention feature. When a user trying to comment with "@" then the list of users should be listed and selected for mentioning. I searched for implementing this. But I am getting only a regular comment box. Is there any way to implement. Something like in the following is what I want. -
AttributeError: module 'rest_framework.serializers' has no attribute 'as_view' in django
i already import and install djangorestframework in my project and import it to my settings, how do i call or import my serializers to my urls.py, i am getting this error AttributeError: module 'rest_framework.serializers' has no attribute 'as_view' this is my serializers.py from rest_framework import serializers from .models import register class registerSerializer(serializers.ModelSerializer): class Meta: model = register field = ('username', 'password', 'email') this is my urls.py from rest_framework import serializers urlpatterns = [ path('admin/', admin.site.urls), path('', serializers.as_view(), name='serializers') ] -
Django getting connection.cursor() very slow (~130ms)
I found that getting connection.cursor() to execute a query was slow (~130 ms). from django.db import connection import time start = time.time() with connection.cursor() as cursor: print('Get cursor time', (time.time() - start) * 1000, 'ms') # Get cursor time 130.66697120666504 ms I'm using MSSQL and not sure if my database settings contributes to this so I'll include them below. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': os.environ['SQL_DATABASE'], 'HOST': os.environ['SQL_SERVER'], 'PORT': os.environ['SQL_PORT'], 'USER': os.environ['SQL_USER'], 'PASSWORD': os.environ['SQL_PASSWORD'], 'AUTOCOMMIT': True, 'OPTIONS': { 'driver': 'FREETDS', 'host_is_server': True, 'query_timeout': 1 }, } } I'm rather new to Django so I'm not sure if this is normal. Has anyone else run into this and have a suggested fix to get this time lower? -
How to push your updated changes to an ec2 instance with django
I have followed the tutorial below and successfully deployed my django app to AWS on ec2. https://dev.to/subhamuralikrishna/deploying-django-application-to-aws-ec2-instance-2a81 (I have not connected my EC2 to RDS yet) Now that I have made some changes to my django app and pushed the changes to github, How do I update the changes to my Ec2 instance? -
Upgrading to Python 3.8.3 caused some symlink errors
I installed Python 3.8.3 package from the official website. The Python works but when I try using few modules I get error. I installed Django by pip install django and verified it by python3 -m django --version it shows 3.0.7 as the version. But when I use django-admin, I get: zsh: /usr/local/bin/django-admin: bad interpreter: /usr/local/opt/python/bin/python3.7: no such file or directory as the error. I think the problem is with symlinks but I have no idea how to solve it. Thanks in advance! -
Why cant I request data from django
I cant request data from my Django server. I keep receiving an error Access to XMLHttpRequest at 'http://localhost:8000/auth/token/login/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. setting.py INSTALLED_APPS = [ 'corsheaders', ], MIDDLEWARE_CLASSES = ( 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ) , CORS_ORIGIN_ALLOW_ALL = True login.js const signin = e => { axios.post("http://localhost:8000/auth/token/login/",signinForm,{ headers: { 'Access-Control-Allow-Origin': '*' }}) .then(res => { // localStorage.setItem("name",loginForm.userName) // localStorage.setItem("token",res.data.access_token) // props.history.push(`/profile/${loginForm.userName}`) console.log(res.data) }) .catch(err => console.log(err)) setSigninForm({ email: '', password: '' }) e.preventDefault() // props.history.push(`/profile/${localStorage.getItem("name")}`) console.log(signinForm) } -
But, no such 'purchase_ptr' field exists in my model?
ERROR: You are trying to add a non-nullable field 'purchase_ptr' to purchase_item without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py I am writing an application for inventory management in Django with the default sqlite. class Purchase_Item(Purchase): product = models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) QTY = models.IntegerField() gross_cost = models.IntegerField(null=True,blank=True) IGST = models.IntegerField(null=True,blank=True) def __str__(self): return self.product.__str__() @property def net_cost(self): net_cost = sum(self.gross_cost + self.IGST) return net_cost -
Passing dynamic javascript variable as url in template
I am trying to create a dynamic url in javascript to pass to my html template. In my js, I've got: // dynamic url to edit flashcard function createDynamicURL() { //The variable to be returned var URL; //The variables containing the respective IDs var cardID= cards.cards[current_card].id //this is defined earlier //Forming the variable to return URL-="study/[1-9][0-9]/"; URL+="card-edit/"; URL+=cardID; return URL; } And in my template I have: <a id="edit-button" class="btn btn-default btn-warning" href="javascript:window.location=createDynamicURL();" >Edit</a> My urls.py: app_name = 'flash' urlpatterns = [ path("decks/",views.DeckList.as_view(),name="deck-list"), path("decks/<int:pk>/",views.DeckDetail.as_view(),name="deck-detail"), path("cards/<int:pk>/", views.CardList.as_view(), name="flash-list"), path("card-edit/<int:pk>/",views.CardEdit.as_view(),name="flash-edit"), path("card-detail/<int:pk>/",views.CardDetail.as_view(),name="flash-detail"), path("edit/<int:pk>/",views.DeckUpdate.as_view(),name="edit"), path("",views.home,name="home"), ] The url I get when I click: http://127.0.0.1:8000/%2Fflash/study/33/NaNcard-edit/51 The the correct url would have been: http://127.0.0.1:8000/%2Fflash/card-edit/51/ So at least it is giving me the correct id. But why is it giving me NaN, and how do I get rid of the study/33? Note the 33 will not always be 33, and I don't have access to that id here, so I want it to be just any 2-digit number. I don't have a lot of experience with javascript, so sorry for the basic question. Any advice would be greatly appreciated! -
Difference between question_id and question.id in DJANGO (Python)
I am a complete Django beginner . I am finding some difficulties in understanding the concepts of using (.set and _set) methods, (.id and _ id ) methods and various methods like that. Currently i am referring Django Docs ->> https://docs.djangoproject.com/en/3.0/intro/ somebody help me in understanding these concepts ,like what is the reason behind the methods and where to use what king of method. Thank you. -
Display videos from model in template - Django
Novice here. Trying to make web app that creates a video (with moviepy) and plays it in the browser. It should work something like this app but when user clicks button a video is created and displays. I have a model with FileField where I upload videos which works fine. I set this up with a form but don't use it as I upload the videos with moviepy/python script. Now I am trying to display the uploaded videos in the browser and am a little lost. Would be grateful for any guidance on how to go about this. So far I've been trying variations on the below: views.py def video_upload_detail_page(request): obj = VideoUpload.objects.get(id=16) template_name = 'video_upload_detail.html' context = {'videofile': obj.videofile} return render(request, template_name, context) .html {% load static %} <br><br> <video width='400' controls> <source src="{{ object.videofile.url }}" type='video/mp4'> Your browser does not support the video tag. </video> <br><br> and this is for the uploading: models.py from django.db import models class VideoUpload(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True) forms.py (I don't actually use this as the videos are uploaded via python script) from django import forms from .models import VideoUpload class VideoForm(forms.ModelForm): class Meta: model = VideoUpload #fields = ["name", "videofile"] fields … -
How to get the price and the id from request.POST.getlist()?
i tried to get two value from request.POST.getlist() what i am doing is : for price in request.POST.getlist('price') print(price) what if I want to get two values with two keys i mean i want the price and the id ?? for price, id in request.POST.getlist('price','id') /something like that ??? -
Gateway 400 Bad Request Nginx
I am first time setup this stack (nginx , uwsgi, django application). Currently I quite blurred on what i doing now, i hope someone can give me some guidelines. This is the documentation i following. https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html What i managed to do is I can access my web app via uwsgi in virtualenv. uwsgi --http :8000 --module folio.wsgi:application What stopping me right now is after i start nginx, when i access 192.168.92.148:8001, i got 400 Bad Request. Below are my files. ifconfig ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.92.148 netmask 255.255.255.0 broadcast 192.168.92.255 inet6 fe80::b9d9:2ea2:a116:9c31 prefixlen 64 scopeid 0x20<link> ether 00:0c:29:75:cf:c6 txqueuelen 1000 (Ethernet) RX packets 391924 bytes 349216106 (349.2 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 218500 bytes 65221010 (65.2 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 folio_nginx.conf file upstream django { server 127.0.0.1:8001; # for a web port socket (we'll use this first) } server { listen 8001; server_name 192.168.92.148; charset utf-8; client_max_body_size 75M; location /static { alias /home/yao1122/Project/folio/folio/static; } location / { uwsgi_pass django; include /home/yao1122/Project/folio/uwsgi_params; } } uwsgi_params file uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param … -
Running bx dev shell fails after bx dev code app with only from django starter
I have an app with nothing except the code provided in django starter. I have got the code locally from my app (agency) with the command bx dev code agency. When i run the command bx dev shell i get the following root@felix-XPS-13-9300:~/agency# bx dev shell --trace IBM Cloud CLI version: 1.1.0+cc908fe-2020-04-29T04:06:12+00:00 dev plugin version: 2.4.8 cr plugin version: MISSING ks plugin version: MISSING cf plugin version: 6.51.0+2acd15650.2020-04-07 docker version: 19.03.11, build 42e35e61f3 docker-compose version: MISSING kubectl version: MISSING helm client version: v2.16.8 git version: 2.17.1 API endpoint: https://cloud.ibm.com Region: eu-gb User: felix.farquharson@gmail.com Account: Felix Farquharson's Account (1a69443a2e2140e8879562718158e5e4) Resource group: No resource group targeted, use 'bx target -g RESOURCE_GROUP' CF API endpoint: https://api.eu-gb.cf.cloud.ibm.com (API version: 2.147.0) Org: felix.farquharson@gmail.com Space: dev Stopping the 'agency-django-run' container... The 'agency-django-run' container was not found Stopping the 'agency-django-tools' container... OK The 'agency-django-tools' container is already stopped Validating Docker image name Binding IP and ports for Docker image. OK Using these variable values: 01: ContainerName string = 02: ContainerNameRun string = agency-django-run 03: ContainerNameTools string = agency-django-tools 04: ContainerBuildTarget string = 05: HostPathRun string = . 06: HostPathTools string = . 07: ContainerPathRun string = /app 08: ContainerPathTools string = /app 09: IsUseRootUserTools bool = false … -
Suggestion on how to setup the schema
I am new to django and new to coding.. I have a requirement for an app and not sure on how to setup my models and forms. Appreciate if anyone can suggest or share thoughts around how this can be designed I have three segments that I want to use as models.. Example - Movies, Categories and users. Movies can have more than one categories mapped to each movie name Category can have multiple movies tagged to each of them (To make things complex) - Users will be tagged to categories that will show movies to them based on categories tagged. Hence each user can have multiple categories tagged to them and vice a versa each category will have lots of users tagged to them Can any expert advise on what would be a best approach to set up the models and forms? Also, Can I build a table view of this information to show users, categories and movies as a single table to users where they can use filtering? not sure how can models get joined together in a view to load to templates. If you can point me to some examples or docs, I will try to learn … -
Django: send array with AJAX
I want to send an array of values via AJAX to a Django view but I only find how to send forms. For example I send the following array of values. How do I access that array in my views? Let to_save = [] $.each($('.linea_producto').find('.esta_coleccion.elegido'), function(index, value) { producto = $(this).find('.producto').text(); marca = $(this).find('.marca').text(); packaging = $(this).find('.packaging').text(); categoria = $(this).find('.categoria ').text(); to_save.push({marca, producto, packaging, category}); }); $.ajax({ url:'/target_url/', type:'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(to_save), success:function(response){ }, error:function(){ }, }); Thanks in advance!