Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to determine if a template block is empty/blank in Django?
I am using Django templates for my website, and I have a template block for the webpage's title: I have a base template (base.html), which formulates the <title> element like this: <title>{% block title %}{%endblock %} - Website Title</title> And then, in each page template, I put a block like so: {% block title %}Webpage Name Here, e.g. About Us{% endblock %} which would then give me: <title>Webpage Name Here, e.g. About Us - Website Title</title> Is there a way to determine programmatically, within the base template, the size/length/content of the title block? I want to make it so that on my homepage, there is no "-" in the title, it just says "Website Title". I figure the best way would be to do something similar to this: <title>{% block title %}{% end block %}{% if title|length > 0} - {/if}Website Title</title> ... but I can't figure out for the life of me how to determine the length of the {% block title %} which is being passed from the page template. -
Update email bcc recipient in email backend
I am building a mail backend that should add a specific address to the bcc of an email. from django.conf import settings from djcelery_email.backends import CeleryEmailBackend class BCCEmailBackend(CeleryEmailBackend): def send_messages(self, email_messages): for i, message in enumerate(email_messages): if settings.DEFAULT_BCC_EMAIL is not None: message.bcc.append(settings.DEFAULT_BCC_EMAIL) super().send_messages(email_messages) When I run my test, the bcc is not set. @override_settings(DEFAULT_BCC_EMAIL="should_be_send@bcc.de") def test_default_bcc_email(self): self.assertEqual(settings.DEFAULT_BCC_EMAIL, "should_be_send@bcc.de") msg = EmailMultiAlternatives( self.subject, self.text_content, "test@sender.de", ["test@recipient.de"] ) msg.attach_alternative(self.html_content, "text/html") msg.send() #... # This test always fails self.assertListEqual(m.bcc, ["should_be_send@bcc.de"], "Default bcc should be set") When I set the bcc directly when initialising EmailMultiAlternatives my test is succeeding. -
searchable dropdown list for adding a new post in django
hey guys in my new project I have too many data and finding a parent foreign key from a drop down list is impossible . so i need to have a search field inside my dropdown list but don't know how can i do that. #i uploaded an image below click to see image class song(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) artist = models.ForeignKey(artist, on_delete=models.DO_NOTHING) album = models.ForeignKey(album, on_delete=models.DO_NOTHING) slug = AutoSlugField(populate_from=['artist', 'name']) # s_slug = models.SlugField(max_length=250, unique=True, verbose_name="Route To") status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') song_link = models.CharField(max_length=500) video_link = models.CharField(max_length=500) name = models.CharField(max_length=150) cover = models.CharField(max_length=300) explicit_content = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) -
Is there a way to manage admin panel edit permissions by model property in Django?
So, I want to be able to control write permissions for a model in Django admin panel using model property value. Here's an example: we have a model called Organization with property is_production, which is boolean. Also, we have two roles: Developers and Customer Support. I want users from Developers group to be able to edit Organizations with is_production = False, and users from Customer Support to be able to edit ones with is_production = True. Is there a no-code / low-code way to do it, like an extension / Django battery? Thanks for your time! -
Django: CloudFront wasn't able to connect to the origin
I'm working on a Django project and it's dockerized, I've deployed my application at the Amazon EC2 instance, so currently, the EC2 protocol is HTTP and I want to make it HTTPS so I've created a cloud front distribution to redirect at my EC2 instance but unfortunately I'm getting the following error. error: CloudFront attempted to establish a connection with the origin, but either the attempt failed or the origin closed the connection. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner. If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation. Generated by cloudfront (CloudFront) Request ID: Pa0WApol6lU6Ja5uBuqKVPVTJFBpkcnJQgtXMYzQP6SPBhV4CtMOVw== docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - ./scripts/init.sql:/docker-entrypoint-initdb.d/init.sql - postgres-data:/var/lib/postgresql/data/ env_file: - prod.env app: container_name: app build: context: . restart: always volumes: - static-data:/vol/web depends_on: - db env_file: - prod.env proxy: container_name: proxy build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: Dockerfile FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV … -
Redirect for a single file with Django and Nginx
I have a Django project serving static correctly files at /static. I'd like to serve a single .txt file in the root though, without the static in the URL. This is my Nginx section: location /ms11973759.txt { try_files /home/myhome/nms/static/ms11973759.txt; } I get a 404, although I can access the file via mysite/static/ms11973759.txt. What am I missing? -
retrieve only on column in filter in dry
how I get get only one column of my model using filter ids = model1.objects.filter(key=value) return model2.objects.filter(column__in=ids) in above example first filter should return list of ids of model1 and in second example data will be return using in of 1st result ids NOTE: model1 it's having number of field and one is id -
Is it possible to create a superuser with different inputs than a simple user in Django Rest Framework?
I am beginning a new project with Django Rest Framework, and I have a specifical need on the creation of a user: to create an account, you need to give information such as your birthdate, the birthdate of a friend, and several other info. But it would NOT be relevant for a superuser to give such information, that's why I am looking for a way to require different info for user and for superuser. Do you know if it's possible ? In the file models.py, I created 2 different classes : class UserProfile(AbstractBaseUser, PermissionsMixin) class SuperUserProfile(AbstractBaseUser, PermissionsMixin) These two classes require different info to create an account. In addition, I created a class to manage user profiles : class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, name1, firstName1, email1, name2, firstName2, birthDate2, password=None): """Create a new user profile""" email1 = self.normalize_email(emailParrain) user = self.model(emailParrain=emailParrain, name1=name1, firstName1=firstName1, name2=name2, firstNameUser=firstNameUser, birthDateUser=birthDateUser) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): """Create and save a new superuser with given details""" user = self.create_user(email,password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user But when I do this, I cannot create a superuser with only the info sub-mentionned (email, name, password). -
django admin panel sort order display
hey guys i want to change the sort of my models in the admin panel with django for example i want to have the "categories" on the top of the list how can i do that? is it possible?! ` class SongAdmin(admin.ModelAdmin): list_display = ['name', 'artist', 'album', 'slug'] list_filter = ['created_date'] search_fields = ['name', 'artist__name', 'album__name'] class Meta: model = song admin.site.register(song, SongAdmin) admin.site.register(categories) admin.site.register(album) admin.site.register(artist) admin.site.register(PlayList) admin.site.register(PlayListSongs) admin.site.register(discount_codes) ` -
Some guidance on json structure to a django DRF serializer
I have a model structure like this: model: server_name: str description: str owner: str but the application sending data to my app use a json format I am not sure on how to create a serializer for. For multiple entries it looks like this { "server1": { "description": "desc of server 1", "owner": "service name" }, "server2": { "description": "desc of server 2", "owner": "service name" } } but I am not sure on how to get it into something matching my model. This is the structure I would like it to have in the serializer [ { "server_name": "server1", "description": "desc of server 1", "owner": "service name" }, { "server_name": "server2", "description": "desc of server 2", "owner": "service name" } ] Any suggestions on this one? -
Field name city is not valid for model user Django error
I am getting the error message: Field name 'city' is not valid for model 'User'. when I visit the endpoint: http://127.0.0.1:8000/update_profile/ Here is my urls.py: urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('api/register', RegisterApi.as_view()), path('update_profile/', views.UpdateProfileView.as_view(), name='update_profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is my UpdateProfileView class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer I extended my user class to include other fields in models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) profile_pic = models.ImageField(upload_to='profile/%Y/%m/%d', default='media/placeholder.png', blank=False, null=False) #we are hooking create_user_profile and save_user profile methods to the User model whenever a save event occurs. This kind of signal is called post_save @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() and my serializer: class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'bio'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], city=validated_data['city'], country=validated_data['country'], bio=validated_data['bio'], email=validated_data['email']), user.set_password(validated_data['password']) user.save() return user #updating user profile class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) class Meta: model = User … -
Get average of averages in django
I have three models like these class School(models.Model): # some fields class Class(models.Model): school = models.ForeignKey(School, related_name='classes') class Student(models.Model): class = models.ForeignKey(Class, related_name='students') degree = models.IntegerField() I want to order schools using average degree , but the average degree Isn't just the average of all the students as the number of the students in the same class are not equal so I need to get some thing like this from django.db.models import Prefetch, Avg classes = Prefetch('classes', Class.objects.all().annotate(avg_degree=Avg('students__degree')) # this line would through an error qs = School.objects.all().prefetch_related(classes) .annotate(avg_degree=Avg('classes__avg_degree')).order_by('avg_degree') of course I can't just use qs = School.objects.all().annotate(avg_degree=Avg('classes__student__degree')) this would give wrong answers -
filtering a select input in a formset so as not to have the data chosen in the new form
Hi I have someone good at filtering formsets can you help me? I have this formset where there is a select I would like to choose a field in case I add another form the select would have all the fields except the one chosen by the first form. so that each form has a free select but it cannot be repeated with the same value. views from django.forms import formset_factory from .forms import GruppiForm def crea_gruppi(request): gruppiFormSet = formset_factory(GruppiForm, extra = 1) gruppi_formset = gruppiFormSet(prefix='gruppi') context = {'gruppi_formset': gruppi_formset} return render(request, 'crea_gruppi.html', context) form class GruppiForm(forms.ModelForm): giorni_settimana = forms.MultipleChoiceField( choices = models.DatiGruppi.giorni_settimana_scelta, widget = forms.SelectMultiple() ) class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] html {% block content %} <section class="mt-5"> <div class="container"> <div class="d-flex align-items-center justify-content-between"> <h2 class="m-0 text-light">crea gruppi</h2> </div> <hr class="bg-light"> <form method="post" autocomplete="off"> {% csrf_token %} {{ gruppi_formset.management_form }} <div class="raccoglitore-gruppi"> {% for gruppo in gruppi_formset %} <div class="gruppo mb-3" style="border: 2px solid red; padding: 5px;"> <div style="color: #fff;"> {{ gruppo.dati_gruppo.label_tag }} {{ gruppo.dati_gruppo|add_class:'form-control mt-2'|append_attr:"placeholder: Gruppo" }} </div> </div> {% endfor %} </div> <div class="mt-3 text-end"> <a href="javascript:void(0)" class="btn btn-warning" id="addgrup">add</a> </div> </form> </div> </section> <div id="form-gruppo-vuoto" class="hidden"> <div class="gruppo mb-3" style="border: 2px solid red; … -
Django: Use makedirs in AWS S3
I have code that will automate CSVs and it will create a dir using makedirs with uuid dirname. The code is working on my local machine but not in S3. I am using an href to download the csv file by passing file_path in context. views.py def makedirs(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise return path def .. tmp_name = str(uuid.uuid4()) file_path = 'static/tmp/'+tmp_name+'/' file_path = makedirs(file_path) reviews_df.to_csv(file_path+'file_processed.csv', index=False) Thanks a lot! -
How to use a ManyToMany field in JsonResponse?
I have this model in Django: class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') likes = models.IntegerField(default=0) def serialize(self): return { 'id': self.pk, 'poster': self.poster.username, 'body': self.body, 'timestamp': self.timestamp.strftime('%b %d %Y, %I:%M %p'), 'likes': self.likes } It works but when I try to add likers to it, I get an error which says I can't use manytomany fields. How can I do such thing? I fetch it in JavaScript like this: fetch('/posts') .then(response => response.json()) .then(data => { console.log(data); }); Using this view: def posts_view(request): posts = Post.objects.all() posts = posts.order_by('-timestamp').all() return JsonResponse([post.serialize() for post in posts], safe=False) -
URL issues with Django 4
I've been using Django since Django 1, and I've always used the same URL patterns (except when we switched from url to path). Now I'm having an issue with 404 errors. I'll give you my Project URLS, and App URLS, and you tell me what am I doing wrong: Project: urlpatterns = [ path('adm/', admin.site.urls), path('', include('core.urls')), path('b/', include('booking.urls')), ] Booking App: urlpatterns = [ path('book/<int:s>/<str:d>/', views.book, name="book"), path('fb/', views.finalize_booking, name="finalize_booking"), ] When I try to call {% url "finalize_booking" %}, it gives me a 404 error. I had the same problem with admin, when I visit xxxx/adm, it gives me a 404 error, it works when I add the slash at the end (xxxx/adm/). This issue was never the case before Django 4. -
Don't queue Dramatiq tasks until Django transaction is committed
I'm currently using Celery but I'm seriously considering migrating to Dramatiq (and django-dramatiq) because of how much simpler things could be. Celery just seems overly complicated (especially for my usecases) and not all that reliable. However, one feature of Celery I use is the option to add a base class for each task. I add a TransactionAwareTask as a base class for most tasks (inspired by this blog post). This base class holds the task (when calling apply_async) and only actually sends it to the queue when transaction.on_commit is reached, meaning that the surrounding transaction succeeded and the task can safely be queued. This way, I will (for instance) never send an email to a client when their action actually failed. And the task will never run before the transaction is committed (which technically could happen if somehow the process was slower than the task queue). Is there a way to do this with Dramatiq? It seems dramatiq middleware might be useful (and I could turn it off for testing where transactions are not committed at all) but I'm not quite sure. Has anyone done something like this? -
Websocket wss configurations in nginx, django, daphne
I have a Django server which uses websockets (Django channels). I have the following configurations of daphne and nginx. What the right way to configure ngnix for wss websockets? Here's what I have: /etc/nginx/sites-available/trading-backend server { server_name trading-backend-test.myserver.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/vagram/trading-backend/static_root/; } location /media/ { alias /home/vagram/trading-backend/media_root/; } location /ws/ { proxy_pass http://unix:/home/vagram/run/daphne.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; } location / { include proxy_params; proxy_pass http://unix:/home/vagram/trading-backend.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/trading-backend-test.myserver.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/trading-backend-test.myserver.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = trading-backend-test.myserver.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name trading-backend-test.myserver.com; return 404; # managed by Certbot } /etc/systemd/system/daphne.socket [Unit] Description=daphne socket [Socket] ListenStream=/run/daphne.sock [Install] WantedBy=sockets.target /etc/systemd/system/daphne.service Description=WebSocket Daphne Service Requires=daphne.socket After=network.target [Service] Type=simple User=vagram WorkingDirectory=/home/vagram/trading-backend/src ExecStart=/home/vagram/trading-backend/env/bin/daphne -b 0.0.0.0 -p 8001 project.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target -
elasticsearch ApiError 406
i used Docker , elasticsearch 7.11.1 image and Django project , so when i run search with django , show me this error Please any hellp ! -
Django DRF group by parent of parent with one-to-one relationships
I'm new to Django, and the jump from SQL to the Django DRF/ORM has been fun but challenging. I'm struggling to understand how to get a sum of a field of a class while grouping by it's parent's parent: models.py : class Plan(models.Model): plan_id = models.BigAutoField(primary_key=True) date = models.DateField() quantity = models.DecimalField( max_digits=18, decimal_places=0, blank=True, null=True) plan_type = models.CharField(max_length=50) plan_line = models.ForeignKey('PlanLine', models.CASCADE) class PlanLine(models.Model): plan_line_id = models.BigAutoField(primary_key=True) year_period = models.CharField(max_length=50) line = models.ForeignKey('Line', models.CASCADE, blank=True, null=True) parent_assembly = models.ForeignKey( 'ParentAssembly', models.CASCADE, blank=True, null=True) class Line(models.Model): line_id = models.BigAutoField(primary_key=True) line_name = models.CharField(max_length=50) factory = models.ForeignKey( 'Factory', models.DO_NOTHING, blank=True, null=True) class Factory(models.Model): factory_id = models.BigAutoField(primary_key=True) factory_name = models.CharField(max_length=50) I'm trying to get Sum(Plan.quantity), group by Factory. I think I need to use the following, but don't understand how to get to Factory in this manor: Plan.objects.value(**Factory**).annotate(qty=Sum('quantity')) -
django abstractuser manytomanyfiled did not get anything
Info: I have create user abstract model in Django. the user has belong to multiple services. when i registered the user in datebase then the user has been register instead user_services. user_services are not stored in databse while we register the new user. models.py class UserAbstract(AbstractUser): user_services = models.ManyToManyField(UserServices, related_name='services', blank=True) is_expert = models.BooleanField(default=False) views.py def Register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') user = form.save() if user is not None: login(request, user) messages.success(request, f'{username} account has been registered!') return redirect('profile') else: messages.error(request, "Invalid username or password.") else: form = UserRegistrationForm() return render(request, 'user/register.html', {'form': form}) -
Django: Calculate and Group inside Django ORM with multiple columns
Good day, right now I'm trying to improve my knwoledge about djangos orm but struggling with the task below: But first, the database looks like this: class DeathsWorldwide(models.Model): causes_name = models.CharField(max_length=50, null=False, blank=False) death_numbers = models.PositiveIntegerField(default=0) country = models.CharField(max_length=50, null=True, blank=True) year = models.PositiveIntegerField(null=False, blank=False, validators=[MinValueValidator(1990), MaxValueValidator(2019)]) causes_name | death_numbers | country | year Alcohol dis. | 25430 | Germany | 1998 Poisoning | 4038 | Germany | 1998 ... Maternal dis. | 9452 | Germany | 1998 Alcohol dis. | 21980 | Germany | 1999 Poisoning | 5117 | Germany | 1999 ... Maternal dis. | 8339 | Germany | 1999 Always a block of all dieseases for each year, every country and so on...The range of years goes from 1990 to 2019. What I - or rather let's say the task - want to achieve, is a list of all countries with calculated numbers of deaths, like this... country | death_numbers France | 78012 Germany | 70510 Austria | 38025 ...but with one additional feature: the number of deaths for each country between 1990-1999 must be subtracted from those of 2000-2019. So a full list would actually look something like this: country | death_numbers | 19xx | 2xxx … -
Extract values form Django context proseccor
I'm looking for the solution for below problem. I have class Category and SubCategory. In SubCategory I take Category as ForeignKey. By contextprocessor I would like to get values of Category. ''' class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) sub_category_name = models.CharField(max_length=50, unique=True, null=True, blank=True) slug = models.SlugField(max_length=50, unique=True, null=True, blank=True) ''' By using contextprocessor I would like to extract ForeigKey value to use it later in for loop: ''' from .models import SubCategory # Create your views here. def sub_menu_links(request): sub_links=SubCategory.objects.all() print(dict(sub_links=sub_links)) return dict(sub_links=sub_links) ''' How can I do it? -
HTML/CSS : justify - center and align two icons in a cell of a table
His guys, I have this table with two icons in the last column. I would like that the icons are next to each, align and with a nice space in the cell. What are the parameters required for that ? I tried with justify-content and margin but it stays like that. Thank you Here is my result : How can I correct that ? Here is the code html : {% block content %} <link rel="stylesheet" href="{% static 'test15.css' %}"> <div class="upload-app"> <div class="upload-in"> <h2>Upload</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% if url %} <p>Uploaded files : <a href="{{url}}">{{url}}</a></p> {% endif %} </div> <div class="listfiles"> <h2>Files Uploaded</h2> <table id="customers"> <tr> <th>Filename</th> <th>Date</th> <th>Size</th> <th>Actions</th> </tr> {% for file in files %} <tr> <td>{{ file.Filename }}</td> <td>{{ file.Uploaded_at | date:'d.m.Y H:i'}}</td> <td>{{ file.SizeFile | filesizeformat}}</td> <td> <a href="{% url 'download' file.Id %}"> <i class='bx bxs-download'></i> </a> <a href=""> <i class='bx bxs-file-pdf' ></i> </a> </td> </tr> {% endfor %} </table> </div> </div> {% endblock %} Here the css : .listfiles{ margin-top: 20px; border-radius: 12px; background-color: #11101d; color: #fff; transition: all 0.5s ease; width: 800px; height: 600px; } .listfiles h2{ display: flex; justify-content: center; font-size : … -
Updating Django profile returns not authorized error
I would like to update an existing Django profile but getting the error message: PUT http://127.0.0.1:8000/update_profile/ 401 (Unauthorized) The specific network error I am getting is: detail: "Authentication credentials were not provided." This is what the event listener triggered when my update profile button is clicked: const handleSubmit = e => { e.preventDefault(); console.log('handle submit',profileUser) const updatedProfileInfo = { username: profileUser.username, email: profileUser.email, first_name: profileUser.first_name, last_name: profileUser.last_name, city: profileUser.city, country: profileUser.country } console.log(updateProfile) updateProfile(updatedProfileInfo); } updateProfile is destructured from useContext here: let { user,logOutUser, updateProfile } = useContext(AuthContext) here is the updateProfile function: const updateProfile = (userData) => { axios .put('http://127.0.0.1:8000/update_profile/', { headers: { Authorization: "Bearer" + window.localStorage.getItem('authTokens').access, 'Accept' : 'application/json', 'Content-Type': 'application/json' }, body: userData }) .then(res => { console.log(res) }) } I pass updateProfile to my Profile through ContextData: let contextData = { user:user, loginUser:loginUser, logOutUser:logOutUser, updateToken: updateToken, updateProfile: updateProfile } ... return( <AuthContext.Provider value={contextData} > {children} </AuthContext.Provider> ) This is how my access token is stored in localStorage authTokens: {"access":****,"refresh":*****}