Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django container can't access postgres container
I am trying to have my database and my django rest api connect using docker-compose. However, my django container is giving me this error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Postgres starts up normally, and I am able to access it locally using the terminal. I'm just not sure why my django container can't connect. $ psql -h 0.0.0.0 -p 5432 -U bli1 -d redribbon Password for user bli1: psql (12.1) Type "help" for help. Within my settings.py for django this is my database values DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "redribbon", "USER": "bli1", "PASSWORD": "password", "HOST": "0.0.0.0", "PORT": "5432", } } docker-compose.yml version: "3" services: postgres: image: postgres:latest restart: always ports: - "5432:5432" volumes: - ./pgdata:/var/lib/postgresql/data/ environment: POSTGRES_DB: redribbon POSTGRES_USER: bli1 POSTGRES_PASSWORD: password api: build: dockerfile: Dockerfile.dev context: ./redribbon-api command: python manage.py runserver 0.0.0.0:8000 volumes: - ./redribbon-api/api:/usr/src/api depends_on: - postgres ports: - "8000:8000" -
If statement in python/django
I am trying to do a simple if statement in python. I have got two fields in my model that corresponds to price (price and discount_price). I would like to filter the results by price but I am not sure how to write the if statement. It should go like this: If 'discount_price exists' then filter by using 'discount_price' if not use field 'price' instead. my views.py def HomeView(request): item_list = Item.objects.all() category_list = Category.objects.all() query = request.GET.get('q') if query: item_list = Item.objects.filter(title__icontains=query) cat = request.GET.get('cat') if cat: item_list = item_list.filter(category__pk=cat) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') if price_from: item_list = item_list.filter(price__gte=price_from) if price_to: item_list = item_list.filter(price__lte=price_to) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list } return render(request, "home.html", context) -
Can't find correct configuration for media assets with django-storages and Amazon S3
I'm attempting to implement the ability to upload images to Amazon S3 in my Django app using django-storages, boto3, whitenoise, and pillow. I've been following this tutorial as well as this one, and while I've been able to successfully get my static assets to load from S3, I can't seem to get my app to upload to a media folder in S3. It still uploads the images to a local environment. My settings has the following configuration, as per the two tutorials: settings.py STATIC_URL = '/static/' AWS_LOCATION = 'static' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = '<my-bucket>' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } DEFAULT_FILES_STORAGE = '<my-project>.storage_backends.MediaStorage' STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] AWS_DEFAULT_ACL = None With a storage-backends.py file in the same directory containing the following: from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False In models.py there's: profile_pic = models.ImageField(upload_to='profile_pics/', blank=True) Which didn't bring me any issues before I implemented whitenoise for deployment, but whitenoise doesn't play well with local files, so that was expected. I've attempted migrations, changing the permissions on … -
How to develop a global Mutation class to perform an ADD Operation in Graphene-Django using GraphQL?
Can anyone share how to develop a global Mutation class to perform an ADD Operation in Graphene-Django using GraphQL? I can write separate Mutations for individual Models but I want to use the main Mutation Class and want to reuse that passing my individual Model Names and their Properties/Attributes. There are many models that just require basic ADD/update/delete mutations no other permutations or calculations are required. -
Iterate over all categories and all products each category
I'm trying to have a page where I loop over all my categories and all the products in each category. Something like this: Category 1: product1 product2 product3 Category 2: product1 product2 product3 Category 3: product1 product2 product3 views.py def model_categories_view(request): context = { "categories": ProductCategory.objects.all(), "models": ProductModel.objects.filter(???), } return render(request=request, template_name='main/categories.html', context=context) categories.html {% for category in categories %} <h1>{{category.title}}</h1> {% for model in models %} {{model.title}} {% endfor %} {% endfor %} How can I list all the models for the current category being iterated? -
How can I add my class GroupAdmin to admin without getting errors?
The following is my admin.py file: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from register.models import Account, ProgramGroup class AccountAdmin(UserAdmin): list_display = ('email', 'user_id', 'date_joined', 'last_login', 'is_admin', 'is_staff') search_fields = ('email', 'user_id') readonly_fields = ('date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () class GroupAdmin(ProgramGroup): list_display = ('group_id', 'group_name', 'group_token') admin.site.register(Account, AccountAdmin) admin.site.register(ProgramGroup, GroupAdmin) However, when I try to make migrations, I get the error path('%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)), AttributeError: 'GroupAdmin' object has no attribute 'urls' If I get rid of GroupAdmin or ProgramGroup in the admin.site.register line, it will migrate, but then I can't see the list_display items in the admin interface. How should I correct this? -
Django ORM - join a subquery
I have to translate this query into Django ORM, but can't seem to get to it. I tried about every annotate/values/filter combination I could find, but I never got it to a JOIN like that (nor to correct results). I have not (yet) tried defining a custom Manager though. SELECT t.id, t.name, dt.deadline dt.deal_id FROM dealtask dt JOIN task t JOIN ( SELECT MIN(deadline) as min_deadline, task_id FROM dealtask GROUP BY task_id ) dt2 ON dt.task_id = dt2.task_id WHERE dt.deadline = dt2.min_deadline My models are the following : class DealTask(models.Model): deadline = models.DateTimeField(blank=True, null=True) deal = models.ForeignKey('Deal', on_delete=models.CASCADE) task = models.ForeignKey('Task', on_delete=models.CASCADE) class Task(models.Model): name = models.CharField(max_length=128) I want to query : for every Task t, the nearest-deadline DealTask dt related to it, and the Deal related to that dt. Is this query possible in Django ORM ? In a constant number of queries, I mean. Also, if you find a simpler query that expresses the same thing, I'm all ears. -
How to retain kwargs between the CBV calls
I have details screen where you are re-directed to a "upload" screen with the selected pk value. Also the upload screen itself can work without kwargs and in this case (absense of pk), it will pickup/create a temporary record per user and continue use it. However, when I re-direct to the "upload" screen with a pk, the value vanishes during multiple file upload def get_context_data(self, **kwargs): context = super(UploadImages, self).get_context_data(**kwargs) if "pk" in self.kwargs: context.update({'taid':self.kwargs['pk']}) elif context.get("taid") is None: context.update({'taid':self._get_usr_tmp_album()}) return context When uploading files, the form_valid is called per file which in turn get_context_data is called every time. When this happens, the self.kwargs returns empty (despite the ID is on the URL) and hence, the code resorts to create/read a temporary record for that user and return it. def form_valid(self,form): context = self.get_context_data(form=form) if self.request.is_ajax(): album_id = context['taid'] URL: http://localhost:8000/images/complete-upload/61/ Is there a way to retrieve the same ID from the URL during the CBV lifecycle? I tried the session and it got into different issues altogether. -
Dynamic extension of Django Model - how to setup the model references
I'm pretty new to Django and I'm having a problem, that I need some help to solve. My problem: 1) I have a component database (model), consisting of an arbitrary number of signals (signals in seperate model, with a foreign key to component model). 2) Based on the component model from 1) I want to create two unique model-instances based on the same component, however with a unique "component" name, system and project-number, fx. Valve1 and Valve2. 3) Moreover each signal from 1) in 2) must inheriting the name of 2) (Valve1), combined with its own name from 1). 4) In addition it should be possible to add an arbitrary number of unique alarms to each signal. I find it difficult to setup the django models in a way to handle the above desires, maybe someone can help me out. I have attached a visualization of the problem, see visualization of problem A snippet of the code: component model Signal model + unfinished alarm model Thanks in advance! /Esben -
How to handle multiple parameters for django url?
I'm trying to pass 2 parameters to a url in django but he is joining the 2 values. In the template I do: <a href="{% url 'update' user.id user.slug %}"</a> And in urls.py I receive the parameters as follows: urlpatterns = [ path('update/<pk>_<slug>', Update, name='update'), ] But the browser shows the two values concatenated and not separated by _. That way I can't handle the id. For example if id = 25 and slug = Richard appears updtate / 25Richard and not updtate / 25_Richard. How do I handle parameters in urls.py? -
Django Model TestCase to retrive and update data
I have a Django Model Class. from django.core.validators import MinLengthValidator from django.db import models Create your models here. class Customer(models.Model): First_name = models.CharField(max_length=25, null=False) Last_name = models.CharField(max_length=25, null=False) Premium_customer = models.CharField(max_length=3, choices=((False, 'No'), (True, 'Yes'))) Reliability_rating = models.IntegerField(null=False) Customer_since = models.DateField(null=False) Cell_Phone = models.CharField(max_length=15, null=False) Home_Phone = models.CharField(max_length=15, null=False) e_mail = models.CharField(max_length=25, null=False) Created_date = models.DateField(null=False, auto_now_add = True) Updated_date= models.DateField(null=False, auto_now = True) def __str__(self): return self.First_name + ' ' + self.Last_name class Meta: ordering = ['First_name'] class Address(models.Model): customer = models.ForeignKey(Customer, max_length=10, on_delete='cascade') Street = models.CharField(max_length=50, null=False) City = models.CharField(max_length=25, null=False) State = models.CharField(max_length=20, null=False) Zip = models.CharField(max_length=11, null=False) Created_date = models.DateField(null=False, auto_now_add = True) Updated_date= models.DateField(null=False, auto_now = True) def __str__(self): return self.Street + ' ' + self.City+ ' ' + self.State + ' ' + self.Zip class Meta: ordering = ['Street'] class Order(models.Model): Order_Number = models.AutoField(primary_key=True, max_length=10) customer = models.ForeignKey(Customer, max_length=10, on_delete='cascade') Payment_method = models.CharField(max_length=10, null=False) Payment_acc_number = models.CharField(max_length=20, null=False) payment_acct_security_code = models.IntegerField(null = False) Order_total = models.DecimalField(max_digits= 10, decimal_places=2) Created_date = models.DateField(null=False, auto_now_add = True) Updated_date= models.DateField(null=False, auto_now = True) def __str__(self): return str(self.Order_Number) + ' ' + str(self.Created_date) class Meta: ordering = ['customer'] class Order_Details(models.Model): order = models.ForeignKey(Order, related_name='orders', on_delete='cascade') Product_name = models.CharField(max_length=10, null=False) … -
Best way to store web page content in database using Django and a single template for web pages
I'm building a web site and the bulk of the content will be the same general type and layout on the page. I'm going to use a single template to handle each post and the actual content will be stored in a database. The content will just be html paragraphs, headers, sub headers, different lists, quotes, code blocks, etc. Web pages will typically be the same or at least similar. All html components should follow the same guidelines to make sure everything looks and feels the same. Currently I'll be the only author, but in the future I plan to incorporate other authors as well. At first I thought, just copy and paste this html content into a textfield in the database and I can add new posts/articles on the admin site. Then I thought, maybe use a textfield and copy and paste json of a list of ['type': , 'content': ]. and then I can have the single template page iterate over this list and display the content based on the 'type'. My idea here is that it would shorten the data I have to add to the database by stripping the html tags out of the equation. Considering … -
Images appearing as broken images in Django project
I'm getting a broken image in a django project, but as far as I have checked, the code looks right. Here's the code in settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have also imported the media option in the templates section: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] Here's the code I'm using in the template. {% if request.user.profile.picture %} <img src="{{ request.user.profile.picture.url }}" height="35" class="d-inline-block align-top rounded-circle"> {% else %} <img src="{% static 'img/default-profile.png' %}" height="35" class="d-inline-block align-top rounded-circle"> {% endif %} The default-profile.png image is loading correctly, but the other profile pictures are not, although they have been loading correctly to the media folder and their urls are displayed correctly in the database. Anyone knows what I'm doing wrong? -
Hosting Django API on Elastic Beanstalk
I've got the following project setup: - Vue project hosted on S3 - Django project for API use only I used EBCLI to deploy everything and have almost everything checking off green except for these messages: Environment health has transitioned from Warning to Severe. 100.0 % of the requests are failing with HTTP 5xx. ELB processes are not healthy on all instances. ELB health is failing or not available for all instances. Environment health has transitioned from Severe to Warning. 100.0 % of the requests are failing with HTTP 5xx. Configuration update completed 34 seconds ago and took 67 seconds. There is no index.html for this project since all URLs are API endpoints for a SQlite file. I'm not exactly sure what it refers to with the requests it is checking. How can I go about narrowing down what the problem is? -
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package while importing models from database
I am trying to pull the data from admin pannel. But when i print the post object here,it throws the error.**strong text I have tried almost every method but nothing seems working views.py** from django.template import RequestContext from django.shortcuts import render, get_object_or_404 from .models import Mam def index(request): question = Mam.objects.all() #question = get_object_or_404(Mam) context = {'latest_question_list': question} return render(request, 'index.html', context) models.py from django.db import models # Create your models here. class Mam(models.Model): name = models.TextField(max_length=60) def __str__(self): return self.name index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> {%for i in context %} <p>{{ i }}</p> {% endfor%}`enter code here` </head> <p></p> <body> </body> </html> -
Saving data to Admin using form
i have problem showing/saving my image file in Admin from Django. I do not know if i explain this properly but an image attachment could. I want the image i commented on to display/save in commented_image as shown empty in Admin. class Comments (models.Model): comment_post = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) commented_image = models.ForeignKey('Image', on_delete=models.CASCADE, related_name='comments', null=True, blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Comment' verbose_name_plural = 'Comments' ordering = ['-date'] def __str__(self): return self.author.__str__() def home(request): all_images = Image.objects.filter(imageuploader_profile=request.user.id) users = User.objects.all() next = request.GET.get('next') if next: return redirect(next) form = CommentForm(request.POST) if request.method == "POST": if form.is_valid(): text = form.save(commit=False) text.author = request.user text.save() return redirect('/') else: form = CommentForm() context = { 'all_images': all_images, 'users': users, } return render(request,'home.html', context,) -
Django generate Model Fields from an Array
I need to generate a DB Model from an array of strings like this: array = ['String 1', 'String 2', ..., 'String N-1', 'String N'] I created my Model Class like this: class FixedCharField(models.Field): def __init__(self, max_length, *args, **kwargs): self.max_length = max_length super(FixedCharField, self).__init__(max_length=max_length, *args, **kwargs) def db_type(self): return 'char(%s)' % self.max_length class MyModel(models.Model): array = get_my_array() # aux function to generate the array origin = FixedCharField(max_length=3) for item in array: item = FixedCharField(max_length=3) As you can see, I need each column name to have a fixed size of 3, so I used the custom FixedCharField that I found in this link Fixed Char Field My question is, will this work? And this is the correct approach to do this? -
Django: How PointField data is stored in the DB?
I was checking the info stored in my database and found that PointFields are stored in a way I could not understand. In this table, my PointField is the field location: | id | created | modified | address | location | |----+-------------------------------+-------------------------------+------------------------+----------------------------------------------------| | | | | | | | 1 | 2019-08-20 16:36:06.235351+00 | 2019-08-20 16:36:06.235351+00 | Evergreen Terrace, 123 | 0101000020E610000000000000000000000000000000000000 | | | | | | | What type of data is it? And if I had to read it without Django PointField, how could I do it? -
Django sessions save only one object
I am building online store and want to use sessions to allow anonymous users to add items to carts before logging in . trying to save the added items in session as a list but it saves only last object added to list def cart(request): user_id = request.user.id cart_items =Cart.objects.all().filter(user_id=user_id, is_ordered=False) ids = request.session.get('cart_id') if ids: for cart_id in ids: if request.user.is_authenticated: cart = Cart.objects.get(id=cart_id) if cart: cart.user = request.user cart.save() # get total prices prices = [] for item in cart_items: prices.append(item.item.price * item.qty) total_price = sum(prices) context = { 'items': cart_items, 'total_price': total_price } request.session['prices'] = prices return render(request, 'cart.html', context) def add_to_cart(request): if request.user.is_authenticated: item = Item.objects.get(pk=request.POST['item_id']) cart = Cart.objects.filter( user=request.user, item=item, is_ordered=False).first() if cart: cart.qty += 1 cart.save() messages.success(request, 'item added to cart!') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: cart = Cart(user=request.user, item=item) cart.save() messages.success(request, 'item added to cart!') else: carts_ids = [] session_cart = request.session.get('cart_id') item = Item.objects.get(pk=request.POST['item_id']) if session_cart : for cart in session_cart: carts = Cart.objects.all().filter(id=cart, item=item) if carts: cart = carts.filter(item=item)[0] print(cart.qty) cart.qty += 1 cart.save() else: print('new cart') new_cart = Cart(item=item) new_cart.save() carts_ids.append(new_cart.id) request.session['cart_id'] = carts_ids else: print('new session') new_cart = Cart(item=item) new_cart.save() carts_ids.append(new_cart.id) request.session['cart_id'] = carts_ids return HttpResponseRedirect(request.META.get('HTTP_REFERER')) here are my models.py and … -
PWA with Django
I developed a small prototype in django with one model: Profile, and 2 templates with 2 views (a list of profiles, and an edit profile page), with a form in forms.py. I want to test creating a PWA with Django and this is the additional things I did: 1) pip install django-progressive-web-app, 2) added 'pwa' to installed apps, 3) added a render view for the base.html that will be using the service worker! def base(request): return render(request,'app/base.html') 4) added it to the urls: urlpatterns = [ path(r'', profiles, name="profiles"), path('user/<pk>', profile, name="profile"), path('', include('pwa.urls')), ] 5) added this to recognise the service worker: PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'posts/static/js', 'serviceworker.js') 6) added the tags: {% load pwa %} <head> ... {% progressive_web_app_meta %} ... </head> 7) and added this to a serviceworker.js file, situated in the app/static/js: var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/base_layout' ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('/base_layout')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); What happened is that the service worker is running under Chrome developer tool, but in the … -
understanding what Serializers do and how they do and also where can i log my request in case of class based views
I have this code which for my views class QuestionViewSet(viewsets.ModelViewSet): queryset=Question.objects.all() lookup_field="slug" serializer_class=QuestionSerializer permission_classes=[IsAuthorOrReadOnly,IsAuthenticated] def perform_create(self, serializer): print("user is", self.request.user) serializer.save(author=self.request.user) and this code for serializers class QuestionSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) created_at = serializers.SerializerMethodField() slug = serializers.SlugField(read_only=True) answers_count = serializers.SerializerMethodField() user_has_answered = serializers.SerializerMethodField() print("author in serializer", author) class Meta: model = Question exclude = ["updated_at"] def get_created_at(self, instance): return instance.created_at.strftime("%B %d, %Y") def get_answers_count(self, instance): return instance.answers.count() def get_user_has_answered(self, instance): request = self.context.get("request") return instance.answers.filter(author=request.user).exists() Then i have this code for models class Question(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) content = models.CharField(max_length=240) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="questions") def save(self, *args, **kwargs): if not self.id: # Newly created object, so set slug self.slug = slugify(self.content) super(Question, self).save(*args, **kwargs) What i basically fail to do is to log the request .In case of function based i could easily log the request and see as what data is coming .However in case of class based views i fail to do this . Also , I don't understand as where data is being saved in case of post request .I don't see ny save etc . Please enlighten as how this works fine ? -
get_context_data method Django
# views.py from django.views.generic import ListView from books.models import Publisher class PublisherList(ListView): model = Publisher context_object_name = 'my_favorite_publishers' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['number'] = random.randrange(1, 100) return context What does calling get_context_data with super() return? What type of information? And is the returned context from get_context_data given the contexT_object_name 'my_favorite_publishers'? -
django discussion about the structure of the database
I have a database question. I use django to save measurements. Since there are many different measured values to be saved, the question of the database structure. my idea is that the user can create a new instance of an object for a series of measurements. unfortunately, django would save all data in a table. I would actually like to create a new table for each series of measurements (which can also be infinitely long). I don't know if that works at all. hence my question whether it is moderately poor to save many different series of measurements in a table or whether it doesn't matter? -
Return redirect with variable
I have this code inside a function : today = (datetime.now() + timedelta(days=0)).strftime("%Y-%m-%d") quicklink_t = f"?start_date={today}&end_date={today}" w_today = quicklink_t return redirect('workspace-detail', token=workspace.token) But I want to add the variable w_today at the end of my redirect link to specify some parameters. How could I achieve that ? Thanks -
Django-filter with ModelChoiceFilter filter displaying {key:value}
I'm using ModelChoiceFilter and provided the queryset the following queryset in the filter.py: filters.py class PagosFilter(django_filters.FilterSet): semana = django_filters.ModelChoiceFilter( queryset=Pagos.objects.order_by('semana').distinct('semana').values('semana')) class Meta: model = Pagos fields = ['semana', ] in the HTML I'm getting the filter presents the choices like this: {'semana':'2020-W06'} {'semana':'2020-W05'} {'semana':'2020-W04'} instead of: 2020-W06 2020-W05 2020-W04 How can I get the values like that?