Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 4 template check if user is authenticated using async view
Is there any way to check if a user is authenticated in the Django template using async view? I am having the errors SynchronousOnlyOperation when I do {% if user.is_authenticated %} in my template. I know there is the option DJANGO_ALLOW_ASYNC_UNSAFE but the doc says it's not safe. So I am wondering if there is a safer method. -
How do i do a temperature conversion in Django with radio buttons?
I'm working with API using python(Django) but I need help with converting the temperatures from Celsius to Fahrenheit and vice versa with a radio button. -
Django DeleteView Redirect to Second Previous Page
I have my generic deleteview. The user can visit here from the generic updateview, because only button is there. I like to redirect the user to previous page after deletion but the previous page is the updateview and it'll be gone with the deletion. Is there any way to send the user to second previous page after deletion ? class ActionDeleteView(generic.DeleteView): # action-deleteview model = models.Action template_name = 'crm/action_delete.html' def get_success_url(self): # for the message message = f'{self.get_object()} is deleted successfully!' messages.success(self.request, message) previous = self.request.META.get('HTTP_REFERER') print('***************** previous: ', previous) return reverse_lazy('action-listview') NOTE: The print(previous) in the code returns the updateview -
Reset Heroku DB now some of my schemas aren't migrating
New to heroku - I had some major problems with a migration from my local django app to Heroku prod so decided to destroy my heroku db with heroku pg:reset - this all seemed to go to plan, I then ran heroku run python manage.py migrate to attempt to recreate my schemas. The following were migrated: Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount But none of my models.py tables went up - eg the following crucial schema was not migrated: class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) cafe_image_url = models.CharField(max_length=200, null=False) # class Meta: # # managed = False def __str__(self): return self.cafe_name Installed Apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'testingland', 'rest_framework', 'bootstrap_modal_forms', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'widget_tweaks', ] Any advice? -
what is initial steps to run project which was already developed code. how to do for first time
i have old code which is on live , my manager gave code in zip file. which is developed python 2.7 and Django 1.11 i downloaded and created environment. when i started install requirement.txt file errors were come. ERROR: No matching distribution found for alabaster==0.7.10 (from -r fedDjango/SAML_val/Samlvalidate/requeriments.txt (line 1)) d:\pro - portal\portal\venv\lib\site-packages\pip_vendor\urllib3\util\ssl_.py:139: InsecurePlatformWarning: A true SSLContext object is not available. Thi s prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecurePlatformWarning, -
Python getting blanck files from django server using docker
The problem I have is difficult to explain, so I am sorry if my question is too big. I am creating an API with python and django REST Framework, and one of the functionalities we need is to upload a file so another client can download it. The way I do this, I get it from the request with file_details = request.FILES.get('file'). Then I upload the file with the request python library like this. import requests url = "server_url" payload = {'memberId': '7d2d92fb-a21c-40a5-9e0d-f4f299edb468', 'memberType': 'professional'} file = [ ('file',(file_details.name, file_details.read(), file_details.content_type)) ] headers = {} response = requests.request("POST", url, headers=headers, data=payload, files=file) When I try this in local (on my machine), it works fine. I run our docker container and make the request with the file, and everything works perfectly. Then I download the file from the server and the file is also ok. The problem is that when I upload the code to the server and I make the postman request directly to it, it seems that is correctly uploaded, but when I try to download it I get a blank pdf file. Do you know how to solve this problem? Thanks in advance for your help. -
How to filter from auth_group_permissions table Django
How to filter from auth_group_permissions table Django. actually, I don't know by which model I can filter from auth_group_permissions. from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType I only get this model from Django documentation but I don't get any from for auth_group_permissions table. please anyone helps me. -
how to create range slider in django and javascript
how to create a range slider in Django and javascript? also for data stuff I'm using an API instead of a database I want to create a range slider like that (video demo): https://itslachiteaching.wistia.com/medias/v4cx2mncw8 #views.py def slider(request): form = SliderForm() context = { "slider": form, } return render(request, 'slider.html', context) #forms.py from django_range_slider.fields import RangeSliderField class SliderForm(forms.Form): range_field = RangeSliderField(minimum=10,maximum=102) #slider.html <div>form {{ slider.as_p }}</div> -
django: JOIN two SELECT statement results
MYSQL - working fine SELECT * FROM (SELECT ...) u LEFT JOIN (SELECT ...) e ON (u.id = e.employee_id) DJANGO u = user_with_full_info.objects.values( 'id' ).filter( branch = team['branch__id'], team = team['team__id'], position__lt = team['position__id'], valid = 1 ) d = staff_review.objects.values( 'employee' ).annotate( last_date=Max('date'), dcount=Count('employee') ).filter( month = month() ) e = staff_review.objects.values( 'performance__name', 'performance__style', 'employee__user__id', 'employee__user__salary_number', 'employee__user__last_name', 'employee__user__mid_name', 'employee__user__first_name', 'date' ).filter( month = month(), employee__id__in = Subquery(u.values('id')), date__in = Subquery(d.values('last_date')), ).order_by( 'employee__id' ) With MYSQL I got: | employee_id | performance_id | | -------- | -------------- | | 3 | 2 | | 1 | 3 | | 4 | NULL | With Django I got: | employee_id | performance_id | | -------- | -------------- | | 3 | 2 | | 1 | 3 | How can I fix that? -
Getting ProgrammingError at ... using Heroku
I made some changes to my models.py file and now I return this error when I try to access my heroku app's admin page: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) The above exception (column testingland_mapcafes.cafe_image_url does not exist LINE 1: ...s"."venue_type", "testingland_mapcafes"."source", "testingla... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1828, in changelist_view 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}, File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1202, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File … -
How do i make my categories function correctly?
so im trying to seperate my blog posts into different categories but right now it all just appears as my username blogcategory.html {% extends "base.html" %} {% block page_content %} <div class="col-md-8 offset-md-2"> <h1>{{ category | title }}</h1> <hr> {% for post in posts %} <h2><a href="{% url 'blogdetail' post.pk%}">{{ post.title }}</a></h2> <small> {{ post.created_on.date }} | Categories: {% for category in post.categories.all %} <a href="{% url 'blogcategory' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> <p>{{ post.body | slice:":400" }}...</p> {% endfor %} </div> {% endblock %} blogdetail.html {% extends "base.html" %} {% block page_content %} <div class="col-md-8 offset-md-2"> <h1>{{ post.title }}</h1> <small> {{ post.created_on.date }} |&nbsp; Categories:&nbsp; {% for category in post.categories.all %} <a href="{% url 'blogcategory' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> <p>{{ post.body | linebreaks }}</p> <h3>Leave a comment:</h3> <form action="/blog/{{ post.pk }}/" method="post"> {% csrf_token %} <div class="form-group"> {{ user.username|default:'Guest' }} </div> <div class="form-group"> {{ form.body }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <h3>Comments:</h3> {% for comment in comments %} <p> On {{comment.created_on.date }}&nbsp; <b>{{ user.username|default:'Guest'}}</b> wrote: </p> <p>{{ comment.body }}</p> <hr> {% endfor %} </div> {% endblock %} blogindex {% extends "base.html" %} {% block page_content %} <div … -
No module named 'corsheaders' docker-compose up
Hy everyone! I'm new in the Django world. I develop a Django website and I want to make a Docker container with the appliation and run it on my localhost. I created my Dockerfile and my docker-compose.yaml but when I run docker-compose up it gives the following error. Attaching to mysite-web-1 mysite-web-1 | Watching for file changes with StatReloader mysite-web-1 | Exception in thread django-main-thread: mysite-web-1 | Traceback (most recent call last): mysite-web-1 | File "/usr/local/lib/python3.10/threading.py", line 1009, in _bootstrap_inner mysite-web-1 | self.run() mysite-web-1 | File "/usr/local/lib/python3.10/threading.py", line 946, in run mysite-web-1 | self._target(*self._args, **self._kwargs) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper mysite-web-1 | fn(*args, **kwargs) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run mysite-web-1 | autoreload.raise_last_exception() mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception mysite-web-1 | raise _exception[1] mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/init.py", line 381, in execute mysite-web-1 | autoreload.check_errors(django.setup)() mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper mysite-web-1 | fn(*args, **kwargs) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/init.py", line 24, in setup mysite-web-1 | apps.populate(settings.INSTALLED_APPS) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate mysite-web-1 | app_config = AppConfig.create(entry) mysite-web-1 | File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 223, in create mysite-web-1 | import_module(entry) mysite-web-1 | File "/usr/local/lib/python3.10/importlib/init.py", line 126, in import_module mysite-web-1 | return _bootstrap._gcd_import(name[level:], … -
Unable to run django test in CircleCI
I am implementing CircleCI for one of the projects. The project is built on Django 3.2. My test cases run properly when I run using python manage.py test blog, when I run the same in CircleCI it returns , ====================================================================== ERROR: project.blog (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: project.blog Traceback (most recent call last): File "/usr/local/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'project.blog' Here is my CircleCI config version: 2 jobs: build: docker: - image: circleci/python:3.8 steps: - checkout - run: name: Installing dependencies command: | python3 -m venv venv . venv/bin/activate pip3 install -r requirements.txt - run: name: Running migrations command: | . venv/bin/activate python manage.py migrate --skip-checks - run: name: Running tests command: | . venv/bin/activate python manage.py test blog I understand that CircelCI clones the project in project folder. Is that something that I am missing in config? -
defaultdict new structure in django
i have this defaultdict(list) in my outout defaultdict(<class 'list'>, {'List of tubes': ['2324', '98', '7654', 'List of auto:': [147, 10048, 1009, 10050, 10, 1647, 10648, 649, 1005]}) How i can add a space inside AND WITOUT {(, ? to obtain 'List of tubes': '2324', '98', '7654' 'List of auto:': 147, 10048, 1009, 10050, 10, 1647, 10648, 649, 1005 -
Django display date with user current timezone
I have such model class SomeModel(models.Model): some_field = models.CharField(max_length-100) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('Created at')) settings.py TIME_ZONE = "UTC" USE_TZ = True The problem: in postgres created_at value is 2022-01-19 01:18:29.096177+03 now I want to show the user, that object was created on 2022-01-19. But when I call created_at.date() it shows 2022-01-18 How to fix that? -
Django formset labels
I am creating a hosptial management system.For this query on stackoverflow there are four models in play. Order, Pharmacyitem, PharmacySalesBills and Inventory, with formsets set up for PharmacyItem and Order. The natural flow of the creating a pharmacy item, populating a sales bill and inventory work as they should. I.e date, new sales item record created and adjustment to inventory stock and sales bill generated using sales item. My idea is for a doctor to create a order, the pharmacist, does a search at any given time on the order model, and uses the model as a bridge to the pharmacy sales item model, to get quantity and name of product and patient from order object. and then using a booleanfield on the order model, which changes to true once the pharmacy item / sales bill has been created. Question: If a doctor prescribes 3 items, via template using formset, and each form in formset, will have its own id. Do i create an additional field in the order model, that acts as an identifier for the current order [so using the above example all 3 items]. Or is there a way formset can take a label, that shows the … -
How to work with foreign key with mutiple selection
Hi Everyone i am trying to achieve select multiple car with foreign key relation because we need to store data with mutiple row, i am tried with manytomany fied but this is not effective as per our requirement, thats way i am trying solve this with foreign key, pls help me out. models.py class Car_team(BaseModel): team = models.ForeignKey( Team, models.CASCADE, verbose_name='Team', null=True, ) car=models.ForeignKey( Car, models.CASCADE, verbose_name='Car', null=True) city =models.ForeignKey( City, models.CASCADE, verbose_name='City', ) start_date=models.DateField(null=True, blank=True) end_date=models.DateField(null=True, blank=True) forms.py class CarTeamForm(forms.ModelForm): start_date=forms.DateField(initial=datetime.date.today, label='Start Date') car = forms.ModelMultipleChoiceField(queryset=Car.objects.all(), required=True, widget=forms.CheckboxSelectMultiple) class Meta: model = Car_team fields = ['car','team','city','start_date'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(CarTeamForm, self).__init__(*args, **kwargs) self.fields['start_date'].widget.attrs['readonly'] = True widgets = { 'car': forms.CheckboxSelectMultiple(attrs={'class': 'form-control select2'}), } views.py def add_carteam(request, city_id=None, id=None): if id is not None: carteam = get_object_or_404(Car_team, city_id=city_id, pk=id) else: carteam = None if request.method == 'POST': form = CarTeamForm(request.POST, request.FILES,instance=carteam) if form.is_valid(): car = form.cleaned_data['car'] team = form.cleaned_data['team'] start_date = Car_team.objects.filter(car__in=car).values_list('start_date', flat=True).filter(end_date__isnull=True) # if start_date: # messages.error(request,'Car already assigned to another team!') query = Car_team.objects.filter(car__in=car).exists() query_set = Car_team.objects.filter(car__in=car).values_list('team', flat=True) team_name = Team.objects.filter(pk__in=query_set).values_list('name', flat=True) car_id = Car_team.objects.filter(car__in=car).values_list('car', flat=True) car_number=Car.objects.filter(pk__in=car_id).values_list('car_number', flat=True) if query_set and start_date: messages.error(request,'Car already assigned to team {} {}!'.format(team_name,car_number)) # if query: # … -
Attach additional data to Django Rest (DRF) request object only when user logs in
I have a Branch model that contains all the branches a user could be a part of. Another model UserBranchRelation that contains the relation of a user with a particular branch. Each user has a particular role inside a particular branch. Admin users have more permissions as compared to a simple member. Moreover, a user could be an admin inside one branch and a member in another. I am trying to come up with a neat solution that would let me attach the user's branch and role to the request object on login. Now whenever an authenticated request is received, I should not need to fetch the branch repeatedly as it would already have been attached to the request object on successful login. Inside my views, I would then use permissions to return data based on user's branch and limit access based on role. Here are my models. # Branch Model class Branch(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) # User and Branch relationship class UserBranchRelation(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) branch = models.ForeignKey(Branch, on_delete=models.CASCADE) role = models.CharField( max_length=20, choices=RoleChoices.choices, default=RoleChoices.MEMBER ) -
App not compatible with buildpack - django project with java script
When I try to deploy my app to Heroku then I received: -----> Building on the Heroku-20 stack -----> Using buildpacks: 1. heroku/python 2. https://github.com/heroku/heroku-buildpack-static.git -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I've been trying to spend a lot of time. Most of the solution is not working. Is it a buildpack issue or something else? Additionally, I connected my GitHub account to Heroku and tried deploying from the GitHub main branch. However, I still receive the error. Here is my GitHub address: https://github.com/Whitemoon2000/Final-year-project -
can't use setUpTestData variable in setUp
i define this line of code in but i got self.user not define user class TestSample(TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() business = BusinessFactory() cls.user = business.main_owner def setUp(self): self.api_client = APIClient() self.client, self.token, self.user = self.client_login( self.api_client, phone=self.user ) -
Django - django.db.utils.IntegrityError: duplicate key value violates unique constraint
I'm trying to build a server at django that will hold my mobile device update files: class updates(models.Model): namedev = models.CharField(max_length=200) devip = models.CharField(max_length=200) nameupdate = models.CharField(max_length=200) datesend = models.DateTimeField(max_length=200) status = models.CharField(max_length=100) And every time I use the "create ()" function it fails to create a column in the database, def create(nameDev,ipDev,nameUpdate,dataSend,status): updates.objects.create(namedev=nameDev,devip=ipDev, nameupdate=nameUpdate,datesend=dataSend,status=status) print("------------------------------test1-------------------------") and I get it: [enter image description here][1] [enter image description here][1] -
Button behavior in django template (href + function)
I have a next problem: <div class="col-4"> <a class="btn btn-warning" href="{% url 'home' %}" role="button">Save and Back</a> {{ request | mail}} </div> The logic is next: I want to click on button and send an email with redirecting to home page. My mail is a filter tag. Unfortunately I can't add my filter to the view, because I am using this view in another place, where I don't want to send an email. My current solution send an email before click on button. Do you have any idea? -
Django custom template tags to remove specific URL query strings
I'm trying to create a simple tag for a django template which removes a specified URL query string. It's purpose is to remove some applied filtering, ie remove saved=1 from http://localhost/?saved=1&source=news&week=5 I have created a custom tag: @register.simple_tag(takes_context=True) def defilter(context, *args): query = context['request'].GET.copy() for key in args: if key in query.keys(): query.pop(key) return query.urlencode() I have then created a link in a django template which recontructs the url get paramters but removes the specified key: <a href="{% url 'articles' %}?{% defilter saved %}">Remove Saved</a> Any ideas why this isn't working the way I expect? I get no errors, it just doesn't remove the specified key. Many thanks -
Django: Is it possible to select unique combinations of two foreign keys without the use of distinct?
I have the following models: class Exercise(models.Model): name = models.CharField(max_length=300) # ... class UserWorkout(models.Model): user = models.ForeignKey(User) # ... class WorkoutSet(models.Model): exercise = models.ForeignKey(Exercise) user_workout = models.ForeignKey(UserWorkout, related_name="sets") date_time = models.DateTimeField(default=timezone.now) weight = models.DecimalField(max_digits=10, decimal_places=6) # ... This is example data for the WorkoutSet model to get a better picture: ID weight DateTime Exercise UserWorkout - 10.0 22/02/2022 3 UUID('755925da-9a43-490c-9ffa-3222acd1dcfa') - 15.0 22/02/2022 3 UUID('755925da-9a43-490c-9ffa-3222acd1dcfa') - 15.0 22/02/2022 3 UUID('755925da-9a43-490c-9ffa-3222acd1dcfa') - 55.0 24/02/2022 5 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') - 57.5 24/02/2022 5 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') - 15.0 24/02/2022 3 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') - 20.0 24/02/2022 3 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') I'm trying to filter this data so it shows how many times each exercise has been performed (i.e. how many workouts it's associated with). So the above data would look like: Exercise UserWorkout 3 UUID('755925da-9a43-490c-9ffa-3222acd1dcfa') 5 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') 3 UUID('bc59c55b-9adc-47c7-9790-2e5d8b21f956') Ultimately I'm going to count how many times each Exercise has been done like this: qs = # some filter statement qs = qs.values('exercise').annotate(frequency=Count('exercise')) I can't use distinct because it doesn't work with annotate: NotImplementedError: annotate() + distinct(fields) is not implemented. Is what I'm trying to achieve possible? Perhaps through a subquery? My SQL is rusty so not sure if that's possible at all. -
Django API return user's data after login
i am using KnoxLogin and when i login , it's return only token and expire date , i want to return more information for example which group contain and etc... models.py class Organization(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(default='0000000',max_length=100) type = models.CharField(default='0000000',max_length=20) owner_id = models.CharField(default='0',max_length=100) def __str__(self): return str(self.name) class User_org(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User,related_name='UserInfo', on_delete=models.CASCADE) organization = models.ForeignKey(Organization,related_name='UserInformation',on_delete=models.CASCADE) def __str__(self): return str(self.user) views.py # Login API class LoginAPI(KnoxLoginView): permission_classes = [permissions.IsAuthenticated,] def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer2 = OrganizationSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return Response(serializer2) and this is my organization serializer and want to show this fileds after login , how do this ? class OrganizationSerializer(serializers.ModelSerializer): UserInformation = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = Organization fields = '__all__'