Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Xero OAuth2
I'm really struggling with applying the xero python SDK examples as they are for flask, and I'm working in Django. Having read the xero pages there's no planned django tutorial. Has anyone here already solved how to apply the settings in a multi tenant app ? -
autocomplete_fields in django admin doesn't work well when the name contain a pipeline(|) in it
i have three simple models : models.py from django.db import models class Name(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Last(models.Model): First = models.ForeignKey(Name, on_delete=models.CASCADE) last = models.CharField(max_length=100) def __str__(self): return '{0} | {1}'.format(self.First, self.last) class Id_cart(models.Model): full = models.ForeignKey(Last, on_delete=models.CASCADE) and as you can see the str method in class "Last" returns a string with a | . and in the admin.py i want to use autocomplete_fields in the "Id_cart" model and for "full" field: admin.py from django.contrib import admin class FullAdmin(autocomplete_all.ModelAdmin): list_display = ['full'] search_fields = ['full'] autocomplete_fields = ['full'] admin.site.register(Id_cart,FullAdmin) But still in the admin page the autocomplete_fields doesn't work correctly and give this message on the search area: The results could not be loaded -
Correct way to use create_or_get with DRF
I have the following models. class Word(models.Model): """Word object""" word = models.CharField(max_length=255, unique=True) def __str__(self): return self.word class Category(models.Model): """Category object""" category = models.CharField(max_length=255, unique=True) def __str__(self): return self.category class Group(models.Model): """Group object""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) group = models.CharField(max_length=255) categories = models.ManyToManyField("Category") words = models.ManyToManyField("Word") def __str__(self): return self.group class Puzzle(models.Model): """Puzzle object""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) puzzle = models.CharField(max_length=255) groups = models.ManyToManyField("Group") def __str__(self): return self.puzzle The following views class WordViewSet(viewsets.ModelViewSet): """Manage words in the database""" search_fields = ["word"] filter_backends = (filters.SearchFilter,) queryset = Word.objects.all() serializer_class = serializers.WordSerializer http_method_names = ["get", "post"] class CategoryViewSet(viewsets.ModelViewSet): """Manage categories in the database""" search_fields = ["category"] filter_backends = (filters.SearchFilter,) queryset = Category.objects.all() serializer_class = serializers.CategorySerializer http_method_names = ["get", "post"] class GroupViewSet(viewsets.ModelViewSet): """Manage groups in the database""" queryset = Group.objects.all() serializer_class = serializers.GroupSerializer permission_classes = [IsOwner, ] def get_serializer_class(self): """Return appropriate serializer class""" if self.action == "retrieve": return serializers.GroupDetailSerializer return self.serializer_class def perform_create(self, serializer): serializer.save(user=self.request.user) class PuzzleViewSet(viewsets.ModelViewSet): """Manage puzzles in the database""" queryset = Puzzle.objects.all() serializer_class = serializers.PuzzleSerializer permission_classes = [IsOwner, ] def get_queryset(self): queryset = Puzzle.objects.all() user = self.request.query_params.get("user") if user is not None: queryset = Puzzle.objects.filter(user=user) return queryset def get_serializer_class(self): """Return appropriate serializer class""" if self.action == … -
Django query for model with a single DateField used for tracking state changes
I have searched all over StackOverflow / Reddit / etc, but can't seem to find anything like this. Assuming we have the following model (purposely simplified): class X(models.Model): related_object = models.ForeignKey(Y) start_date = models.DateField(unique=True) is_rented = models.BooleanField() Where model X is tracking state changes of an instance of model Y. It could be tracking something like the state of cars at a car rental agency that may be rented out. A new instance of the model is created each time the state of each car changes. The resulting objects might look something like this: {"id" : 1, "related_object" : 2, "start_date" : "2021-03-03", "is_rented" : False}, {"id" : 2, "related_object" : 2, "start_date" : "2021-03-06", "is_rented" : False}, {"id" : 3, "related_object" : 2, "start_date" : "2021-03-10", "is_rented" : True}, {"id" : 4, "related_object" : 2, "start_date" : "2021-03-15", "is_rented" : False}, {"id" : 5, "related_object" : 2, "start_date" : "2021-03-16", "is_rented" : True}, {"id" : 6, "related_object" : 4, "start_date" : "2021-03-16", "is_rented" : False}, {"id" : 7, "related_object" : 2, "start_date" : "2021-03-17", "is_rented" : False}, {"id" : 8, "related_object" : 4, "start_date" : "2021-03-22", "is_rented" : True}, I want to be able to perform the following queries: … -
Updating DateTimeField in Django
I have a DateTimeField() in my models.py. What I am trying to do is to update it, along with some other values in the model. Everything else updates fine apart from my DateTimeField(). the error i get says that AttributeError: module 'datetime' has no attribute 'now' anyone see where I am going wrong with m update? sModel.objects.all().update(sPasses=pass_number_for_graph, sFails=fail_number_for_graph, sNds=p_number_for_graph, sTimestamp=datetime.now()) -
React DRF Select All the Options in the ManytoMany field by default
I am working on a project with React and DRF and currently have my models like this: class Author(models.Model): author_name = models.Charfield(max_length = 15) class Books(models.Model): book_name = models.CharField(max_length = 15) authors = models.ManytoManyField(Author) I have my models setup correctly and am able to send data to backend correctly. However, what I need is - all the options in the ManytoManyfield to be selected by default. Currently, the option is displayed in the ManytoManyfield but it is not selected. I am not sure how to go about it. I have gone through this question but am still not clear on this. Please guide me on how this is done. Thanks for your time in advance. -
Why in Django Rest Framework remove objects is showing on list?
After removing object is is still in response data. /api/premises/premises/4 returns { "detail": "Not found." } but /api/premises/premises/ returns [ { "id": 1, "image": "/product/lb-gallery-main.jpg", "owner": "owner@lebernardin.com", "name": "Le Bernardin", "description": "Le Bernardin to francuska restauracja z owocami morza na Manhattanie w Nowym Jorku. Gilbert Le Coze i jego siostra Maguy Le Coze otworzyli restaurację w Paryżu w 1972 roku, pod nazwą Les Moines de St. Bernardin.", "country": "Poland", "city": "Gdynia", "postcode": "80-209", "address": "Starowiejska 1", "tags": [ 1, 2 ] }, { "id": 4, "image": "naws.com/product/Union-Oksford.jpg", "owner": "admin@admin.com", "name": "dadad", "description": "dada", "country": "dada", "city": "dada", "postcode": "dad", "address": "dadadada", "tags": [] }, { "id": 2, "image": "196290008887877_5616210528952631689_n.jpg", "owner": "admin@admin.com", "name": "Sebastian Wrzałek", "description": "adadada", "country": "dadad", "city": "adada", "postcode": "dada", "address": "dadadadaddd", "tags": [] } ] Weird that it is not displayed on Django Admin. Also I am using Docker, after restart it is updating list and not showing deleted item. When I checked Database table directly data is correntc meaning item is removed correctly. I am thinking where it comes from and why it is cached somehow? docker-compose.yml version: "3" services: redis: image: redis command: redis-server ports: - "6379:6397" app: build: context: . ports: - "8000:8000" volumes: … -
Runing Django tests with Jenkinsfile (with docker)
i have a Django app running inside Docker (also Postgres, Nginx and Jenkins are inside docker), and i want to run tests by creating a Pipeline The problem is that every time i run it with python app/manage.py test (since the jenkisnfile is outside the project folder named "app") ,it just run an empty test.py file (so it return 0 test succesfull) even though i have actual tests. if i ran the test directly from the terminal it work $ docker-compose run web python manage.py test Creating proj1_web_run ... done Creating test database for alias 'default'... System check identified no issues (0 silenced). .......... ---------------------------------------------------------------------- Ran 10 tests in 0.229s OK Destroying test database for alias 'default'.. here is Jenkinsfile pipeline { agent { docker { image 'python:3.9' } } stages { stage('Build') { steps { sh 'pip install -r requirements.txt' } } stage('Test') { steps { sh 'python app/manage.py test' } } stage('Deploy') { steps { sh 'echo not yet...' } } } } message in Jenkins console output + python app/manage.py test System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK thank you very much for your help -
Cant get datetime formatting right
I don't know why but I always seem to have trouble formatting dates with strptime. I really can't see where I am going wrong here but this is the error I got... time data '2021-04-10 18:00:00' does not match format '%Y-%m-%d %H:%M:%S.' I appreciate any help you can give. weatherDate = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S') -
How to space bootstrap 5 cards?
So, I have a few cards, and I want them to be on the same line, so I used rows and cols. This works. But there is another problem. The problem is, they seem to squished together. I try to use margin-left or margin-right or all those spacing stuff, but none of them work. So could someone help me space these out. I am using a template for loop in django for this. <div class="row"> {% for jax in u_jaxes %} <div class="col-sm-4"> <div id="card2" class="card"> <div class="card-body"> <a href="{% url 'edit_jax' jax.title %}">{{ jax.title }}</a><br><br> <img src="https://cdn1.iconfinder.com/data/icons/logotypes/32/badge-html-5-128.png" alt="Badge, html, html5, achievement, award, reward, trophy"/ height="17" width="17"> HTML, CSS, JS <span style="float:right"> {{ jax.date_created|timesince }} ago </span> <a href="{% url 'edit_jax' jax.title %}" class="stretched-link"></a> </div> </div> </div> {% endfor %} </div> if anyone needs anything else like what css code I'm using and all, please let me know. Thanks! -
ImageField attribute has no file associated with it
I have a model, which has 3 ImageField. When loading a new entry into the database, it may have some blank images, so the value is None. When the client request the model data entry, I get in the server side: ValueError: The 'picture2' attribute has no file associated with it. How can I avoid it? class item (models.Model): certificate=models.ImageField(default=None) provider = models.ForeignKey(serviceProvider, on_delete=models.CASCADE, null=True) radius = models.FloatField(default=None) description= models.TextField(blank = True) hour_init = models.TimeField() hour_end = models.TimeField() picture1=models.ImageField(default=None, blank=True) picture2=models.ImageField(default=None,blank=True) picture3=models.ImageField(default=None, blank=True) This is the view function: def addRubro (request): if request.method == 'POST': if request.POST.get("tipo")=="2": proveedores=serviceProvider.objects.filter(user=request.POST.get("user")) if not proveedores: return HttpResponse("Bad") else: rubros=item.objects.filter(provider=proveedores.first()) if len(rubros)<2: new = item() new.provider=proveedores.first() new.radius=request.POST.get("radius") new.description=request.POST.get("description") new.hour_init=request.POST.get("hour_init") new.hour_end=request.POST.get("hour_end") new.certificate=request.FILES.get("certificate") new.picture1=request.FILES.get("picture1") new.picture2=request.FILES.get("picture2") new.picture3=request.FILES.get("picture3") new.save() return HttpResponse("Item loaded") You can see that many times, a single image is sent, so the picture2 and picutre3 will be None. Then when I try to send model information back to the client, I do it using this function def requestRubros(request, tipo,user,rubro): if tipo=="2": proveedores=serviceProvider.objects.filter(user=user) if proveedores: rubro=item.objects.filter(provider=proveedores.first()).filter(items=rubro) if rubro: data = [{"radius": str(rubro.first().radius), "description": rubro.first().description,}, { "hour_init": str(rubro.first().hour_init), "hour_end": str(rubro.first().hour_end)}, {"certificate": "data:image/png;base64,"+base64.b64encode(rubro.first().certificate.read()).decode('ascii'), "picture1": "data:image/png;base64,"+(base64.b64encode(rubro.first().picture1.read())).decode('ascii'), "picture2": "data:image/png;base64,"+base64.b64encode(rubro.first().picture2.read()).decode('ascii'), "picture3": "data:image/png;base64,"+base64.b64encode(rubro.first().picture3.read()).decode('ascii')}] return JsonResponse(data, safe=False) else: return HttpResponse ("Bad data") else: return … -
How to test mp3 modification by upload in Django DRF, via PUT?
I have the following so far: client = Client() with open('my_modified_audio.mp3', 'rb') as fp: response = client.put( f"/path/{resource_id}/", data={'audio': fp}) However, I get response.status_code == 415 because the serializer in DRF's. serializer = self.get_serializer(instance, data=request.data, partial=partial). fails with rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request. I have tried format="multipart", setting the content type to json or form-encoded, nothing helped so far. The audio is models.FileField. How can I make this put request work? -
list_filter in Django admin
I have a category model: class Category(models.Model): name = models.CharField(max_length=300) slug = models.SlugField(max_length=300, unique=True) sub_category = models.ForeignKey('Category',null=True, blank=True, on_delete=models.CASCADE) in the admin.py I want to use list_filter. I want to filter by a category is a sub category or no. my field is not boolean. how do I can do this??? -
Python dictionary taking only one object
I am going to take two field as key pair in dictionary but it writes only one object for example, I have CarType model and two objects in this model. I need to write these objects to dict it works but not as expected. Here what I have done so far class CarType(models.Model): ... types = models.ManyToManyField("Type") d = {} for type in self.types.all(): for t in Type.objects.filter(id=type): d.update({t.name: t.model}) and it outputs {'key_1': 'value_2'} but actually it should be like {'key_1': 'value_1', 'key_2': 'value_2'} I mean if how many items are in Type model they should be in dictionary. Unfortunately, it is taking only one object. can anybody help with this please? any help would be useful ) -
form initials do not show
i am trying to set the form initials for the sender field as the logged in user, and it does not show. i removed the if request method statement and adjusted the indentaion and the initials showed. I am stuck, i believe the form is supposed to have that request method statement. i've gone through the documentation and it says the post method binds the data and submits, but there isn't any data when the page is refreshed or newly loaded. what could be wrong? views.py def transfer(request): profile = Profile.objects.get(user=request.user) if request.method == "POST": form = TransferForm(request.POST,initial={"sender": profile}) if form.is_valid(): print(form) form.save() sender = models.sendcoins.objects.get(sender=request.user.profile) profile2 = Profile.objects.get(username=receiver) user_wallet = wallet.objects.get(owner=profile) print(receiver) temp = sender # NOTE: Delete this instance once money transfer is done receiver = models.wallet.objects.get(owner=profile2) # FIELD 1 transfer_amount = sender.amount # FIELD 2 sender = models.wallet.objects.get(owner=profile) # FIELD 3 # Now transfer the money! sender.balance = sender.balance - transfer_amount receiver.balance = receiver.balance + transfer_amount # Save the changes before redirecting sender.save() receiver.save() temp.delete() # NOTE: Now deleting the instance for future money transactions else: return(HttpResponse("form is not valid")) else: form = TransferForm() return render(request, "sendcoins.html", {"form": form}) -
Generating username from Fullname field and adding 8 char string with it
I want to generate unique username for every user during registration based on his/her name, user can change it later. my models.py : full_name = models.CharField("Full Name", max_length=100, null=True,blank=True) username = models.CharField("Username", max_length=100, null=True, blank=True) //I want this to be auto generated Example : full_name: abc.mc username: abc.mc #fdg415 I am using drf to get these data and while doing so I want to fill the username field class RegisterSerializer(serializers.HyperlinkedModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=HNUsers.objects.all())] ) mobile_number = serializers.CharField( required=True, validators=[UniqueValidator(queryset=HNUsers.objects.all())] ) required_formats = ['%d-%m-%Y', '%Y-%m-%d'] date_of_birth = serializers.DateField(format="%d-%m-%Y", input_formats=['%d-%m-%Y', 'iso-8601']) class Meta: model = HNUsers fields = [ 'full_name', ] def create(self, validated_data): return HNUsers.objects.create(full_name=validated_data['full_name']) any help will be much appreciated -
Integrating multiple bokeh charts into Django
Essentially I would like to publish multiple charts stacked on top of each other inside a Django project file architecture. I will generate multiple charts that need to be published in the same page under each other. I'm hoping to also include a select bar that still interacts with the other charts. I have the following first_dashboard.py: import numpy as np from bokeh.io import show from bokeh.layouts import column, gridplot from bokeh.models import ColumnDataSource, RangeTool from bokeh.plotting import figure from bokeh.sampledata.stocks import AAPL class RandomCharts(): def __init__(self): pass def make_plots(self): dates = np.array(AAPL['date'], dtype=np.datetime64) source = ColumnDataSource(data=dict(date=dates, close=AAPL['adj_close'])) p = figure(plot_height=300, plot_width=800, tools="xpan", toolbar_location=None, x_axis_type="datetime", x_axis_location="above", background_fill_color="#efefef", x_range=(dates[1500], dates[2500])) p.line('date', 'close', source=source) p.yaxis.axis_label = 'Price' select = figure(title="Drag the middle and edges of the selection box to change the range above", plot_height=130, plot_width=800, y_range=p.y_range, x_axis_type="datetime", y_axis_type=None, tools="", toolbar_location=None, background_fill_color="#efefef") range_tool = RangeTool(x_range=p.x_range) range_tool.overlay.fill_color = "navy" range_tool.overlay.fill_alpha = 0.2 select.line('date', 'close', source=source) select.ygrid.grid_line_color = None select.add_tools(range_tool) select.toolbar.active_multi = range_tool plots = {'Plot1':p, 'Plot2':p, 'Select1':select} return plots And the following view: from django.shortcuts import render from bokeh.plotting import figure, output_file, show from bokeh.embed import components from bokeh.sampledata.iris import flowers from bokeh_example.first_dashboard import RandomCharts # Create your views here. def homepage(request): dashboard = … -
How to make reverse relationship query with count in Django
I have related models as defined below. I want to write a query to get all product that have product_options. I there a way I can achieve this or how to my attempted solution. I have pasted my solution below. # Attempted Solution Product.objects.filter(product_options__count__gt=0) # Defined models class Product(models.Model): name = models.CharField(max_length=200) class ProductOption(models.Model): name = models.CharField(max_length=200) product = models.ForeignKey( Product, on_delete=models.PROTECT, related_name='product_options' ) -
How i can running django project?
I can run django only on my own computer. If I copy it to another one and run I get error. Virtualenv is running successfully, but then i get this message "Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" I tried to install django on other computers too, but it isnt helps. What is wrong? Project .idea __pycatch__ main Project templates venv db.sqlite3 manage start start.bat @echo off cmd /k "cd /d C:\Users\[user]\PycharmProjects\Project\venv\Scripts & activate.bat & cd /d C:\Users\[user]\PycharmProject\Project & python manage.py runserver" manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
HttpResponse with text and xlsx file
This is the first question I've asked so I apologize if things are unclear. I tried to find existing information for this on the internet but was unsuccessful. context: I'm working on a Django app right now. Currently my main view allows you to type in search terms, and will perform a search, write the information to a xlsx file, and return that file, which automatically downloads to your computer. My response format looks like this: filename = 'query_results.xlsx' response = HttpResponse( xlsx, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response based off this link: https://xlsxwriter.readthedocs.io/example_django_simple.html my question: I have some additional information about the query that isn't fully essential but I think would be helpful to return along with this xlsx file. I'm wondering if it is possible to return some text to the webpage along with the xlsx file? -
How to use OneToOneField in the Model and save both table with class-based-views
I need to register a modelform in the database, but as I have a OneToOneFiel in the model, I don't know what is the best way to register the information in the two tables in the database with a class-based-views. The following code worked for me, but it doesn't seem like the right solution, or pythonic solution. models.py class Pessoa(models.Model): nome = models.CharField('Nome', max_length=100) email = models.EmailField('E-mail', max_length=30, unique=True) logradouro = models.CharField('Logradouro', max_length=50) def __str__(self): return self.nome class Assinante(models.Model): pessoa = models.OneToOneField(Pessoa, models.DO_NOTHING) qualquer = models.CharField('Qualquer', max_length=20) aceito = models.BooleanField('Aceito', default=False, null=False) def __str__(self): return self.pago forms.py class AssinanteModelForm(forms.ModelForm): nome = forms.CharField(label='Nome', min_length=8, max_length=100) email = forms.CharField(label='E-mail', max_length=30) logradouro = forms.CharField(label='Logradouro', max_length=50) qualquer = forms.CharField(label='Qualquer', max_length=20) aceito = forms.CheckboxInput() def send_mail(self): # Anything class Meta: model = Assinante fields = ['nome', 'email', 'logradouro', 'aceito'] views.py (not pythonic, I believe) class AssinanteView(FormView): template_name = 'club.html' form_class = AssinanteModelForm success_url = reverse_lazy('success') def form_valid(self, form, *args, **kwargs): pessoa = Pessoa( nome=form.cleaned_data['nome'], email=form.cleaned_data['email'], logradouro=form.cleaned_data['logradouro'], ) assinante = Assinante( qualquer=form.cleaned_data['qualquer'], aceito=form.cleaned_data['aceito'], ) pessoa.save() assinante.pessoa = pessoa assinante.save() # form.send_mail() messages.success(self.request, "Cadastro realizado com sucesso.") return super(AssinanteView, self).form_valid(form, *args, **kwargs) urls.py urlpatterns = [ ... path('club', AssinanteView.as_view(), name='club'), ] template html (cleaned) <form action="{% url … -
I get the error Could not find a version that satisfies the requirement djangorestframework-simplejwt == 4.6.0 in Django
When I install djangorestframework-simplejwt4.6.0 in Django and try to deploy it to Heroku remote: ERROR: Could not find a version that satisfies the requirement djangorestframework-simplejwt==4.6.0 (from -r /tmp/xxxxx/requirements.txt (line 19)) (from versions: 1.0, 1.1, 1.2, 1.2.1, 1.3, 1.4, 1.5.1, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.1, 3.0, 3.1, 3.2, 3.2.1, 3.2.2, 3.2.3, 3.3, 4 .0.0, 4.1.0, 4.1.1, 4.1.2, 4.1.3, 4.1.4, 4.1.5, 4.2.0, 4.3.0, 4.4.0) remote: ERROR: No matching distribution found for djangorestframework-simplejwt==4.6.0 (from -r /tmp/xxxxx/requirements.txt (line 19)) I get the error. I was able to deploy it by lowering the version to 4.4.0 and deploying it to Heroku, but when I run it with python manage.py runserver and access it, I get AttributeError: 'str' object has no attribute 'decode'``` I get the error AttributeError: 'str' object has no attribute. How can I deal with this situation? I would appreciate it if you could help me. Translated with www.DeepL.com/Translator (free version) -
Django: Create tree view with categories that include files and category children
From this answer I was able to create a tree view of category items. But I need to make an api call to get files in the same way. How can I achieve that? models.py class Category(MPTTModel): name = models.CharField(max_length = 50, blank = True) parent = TreeForeignKey('self', null = True, blank = True, on_delete = models.CASCADE, related_name='children') class MPTTMeta: order_insertion_by = ['name'] class Document(models.Model): name = models.CharField(max_length = 128, blank = True) description = models.TextField(blank = True, null = True) file = models.FileField(null = True, blank = True, upload_to='documents/', validators=[FileExtensionValidator(allowed_extensions=['pdf'])]) category = models.ForeignKey(Category, null = True, blank = True, on_delete = models.SET_NULL) class Meta: verbose_name = 'Document' verbose_name_plural = 'Documents' -
How to send SMS using Django for free?
I tried Twilio but it only gives one phone number to send which is registered ones. So, can anyone have used Django messaging sending packages that can send free SMS in bulk. -
Django + React I need advice for Form Rendering and Auth User
I'm using django-rest-framework-simplejwt for authentication. How can I retrieve the logged in user's information when the user is logged in via reactjs For example, if I wanted to show it as Welcome request.user.username #wrong i know. I did some research on both "stackoverflow" and "github", but I could not find anything that meets my request, or I may be thinking wrong with retrieving user information. Do you have any examples that you can recommend? Backend; View.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer Serializer.py class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['is_superuser'] = user.is_superuser return token urls.py urlpatterns = [ #... path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] Fronted Axios.js const baseURL = 'http://127.0.0.1:8000/api'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem('access_token') ? 'JWT ' + localStorage.getItem('access_token') : null, 'Content-Type': 'application/json', accept: 'application/json', }, });... Login.js const handleSubmit = (e) => { e.preventDefault(); console.log(formData); axiosInstance .post(`token/`, { email: formData.email, password: formData.password, }) .then((res) => { localStorage.setItem('access_token', res.data.access); localStorage.setItem('refresh_token', res.data.refresh); axiosInstance.defaults.headers['Authorization'] = 'JWT ' + localStorage.getItem('access_token');});... My last question is how can I populate the cateogry dropdown menu with recorded categories so that I can select the category when creating a post? (i just need advice with some example links) …