Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template inheritance: passing for loop iterable
I am developing a dictionary application using Django. One of the main themes of the app is displaying feeds of definitions. Specifically, I have: an "index" feed where new definitions are listed, a "headword" feed where definitions of a particular headword are listed, and a "tag" feed where definitions tagged with a particular tag are listed. index.html: {% block body %} <h1>Definitions</h1> <ul> {% for definition in definitions %} <li> Headword: {{ definition.headword }} <br> Definition: {{ definition }} <br> Example: {{ definition.example }} <br> Tags: <ul> {% for tag in definition.tags.all %} <li>{{ tag }}</li> {% empty %} <li>No tags.</li> {% endfor %} </ul> </li> {% empty %} <li>No definitions.</li> {% endfor %} </ul> {% endblock %} headword.html: {% block body %} <h1>{{ headword }}</h1> <ul> {% for definition in headword.definitions_headword.all %} // same code as above tag.html: {% block body %} <h1>{{ tag }}</h1> <ul> {% for definition in tag.definitions_tag.all %} // same code as above Clearly, I need a base feed.html template that these three files can share. For the h1 tag no problem. However, how can I pass the name of the iterable variable in the three for loops? I tried nesting a {% block iterable … -
Django-admin-site does not work with webpack
I'm using webpack dev-server to run my static files, and everything works fine, but my django-admin-site does not load styles. My settings.py STATIC_URL = 'http://127.0.0.1:8080/' CRISPY_TEMPLATE_PACK = 'bootstrap4' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "dist") ] webpack.config.js const webpack = require('webpack'); module.exports = { mode: 'development', entry: { main: './static/js/index.js' }, output: { publicPath: 'http://127.0.0.1:8080/' }, resolve: { extensions: ['.ts', '.js' ], modules: ['/static/js/', 'node_modules'], alias: {}, }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }) ], module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.(scss)$/, use: ['style-loader', 'css-loader', 'sass-loader'] }, { test: /\.(svg|eot|woff|woff2|ttf)$/, loader: 'file-loader', options: { outputPath: 'fonts' } } ], }, } When I change STATIC_URL to /static/ then my django-admin-site works perfect with styles but my entire app doesn't load styles. Is there any way to make it work together? -
DateTimeField.strftime() replaces the original value
I have a ticket system, where I have tickets with following mode: state = models.IntegerField(default=1, choices=TICKET_STATES) type = models.IntegerField(default=9, choices=TICKET_TYPE) priority = models.IntegerField(default=2, choices=TICKET_PRIORITY) heading = models.CharField(max_length=255, default='Uusi tiketti') description = models.TextField(default='') date_modified = models.DateTimeField(auto_now=True, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) date_closed = models.DateTimeField(null=True, blank=True) created_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='tickets_created' ) modified_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='tickets_modified' ) closed_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='tickets_closed' ) Now, I made a function that converts an instance to a dict, so I can pass it through API def as_dict(self): data = model_to_dict(self) data['created_by'] = { 'id' : self.created_by.id, 'name' : self.created_by.full_name() } data['state'] = { 'id' : self.state, 'name' : self.get_state_display(), 'color' : self.get_color() } data['priority'] = { 'id' : self.priority, 'name' : self.get_priority_display() } data['type'] = { 'id' : self.type, 'name' : self.get_type_display() } print(type(self)) print(type(self.date_created)) data['date_created'] = self.date_created.strftime('%Y-%m-%d %H:%M:%S') return data However, issue is that if I then try to do anything, I get following complaint: AttributeError: 'str' object has no attribute 'strftime' This makes me think that strftime somehow converts the DateTimeField to str, but this should not be the case? Anyone have an idea what is happening here? -
Pre-populate DateTimeField with specific date in django migration
I want to create and pre-populate DateTimeField with specific date for already existing objects. models.py publish_date = models.DateTimeField(verbose_name=_('publish date')) I try to create a nullable field first, fill it with some data and then remove the null=True from it: migrations.py def set_default_publish_date(apps, schema_editor): MyModel = apps.get_model('myapp', 'MyModel') MyModel.objects.all().update(publish_date=datetime.date(day=1, month=1, year=2019)) class Migration(migrations.Migration): dependencies = [ ('myapp', '0005_auto_20200831_1208'), ] operations = [ migrations.AddField( model_name='mymodel', name='publish_date', field=models.DateTimeField(null=True, verbose_name='publish date'), preserve_default=False, ), migrations.RunPython(set_default_publish_date, migrations.RunPython.noop), migrations.AlterField( model_name='mymodel', name='publish_date', field=models.DateTimeField(verbose_name='publish date'), preserve_default=False, ), ] As a result of running migrations I get an error: django.db.utils.OperationalError: cannot ALTER TABLE "myapp_mymodel" because it has pending trigger events What can I do to fix it? -
Django how to integer field start zero?
(sorry my bad english) i have a integer field my models.py.i use this for phone numbers.and phone numbers start zero(0) or plus(+).and when i write this field:05555555 this will be display:5555555.how i do this i write 05555555 and display 0555555?i tried phone number field but working with problem.here my models.py: from django.db import models from django.contrib.auth.models import User class elan(models.Model): cixis_yeri = models.CharField(max_length=150) catma_yeri = models.CharField(max_length=150) cixis_vaxti = models.DateField() catma_vaxti = models.DateField() elaqe_nomresi = models.IntegerField() sirket = models.CharField(max_length=100,blank=True,null=True) elave_melumatlar = models.TextField(null=True,blank=True) silinme_vaxti = models.DateTimeField() user = models.ForeignKey('auth.User',verbose_name='paylasan',on_delete=models.CASCADE) favorit = models.ManyToManyField(User,blank=True,related_name="favorit") def __str__(self): return self.cixis_yeri class Meta: ordering = ['-id'] forms.py: from django import forms from .models import elan class elanform(forms.ModelForm): class Meta: model = elan fields = [ 'cixis_yeri', 'catma_yeri', 'cixis_vaxti', 'catma_vaxti', 'elaqe_nomresi', 'elave_melumatlar', 'sirket', ] labels = { 'cixis_yeri':"Çıxış Yeri", 'catma_yeri':"Çatma Yeri", 'cixis_vaxti':"Çıxış Vaxtı", 'catma_vaxti':"Çatma Vaxtı", 'elaqe_nomresi':"Əlaqə Nömrəsi", 'elave_melumatlar':"Əlavə Məlumatlar", 'sirket':"Şirkət", } widgets = { 'cixis_yeri': forms.TextInput(attrs = {'class':'form-control kendi','placeholder':'Olke-Seher','id':"exampleFormControlInput1"}), 'catma_yeri': forms.TextInput(attrs = {'class':'form-control kendi','placeholder':'Olke-Seher'}), 'cixis_vaxti': forms.DateInput(attrs = {'class':'cixis_vaxti','type':'date'}), 'catma_vaxti': forms.DateInput(attrs = {'class':'catma_vaxti','type':'date'}), 'elave_melumatlar': forms.Textarea(attrs = {'class':'form-control kendi','placeholder':'elave_melumatlar(Vacib Deyil)','type':'text','id':'exampleFormControlTextarea1','rows':'6','columns':'2'}), 'sirket': forms.TextInput(attrs = {'class':'form-control kendi','placeholder':'(Vacib Deyil)','type':'text','id':'exampleFormControlTextarea1','rows':'6','columns':'2'}), 'elaqe_nomresi': forms.NumberInput(attrs = {'class':'form-control kendi','placeholder':'Elaqe','id':"exampleFormControlInput1"}), } please help me.thanks now. -
Unable to create api for generic relationship in django
I'm trying to create api endpoint for generic relationship but I'm facing error. Here I'm using model viewset. My code is same as describe in django rest frameworks docs https://www.django-rest-framework.org/api-guide/relations/#generic-relationships But I'm facing error. -
Heroku with Django, Celery and CloudAMPQ - timeout error
I am building an online shop, following Chapter 7 in the book "Django 3 by Example." Everything works fine in my local machine. It also works well when I deploy it to Heroku. However, when I try to use Celery and RabbitMQ (CloudAMQP, Little Lemur, on Heroku), the email message the worker was supposed to send to the customer is not sent. The task takes more then 30 seconds and then it crashes: heroku[router]: at=error code=H12 desc="Request timeout" method=POST I have created a tasks.py file with the task of sending emails. My settings.py file include the following lines for Celery: broker_url = os.environ.get('CLOUDAMQP_URL') broker_pool_limit = 1 broker_heartbeat = None broker_connection_timeout = 30 result_backend = None event_queue_expires = 60 worker_prefetch_multiplier = 1 worker_concurrency = 50 This was taken from https://www.cloudamqp.com/docs/celery.html And my Profile is as follows, web: gunicorn shop.wsgi --log-file - worker: celery worker --app=tasks.app Am I missing something? Thanks! -
How to use same JavaScript file on two pages with same element ids?
I have created two django template pages with almost same functionality and therefore may of the elements have same ids.....so I reffered the same javascriipt file in both the templates... but now it doesn't work because I suppose both the pages have similar ids of the elements. What should I do so that the js knows to modify only the element on the page which called the function not the other page which has an element with the same id -
TemplateColumn with button and form only returns name of record not content
I am trying to add a button with some functionality in a table that returns some info to the view using a POST: class ProductTable(django-tables2.Table): Template = (f"""<form action="/product_all/" method="POST">{{% csrf_token %}} <button> <input type="hidden" name="store_id" value="{{ record.get_store_id }}"/>view</button> </form>""") view = TemplateColumn(Template) But when printing the request I get: <QueryDict: {'store_id': ['{ record.get_store_id }'], 'csrfmiddlewaretoken': ['...']}> instead of the value. -
Asking for advice on how to get current form data before .save() in django
I have a model called Class which has a ManyToManyField with Student Model. I also have a form called ClassForm for Class Model. My question is how can I filter the Student Model with the field I select in ClassForm? The code are down below and I will explain more about my question. models.py # Student model class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) year = models.CharField(max_length=50) department = models.CharField(max_length=100) studentID = models.CharField(max_length=50) def __str__(self): return '%s , %s , %s' % (self.studentID, self.department, self.year) # Class model class Class(models.Model): department_choice = ( ('TC', 'TC'), ('GIC', 'GIC'), ('GEE', 'GEE'), ('GIM', 'GIM'), ('OAC', 'OAC'), ('OTR', 'OTR'), ('GCI', 'GCI'), ('GGG', 'GGG'), ('GRU', 'GRU') ) year_choice = ( ('year 1', 'Year 1'), ('year 2', 'Year 2'), ('year 3', 'Year 3'), ('year 4', 'Year 4'), ('year 5', 'Year 5') ) teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) # student class_in_department = models.CharField(max_length=100, choices=department_choice) class_in_year = models.CharField(max_length=50, choices=year_choice) subject = models.CharField(max_length=150) forms.py class ClassForm(forms.ModelForm): class Meta: model = Class fields = ['class_in_department', 'class_in_year', 'subject', 'student'] widgets = {'student': forms.CheckboxSelectMultiple} def __init__(self, *args, **kwargs): super(ClassForm, self).__init__(*args, **kwargs) self.fields['class_in_department'].widget.attrs.update(department_attr) self.fields['class_in_year'].widget.attrs.update(year_attr) self.fields['subject'].widget.attrs.update(subject_attr) self.fields['student'].queryset = Student.objects.filter(department="GIC") As you can see I filtered the student field with department="GIC" (last line). … -
AWS+Django+Nginx Unable to server static files
I am having a hard time getting my static files on the website whenever i run the server its shows ""GET /static/css/agency.css HTTP/1.1" 404 179" I am pretty new to django and trying a basic portfolio app here is my configuration 1. /home/ubuntu/portfolder inside (port folder) portproject inside (django project folder) __init__.py __pycache__ asgi.py settings.py urls.py wsgi.py django.ppk app.sock port_pics logfile manage.py media protappli inside (django app folder) __init__.py __pycache__ admin.py apps.py forms.py migrations models.py templates templatetags tests.py views.py static admin css custom img js mail scss vendor The settings.py file STATIC_URL = '/static/' STATIC_ROOT = '/home/ubuntu/portfolder/static/' '''STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static/'), ]''' nginx config file server { #listen [::]:80; listen [::]:1234; server_name 13.59.57.0 ec2-13-59-57-0.us-east-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/portfolder/app.sock; } location /static/ { autoindex on; root /home/ubuntu/portfolder; proxy_pass http://13.59.57.0:8000/home/ubuntu/portfolder/static/; #expires 7d; } location /media/ { autoindex off; root /home/ubuntu/portfolder; expires 7d; } location ~* .(jpg|svg|jpeg|gif|png|ico|css|zip|rar|pdf)$ { alias /home/ubuntu/portfolder/; error_page 404 = 404; } } I have tried doing everything i had referred to 10-12 similar queries from stack overflow but none of them showed any promising results. thanks in advance -
ERROR: Twisted-20.3.0-cp39-cp39-win_amd64.whl is not a supported wheel on this platform
I was installing django channels and I got an error that twisted was not installed. I tried installing it after downloading the package from here https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted. But now I am getting this error. ERROR: Twisted-20.3.0-cp39-cp39-win_amd64.whl is not a supported wheel on this platform. Is there a way to install it properly in windows 10. I am using python 3.8. Thanks -
What is the best way to authenticate the same user from the same database but the different applications (e.g. Django and Node js)?
I have created a registration and login system in Django 3.0 framework. In the backend, I am using the MYSQL database. And it is running on EC2-instance-1. There is a Nodejs script running on the other EC2-instance-2. Connected to MYSQL database which is hosted on EC2-instance-1 So, I have registered a user from the Django app and I also can authenticate that user. But when I try to authenticate the same user from Node js Script connected to the same database it won't work. What is the best way to authenticate the same user from the same database but the different applications (e.g. Django and node js)? -
Get multiple objects in one query in Django
I have 3 models: class Ticket(models.Model): id = models.CharField(primary_key=True, max_length=20, null=False) title = models.CharField(max_length=255, blank=False, null=True) description = models.TextField(blank=False, null=True) class Attachment(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) file = models.FileField(blank=True, null=True, upload_to='attachments/') class Comment(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) comment = models.TextField(null=False) In my views.py file in want to process all of them, so in order to get them I perform 3 queries: tickets = Ticket.objects.filter(id=ticket_id) attachments = Attachment.objects.filter(ticket=ticket_id) comments = Comment.objects.filter(ticket=ticket.id) I want to hit database just once, so my question is how can I get them in one query? I have read about select_related() method, but Attachment and Comment models are not related directly to each other, so I can't start query from any of them. From the other hand Ticket model doesn't have fields like attachment or comment so I can't start query from it. -
Bootstrap Dropdown appears behind other elements
I have a template that mix bootstrap accordion and dropdown, the problem is that dropdown appears behind the next question card or what is the same, inside your card and is not seen. template.html: <div class="card-body"> <!-- Acordion --> <div class="accordion" id="dlns_faqs_acordion"> {% for element in elements %} <div class="card"> <div class="card-header dlns_faqs_acordion_heading" id="dlns_faqs_acordion_heading_{{ forloop.counter0 }}"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#dlns_faqs_acordion_content_{{ forloop.counter0 }}" aria-expanded="false" aria-controls="dlns_faqs_acordion_content_{{ forloop.counter0 }}"> {{ element.question }} </button> </h2> <!-- Options --> <div class="dropdown"> <button class="btn dlns_elements_button" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="fas fa-ellipsis-h"></span> </button> <div class="dropdown-menu dropdown-menu-right text-center" arial-labelledby="option_button"> ... <a>...</a> ... </div> </div> </div> <div id="dlns_faqs_acordion_content_{{ forloop.counter0 }}" class="dlns_faqs_acordion_content collapse" aria-labelledby="dlns_faqs_acordion_heading_{{ forloop.counter0 }}" data-parent="#dlns_faqs_acordion"> <div class="card-body"> {{ element.answer }} </div> </div> </div> {% endfor %} </div> </div> style.css: .dlns_faqs_acordion { border: none; } .dlns_faqs_acordion_heading { border: none; background: transparent; display: flex; flex-wrap: nowrap; justify-content: flex-start; align-items: center; flex-direction: row; align-content: space-between; } .dlns_faqs_acordion_heading button { color: var(--dlns_color_primary) !important; } .dlns_faqs_acordion_heading button.collapsed { color: black !important; } .dlns_faqs_acordion_heading button:hover { text-decoration: none; } .dlns_faqs_acordion_content { color: var(--dlns_color_tertiary); } Here there are some images with the problem: Anybody cloud help me ? Thanks in advance. -
How can i lock some rows for inserting in Django?
I want to batch create users for admin. But, the truth is make_password is a time-consuming task. Then, if I returned the created user-password list util the new users are all created, it will let front user waiting for a long time. So, i would like to do somethings like code showed below. Then, I encountered a problem. Cause I can not figure out how to lock the user_id_list for creating, someone registered during the thread runtime will cause an Dulplicate Key Error error thing like that. So, I am looking forward your good solutions. def BatchCreateUser(self, request, context): """批量创建用户""" num = request.get('num') pwd = request.get('pwd') pwd_length = request.get('pwd_length') or 10 latest_user = UserAuthModel.objects.latest('id') # retrieve the lastest registered user id start_user_id = latest_user.id + 1 # the beginning user id for creating end_user_id = latest_user.id + num # the end user id for creating user_id_list = [i for i in range(start_user_id, end_user_id + 1)] # user id list for creating raw_passwords = generate_cdkey(num, pwd_length, False) # generating passwords Thread(target=batch_create_user, args=(user_id_list, raw_passwords)).start() # make a thread to perform this time-consuming task user_password_list = list(map(list, zip(*[user_id_list, raw_passwords]))) # return the user id and password immediately without letting front user waiting so … -
How do i set default permission classes to my custom permission (Django Rest Framework)
I created a custom permission to allow users only with a specific API KEY to access my API endpoints.. from rest_framework import permissions from django.conf import settings class CustomerAccessPermission(permissions.BasePermission): def has_permission(self, request, view): is_allowed = request.META.get('HTTP_X_APIKEY') == settings.API_KEY return is_allowed How do i apply this to my REST_FRAMEWORK configurations in settings.py as a default PERMISSION_CLASS OR is there a better way for me doing this.. (NOTE: i have already handled authentication, i don't want authenticated users to access my end points) -
Is it possible to get the render initiator in django-cms?
Is there a way to find out where the render_plugin-call occurred? Example: I have a CMS Plugin A that renders its children regularly, but I want to include another CMS plugin B to also render A's child plugins, so I'd like to check in A's child plugin template wether it was initiated by parent A or parent B. -
How to implement Social Auth with django and swift?
If I am using swift to obtain the user token from social sign in like (facebook, google). How safe it will be for me to get userId from those tokens and hash it with my backend and save it in my database. So that every time, users login with social providers, their userID's will be updated and hashed. -
Render Django M2M Field with selection
I have a list of models of class A. I would now like to transfer these instances of A to an M2M field via a selection. I would like to have a selection like in the example picture. Is there already a finished widget here, or do I have to make it completely myself? enter image description here many thanks -
save the corresponding id of a selected values from a multiselect field django form
I am new to django and I am trying to implement if user selectes his category interest from a multi select form I want to save its corresponding category id in database.my django code is like below Interest table looks like category_id. category_name 101. Food **models.py** class Interest(models.Model): category_id=models.IntegerField() category_name=models.CharField(max_length=50,null=True) class User_Interest(models.Model): userCD=models.ForeignKey(User,on_delete=models.CASCADE) category_id=models.ForeignKey(Interest,on_delete=models.CASCADE) **forms.py** class UserInterestForm(forms.ModelForm): class Meta: model = User_Interest fields=['userCD','category_id'] choice=Interest.objects.all() ch_list=[] for ch in choice: ch_list.append([ch.category_name,ch.category_name]) interest = MultiSelectFormField(choices=ch_list) **admin.py** class User_InterestAdmin(admin.ModelAdmin): exclude = ('category_id',) list_display=('userCD','category_id') form=UserInterestForm Here am able to select interest in checkboxes but category id's storing category_id as "Null".Can anyone please guide me what should I need to do achieve my requirement. expected output:User_Interest table UserCd category_id xxxxx. 101 -
How to hide variables in the URL?
I am getting a "Method not allowed (POST)" error on my site and I try to understand how to avoid that. I have a django-tables2 table with a button, that calls a SingleTableView. I had a working piece of code that looked like this: class AllProductsColumn(tables2.Column): empty_values = list() def render(self, value, record): return mark_safe(f"""<a href="/product_all/{record.get_store_id}/{record.name}"> <button class="btn btn-secondary">view</button></a>""") and in the table I called it with view = AllProductsColumn(orderable=False) and this worked using this url pattern: path(r"product_all/<int:store_id>/<store_name>", views.ProductView.as_view(), name="product-all"), Then I came to the point where I wanted to make everything "nicer" and therefore hide the variables. So I rewrote the table as: ViewTemplate = (f"""<form id="params" action="/device_all/" method="POST">{{% csrf_token %}} <button class="btn btn-secondary"> <input type="hidden" name="store_id" value="{{ record.get_store_id }}"/> <input type="hidden" name="store_name" value="{{ record.name }}"/> view</button> </form>""") and changed the URL pattern to: path(r"product_all/", views.ProductView.as_view(), name="product-all"), and this obviously does not work, because the SingleTableView has no method post. So ... how can I hide my variables? view: class ProductView(SingleTableView): model = Product template_name = "app/product_all.html" table_class = ProductTable paginate_by = 10 -
Determine if Django REST Framework serializer is used in context of many=True
I have a Django REST Framework serializer that is used in several places. One of the fields is a SerializerMethodField that I only wanted to include if the serializer is used to serialize only a single object. Basically, I want to not include one of the SerializerMethodField (or change it's behavior) when I have that MySerializer(objects, many=True). Any ideas how to do this? -
I don't understand why my form is not validating in django
I am still new to django. Playing around with a leadmanager app and I don't know why my form is not validating. views def index(request): lead=LeadForm() if request.method == 'POST': lead=LeadForm(request.POST) if lead.is_valid(): messages.success(request, f'Thank you for registering. Someone will be contacting you soon.') return redirect('index') else: lead=LeadForm() messages.error(request, f'Something went wrong. Please try again later.') return render(request, "frontend/index.html", {'lead':lead}) in index.html <form action="" method="POST" class="lead-form"> {% csrf_token %} <fieldset class="lead-info"> <div class="form-control"> <label for="">Full Name</label> {{ lead.fullname }} </div> <div class="form-control"> <label for="">Email</label> {{ lead.email }} </div> <div class="form-control"> <label for="">Phone</label> {{ lead.phone }} </div> <div class="form-control"> <label for="">City</label> {{ lead.city }} </div> </fieldset> <button type="submit" class="btn-pill">Submit</button> </form> in forms.py class LeadForm(forms.ModelForm): email = forms.EmailField() class Meta: model = Lead fields = ['fullname', 'email', 'phone', 'city', 'contact_preference'] widgets = {'contact_preference': forms.RadioSelect } Any help is appreciated. contact_preference is rendering FYI, I just cut the code to keep this question not that long. -
Vue.js + Axios not assigning response
I have the following vue.js code using django as a backend. The response is coming through fine, but I can't seem to set the variable properly. Am I doing something wrong with the assignment? Thanks <script> import axios from 'axios' //Datatable export default { data () { return { items: [], } mounted () { this.getItems() }, methods: { getItems() { const newLocal='http://127.0.0.1:8000/items/' axios({ method: 'get', url: newLocal, auth: { username: 'login', password: 'pass' } }).then(response => { let result = []; result = response.data; console.log(response.data); console.log("Data length: " + response.data.length); /// Returns '7' console.log("Result length: " + result.length); /// Returns '7' this.items = result; console.log("Item length #1: " + this.items.length) /// Returns '7' }) console.log("Item length #2: " + this.items.length) /// **Returns '0' ???** },