Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to integrate django backend with react frontend?
I am working on a website which has its back-end developed in django and front-end developed in React.I have got the build folder from the react app. How should I proceed to integrate my back-end with react? -
Celery is not executing tasks concurrently
I'm new to celery, please let me know in comments if more information is required. I have around 3000 tasks queued in redis and i want to execute these tasks concurrently over multiple threads, after a bit of research i ended up using eventlet for thread pooling and set concurrency to 500, like so celery worker -A <app_name> -P eventlet -c 500 but when i checked celery flower many free threads are available which the celery is not using Any idea on how to make use of those free threads and make tasks faster? also if possible please suggest a good read for working with celery -
Django: Names are not showing in drop-down list
I need to show a list of countries for users to select from the ship's country field. But it's showing Country object(1), Country object(2)... instead of showing names of countries I've created classes for Ship and Country with the Ship class having a foreignkey of country. class Ship(models.Model): # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) callsign = models.CharField(max_length=50) last_updated = models.DateTimeField(auto_now=True, editable=False) weight = models.DecimalField(max_digits=20, decimal_places=4) # RelationShip Fields shipflag = models.ForeignKey( 'manifest.Country', on_delete=models.SET_NULL, related_name="Ships", null=True ) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('manifest_Ship_detail', args=(self.slug,)) def get_update_url(self): return reverse('manifest_Ship_update', args=(self.slug,)) class Country(models.Model): # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) code = models.CharField(max_length=5) # RelationShip Fields continent = models.ForeignKey( 'manifest.Continent', on_delete=models.CASCADE, related_name="Countrys", ) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('manifest_Country_detail', args=(self.slug,)) def get_update_url(self): return reverse('manifest_Country_update', args=(self.slug,)) In the 'create new ship' form at the country dropdown combo I expect to see a list of countries like United States, Mexico, Canada... but instead am seing countries as objects like this object(1), Country object(2)... -
Build dict through for loop without repetition
My code is currently very repetitive with grouped_events.setdefault('VAR', []).append(event) and event_data_by_organizer[organizer.pk]['events_draft'] = grouped_events.get('VAR'). Do you see any better way in writing this? Currently, my best idea would be to write a function above where I insert the strings such as 'archived' etc. # Events by status grouped_events = {} for event in events: if event.status == EventStatus.ARCHIVED: grouped_events.setdefault('archived', []).append(event) elif event.status == EventStatus.DRAFT: grouped_events.setdefault('draft', []).append(event) elif event.is_over: grouped_events.setdefault('past', []).append(event) else: grouped_events.setdefault('live', []).append(event) event_data_by_organizer[organizer.pk][ 'events_archived' ] = grouped_events.get('archived') event_data_by_organizer[organizer.pk]['events_draft'] = grouped_events.get( 'draft' ) event_data_by_organizer[organizer.pk]['events_past'] = grouped_events.get( 'past' ) event_data_by_organizer[organizer.pk]['events_live'] = grouped_events.get( 'live' ) -
Is there a way to add ManyToMany filed inside current form (not in popup page) in django admin?
I have 2 models in django. the first one is Tag and second one is Article that is related to Tag models via ManyToMany fields. class Tag(models.Model): title = models.CharField(max_length=60, blank=False) class Article(models.Model): title = models.CharField(max_length=160) content = models.TextField() tags = models.ManyToManyField(Tag) When I want to and one or more tag(s) for article, a popup appears to add tag. I want to add this inside the current form. Is it possible? -
Add Extra fields in serializer from one to one relation models
In this project, I have two models Student and Parent related to each other through one to one field. In Parent serializer, I want to add Students attributes like age. I am thinking of using SerializerMethodField for both cases is their any better way to do it? I am not getting the queries on how to get the object attributes and little explanation would be great. Here what I have done till now. Models.py class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, default=None) batch = models.ForeignKey(Batch, on_delete=models.CASCADE, null=True, related_name='students') email = models.EmailField(null=True) phone_number = models.CharField(max_length=10, null=True) dob = models.DateField(blank=True, null=True, help_text="Enter in the following format : YYYY-MM-DD") address = models.TextField(max_length=150, null=True) age = models.IntegerField(blank=True) image = models.ImageField(upload_to='profile_pictures', default='student_image.png', blank=True) @property def remarks(self): return self.remark_set.all() @property def marks(self): return self.marks_set.all() def __str__(self): return self.user.firstName + ' ' + self.user.lastName class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, default=None) child = models.ForeignKey(Student, on_delete=models.CASCADE) email = models.EmailField(null=True) phone_number = models.CharField(max_length=10, null=True) address = models.TextField(max_length=150, null=True) image = models.ImageField(upload_to='profile_pictures', default='student_image.png', blank=True) def __str__(self): return self.user.firstName + ' ' + self.user.lastName Serilaizer.py class ParentSerializer(serializers.HyperlinkedModelSerializer): student_age = serializers.SerializerMethodField() student_batch = serializers.SerializerMethodField() parent_name = serializers.SerializerMethodField() class Meta: model = Parent fields = "__all__" def get_student_age(self, obj): return Parent.objects.get(child__age = … -
Django annotate group by date return object
I'm using Django's annotate from the aggregate doc. My goal is to group a model by date and return all objects associated with each date in this form: [{ 'date': 'datetime.datetime(2019, 6, 22, 11, 35)' 'instances': [<Model: (1)>, <Model: (2)> ] }, { 'date': 'datetime.datetime(2019, 6, 21, 11, 35)' 'instances': [<Model: (3)>, <Model: (6)> ] },] I tried this query: Flight.objects.values('origin_scheduled_dep').annotate(Count('origin_scheduled_dep')).order_by('origin_scheduled_dep') But that's returning the values I specified: <QuerySet [{'origin_scheduled_dep': datetime.datetime(2019, 6, 22, 11, 35), 'origin_scheduled_dep__count': 1}, {'origin_scheduled_dep': datetime.datetime(2019, 6, 22, 15, 40), 'origin_scheduled_dep__count': 1}, {'origin_scheduled_dep': datetime.datetime(2019, 6, 22, 22, 0), 'origin_scheduled_dep__count': 2}]> Thanks for any help, always :) -
How can i send matplot graph as a graph to django template but not as a image
I wanted to send matplot graph as a graph to my django template not as a image to template. How can i achieve this? This is my sample code which is successfully generate graph and send as a image but i want to send as a graph only so that if in my template someone hover at the data point, it should display annotation but saving as a image will not work so sending as a graph to template. def graph(request): register_matplotlib_converters() dates_in_string = ['2010-01-01', '2010-01-02', '2010-01-03', '2010-01-04', '2010-01-21'] dates_datetime = [] m = pd.date_range('2015-07-03', '2015-07-20') print(m) for d in dates_in_string: dates_datetime.append(datetime.datetime.strptime(d, '%Y-%m-%d')) dates_float = matplotlib.dates.date2num(dates_datetime) list1 = [0,0,1,4,5,6,3,44,4,6,3,4,5,6,7,8,9,4] plt.grid(True) plt.plot_date(m, list1, linestyle='-', tz=None, xdate=True, ydate=False, label="chat-clicks") plt.title("Chat click Analysis") plt.ylabel("Chat clicks") plt.xlabel("Day") plt.legend(loc='upper left') # for i,j in zip(m,list1): # plt.annotate(str(j),xy=(i,j)) mplcursors.cursor(hover=True) plt.savefig("graph.png") # plt.show() figfile = BytesIO() plt.savefig(figfile, format='png', dpi=300) figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()).decode('utf-8').replace('\n', '') figfile.close() result = figdata_png return render(request,'graph.html', {"result":result}) -
Debugging Django URL Dispatcher
I would love to see the view class or the view method in it's fully packaged path format with every request i submit in my Django application. For example, when i submitted http://localhost/myapp/something, i can debug out in a log file that it actually resolves to my.package.myapp.views.MyViewClass or myViewMethod(). I assumed that i couldnt do this in a middleware as the url is resolved and dispatched after middleware request lifecycle is done. So where should i add the debug to intercept and log this out, other than having to debug all these in my view methods and classes ? -
Django Rest API end-point showing unexpected numeric value instead of string
My each and everything working fine except an awkward issue. At first see my models: from django.db import models from django.contrib.auth.models import User class Author(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) detail = models.TextField() def __str__(self): return self.name.username class Category(models.Model): name = models.CharField(max_length=100) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) and this is serializer class: class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'author', 'title', 'body', 'category'] And this is my views class ArticleSingle(RetrieveAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = 'pk' and my url is path('api/v1/article/<int:pk>/detail', views.ArticleSingle.as_view(), name='article-single'), Everything else working fine but the problem is, when i hit in url to get article details, it show everything else good except an issue and that is, author name and category name returning a numeric value.. below are unexpected result: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "id": 2, "author": 1, "title": "i am title", "body": "i am body", "category": 1 } Please look closely on author and category , it returns me numeric value, why? -
Django Rest Auth: Token-based Authentication Returns Anonymous User Consistently
Currently, I have a custom user setup, in which django-rest-auth handles login/registration/logout. However, I have a custom user model that covers GET, PUT, PATCH, and DELETE methods. For PUT, PATCH, and DELETE, I need my user to be authenticated. Using django-rest-auth and django-rest-framework together, I repeatedly run into the error: Authentication credentials were not provided in my tests, due to my user's lack of authentication resulting in an AnonymousUser object. How can I fix this? Relevant files below. Routes auth: { login: { create(password, [username], [email]) } logout: { list() create() } password: { reset: { confirm: { create(new_password1, new_password2, uid, token) } create(email) } } registration: { verify-email: { create(key) } create(username, password1, password2, [email], [first_name], [last_name]) } } users: { list() read(id) update(id, username, email, [first_name], [last_name]) partial_update(id, [username], [email], [first_name], [last_name]) delete(id) } Views class UserViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (UserOwnerCanEditOrReadOnly, ) Settings REST_FRAMEWORK = { 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), } Permissions from rest_framework import permissions class UserOwnerCanEditOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): # All users (and those not logged-in) can make GET requests # but only the user can use PUT, POST, DELETE … -
Django 2.2 Time and Data Localization Specifics
I am learning Django's ways of doing internationalization and localization. To do so, I am following this tutorial: http://www.marinamele.com/taskbuster-django-tutorial/internationalization-localization-languages-time-zones The issue I have encountered is that the test the tutorial proposes is not working. Furthermore, I cannot see how it could ever have worked. Here is the relevant template bit <div class="row"> <div class="col-md-4"> <h2 id="local-date">{{today}}</h2> <p>This is the time using your local information. </p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> <div class="col-md-4"> <h2 id="non-local-date">{{today|unlocalize}}</h2> <p>This is the default time format. </p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> The view is as follows from django.shortcuts import render import datetime def home(request): today = datetime.date.today() return render(request, "taskbuster/index.html", {'today': today}) The test is below def test_localization(self): today = date.today() for lang in ['en', 'ca']: activate(lang) self.browser.get(self.get_full_url("home")) local_date = self.browser.find_element_by_id("local-date") non_local_date = self.browser.find_element_by_id("non-local-date") self.assertEqual(formats.date_format(today, use_l10n=True), local_date.text) self.assertEqual(today.strftime('%Y-%m-%d'), non_local_date.text) The failure I am seeing is self.assertEqual(today.strftime('%B %d, %Y'), non_local_date.text) AssertionError: 'June 22, 2019' != 'jun. 22, 2019' - June 22, 2019 ? ^ ^ + jun. 22, 2019 ? ^ ^ As you can see, the Catalan version is not the same as the default non-localized version. Am I missing something obvious here? Has something changed with the way … -
How to link static style files to Django app on Apache
I'm in the process of setting up an Apache web server on an Ubuntu VM using Django with the intention of configuring it for production. I used this walk-through to get Apache and Django up and running, and since, I've been following along with the official tutorial provided in the Django docs. I've gotten up to Part 6, which discusses managing static files, but I can't seem to get the styling to apply. Abbreviated Server File Structure: /etc/ --apache2/ ----apache2.conf .... /build/ --django/ <-- Django installation --tstdj/ <-- target project ----manage.py ----polls/ ------... ------static/ --------polls ----------styles.css ------templates/ ----------.... ----------index.html ------urls.py ------views.py ----static/ ------.... ------polls/ --------styles.css ----tstdj/ ------.... ------settings.py ------urls.py ------wsgi.py /etc/apache2/apache2.conf: .... WSGIDaemonProcess www-data processes=2 threads=12 python-path=/build/tstdj WSGIProcessGroup www-data WSGIRestrictEmbedded On WSGILazyInitialization On WSGIScriptAlias / /build/tstdj/tstdj/wsgi.py Alias /static/ /build/tstdj/static <Directory /build/tstdj/tstdj> Require all granted </Directory> <Directory /build/tstdj/static> Require all granted </Directory> <Directory /static> Require all granted </Directory> /build/tstdj/tstdj/settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) .... STATIC_ROOT = BASE_DIR + '/static/' STATIC_URL = '/static/' STATICFILES_DIRS = [ '/build/tstdj/polls/static', ] #STATIC_DIRS = 'static' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] /build/tstdj/polls/templates/polls/index.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/styles.css' %}"> <p><span>My name Jeff</span></p> {% if latest_question_list %} <ul> {% for question in … -
Django: test that creates model works but test that renders template not
I'm learning about testing and I'm using the coverage package. I've problems testing my only view, it queries the DB for today's editorial if not present, it'll return yesterday's editorial. def today_editorial(request): '''it does not handle the case when an editorial has not been created before more than 2 days ''' editorials = Editorial.objects.all().order_by('-id') tz = pytz.timezone('America/Bogota') today_date = datetime.now(tz).date() yesterday_date = today_date - timedelta(days=1) try: today_editorial = Editorial.objects.get(date = today_date) if today_editorial: return render(request, 'editorial/index.html', {'editorials': editorials, 'today_editorial': today_editorial}) except: yesterday_editorial = Editorial.objects.get(date = yesterday_date) if yesterday_editorial: return render(request, 'editorial/index.html', {'editorials': editorials, 'yesterday_editorial': yesterday_editorial}) test_views.py Is curious that this test does not work because the test that creates the Editorial object works. And for this test, I'm just copying the function that creates the Editorial object from the test_models.py file: from django.test import TestCase from django.test import TestCase from editorial.models import Editorial from editorial.views import * from django.utils import timezone from django.urls import reverse # Create your tests here. # views test class EditorialTestViews(TestCase): def create_editorial(self, title="only a test", body="yes, this is only a test"): return Editorial.objects.create(title=title, body=body, url="https://www.google.com", image = "https://img.elcomercio.pe/files/article_content_ec_fotos/uploads/2019/06/19/5d0ae893b3287.jpeg", date=timezone.now()) def test_today_editorial_view(self): e = self.create_editorial() #you've to have create todays editorial for the view to work … -
How To Set Initial Form Field Value From View in Django
I am trying to set the initial value of a form field from my view. I've read the documentation and some other questions on here and I can't determine why my case is not working. In one form (CreateOrderForm) I am entering a value for the 'reference' field. In my next view, I use .get to retrieve that input and then try to default the 'reference' field in the CreateManifestForm to be the same. I get no error, but no value comes in. Below is what I am attempting: FORMS.PY class CreateOrderForm(forms.ModelForm): class Meta: model = Orders fields = ('reference', 'ultimate_consignee', 'ship_to', 'vessel', 'booking_no', 'POL', 'DOL', 'COO', 'POE', 'ETA', 'pickup_no', 'terms', 'sales_contact', 'trucking_co', 'loading_loc', 'inspector', 'total_cases', 'total_fob', 'freight_forwarder', 'commodity', 'is_airshipment', 'credit') class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'description', 'count') VIEWS.PY def add_order(request): if request.method == "POST": form = CreateOrderForm(request.POST) objectlist = Customers.objects.all() if form.is_valid(): reference_id = form.cleaned_data.get('reference') form.save() return redirect('add_manifest')#, kwargs={'reference_id': form.cleaned_data['reference']}) else: form = CreateOrderForm() objectlist = Customers.objects.all() context = { 'form': form, 'objectlist': objectlist, } return render(request, 'add_order.html', context) def add_manifest(request): if request.method == "POST": form = CreateManifestForm(request.POST) if form.is_valid(): form.save() return redirect('add_manifest') reference_id = request.POST.get('reference') form = CreateManifestForm(initial={'cases': reference_id}) manifests = Manifests.objects.all().filter(reference=reference_id) … -
Add new item in Django admin then redirect to another page
I want to add a link from a custom template that goes into a Django admin add page: The model it will change is dynamic as seem in the code below, but it will have a select field, that I want to bring it already filled and disabled from further changes until saving if possible; After saving it goes back to the same template (passing through the view); Update the charts I have in the template with the new data. I think the easiest way was to open the add page into a popup, but after the model is saved it returns to the list and doesn't close the popup, maybe there's a property to make that happen? I tried _is_popup but it does nothing. Another thing I tried was messing around with the admin template called submit_line.html and admin_modify.py templatetag. <a href="/admin/core/{{ indicator_key }}/add/?_is_popup=1" target="popup" onclick="window.open('/admin/core/{{ key }}/add/?_is_popup=1', 'popup','width=600,height=800'); return false;"></a> -
Django - Using allauth credentials to send emails through Gmail API
I've been able to add Allauth Google OAuth2 authentication to my Django webapp. However, I've been having trouble understanding how to use the access token to send a email through the Gmail API. This is the documentation that I have been following: https://developers.google.com/gmail/api/auth/web-server I'm confused about how to use the user token that was authorized by Allauth in the gmail api. My goals is to allow the user who signed in to send an email (using their own email addresses) through a form in the Django app. -
Django: Exception Value 'Gifts' object is not iterable
Doing this causes error gifts = get_object_or_404(Gifts) While doing this does not. gifts = Gifts.objects.all(); Django: Exception Value 'Gifts' object is not iterable from django.shortcuts import render,redirect, get_object_or_404 from .models import Gifts def home(req): gifts = get_object_or_404(Gifts) #gifts = Gifts.objects.all() return render(req,'gifts/gift_home.html',{"gifts":gifts}) -
error in from .murmurhash import murmurhash3_32
I try to run it but Ifound this error, I have already try it and all it is ok but I have change in same version of packages and I get this error from sklearn.externals import joblib File "C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\f\lib\site-packages\sklearn\__init__.py", line 134, in <module> from .base import clone File "C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\f\lib\site-packages\sklearn\base.py", line 13, in <module> from .utils.fixes import signature File "C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\f\lib\site-packages\sklearn\utils\__init__.py", line 9, in <module> from .murmurhash import murmurhash3_32 File "sklearn\utils\murmurhash.pyx", line 26, in init sklearn.utils.murmurhash File "__init__.pxd", line 1000, in numpy.import_array ImportError: numpy.core.multiarray failed to import -
How to Pass User Entered Parameter in Django
I have a view for entering an "order" which once submitted renders a view to create a "manifest" which may have multiple entries. For each order, the user enters a "reference id" and in the corresponding manifest, the reference id must be the same as the order (reference id in Manifests model is a foreign key to Orders model). I need a way for the reference ID of the Order to post to the Manifests model for each line entered in the Manifest without the user having to enter it each time. I was trying to either pass the reference ID through the url (I am in Django 1.10) but can't figure out how to leverage that. I also was toying with the idea of using .get to get the reference id from the order and make it a read only field in the Manifest view, but I couldn't figure that out. MODELS.PY class Orders(models.Model): reference = models.CharField(max_length=50, unique=True) ultimate_consignee = models.ForeignKey(Customers, blank=True) ship_to = models.CharField(max_length=500, blank=True) vessel = models.CharField(max_length=100, blank=True) def __str__(self): return self.reference class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() description = models.CharField(max_length=1000) count = models.IntegerField() def __str__(self): return self.reference VIEWS.PY def add_order(request): if request.method == "POST": … -
Reverse Django admin URLs
As described this answer, we can use the url tag to reverse Django admin URLs. Django [documents][1]. However, in the examples shown there, you need the app name and model name in the string passed to url. Is there a way to pass those in as parameters instead? What I'm looking to do is something like this: {% url 'something here' app_name model_name object_id %} What do I put for 'something here'? -
Using both Groups and Individual Permissions
In Django I have created a system with various groups of users. Using django.auth I have also created permission groups and I have associated the appropriate application permissions for each group. This works great for role based access, but now I have a requirement where I also need the ability to remove individual permissions from a specific user in a group. This means I need group permissions, but at the same time these group permissions can be unassigned to individual users. Using Django groups this appears to not directly be possible as the permissions are abstracted from individual users. How can I accomplish this? I am in the process of changing everything to individual user permissions, but this seems a bit tedious for clients if they have to manually set permissions for each new user, I am hoping someone knows of a better way. -
Atom not finding search terms in django.po?
I've found that if I do a project-wide search for a certain term, I can't find it, yet if I open django.po and search locally, I can find what I'm looking for. It seems that django.po is no longer 'indexed' for search. I seem to recall this working before, so it might be a side-effect of a package I recently installed. In any case, I would like the search index in Atom to include django.po, but I wasn't able to find documentation on how to do this. Do anybody know? P.S. In case it is relevant, here is a list of the packages I have installed: -
How to Set Checkbox Checked if Value Is Yes (Django)
I have a form which I am prefilling through a GET request. I am setting the value of a checkbox to either Yes or No. I would like to set the checkbox to checked if the value is Yes. script <script> if ($('#cisco').val() == 'Yes') { $('#cisco').prop('checked', true); } </script> form.html <div class="field"> <div class="control"> <label class="checkbox"> <input type="checkbox" name="cisco" id="cisco" value="{{ request.GET.cisco }}">Cisco: </label> </div> </div> -
how to see Django session in postman?
I think when some API request Django server, Django create a session and store it in database. This session were in each request and response, 1. I want to see session, and their data like session_key and ... in postman native app 2. How can I access to this session in apiview or I access it just in middlewere!? for my first problem, I tried using cookies in postman, but I can't find what I want for my second one I tries : from django.contrib.sessions.models import Session and SessionStore but they didn't me session in request also I tried to use request.session. but this didn't get me session_key.` here I try make new session but I found myself as a failure! class UserRegisterView(APIView): def post(self, request, format=None): phone = dict(request.data)['phone'][0] try: user = User.objects.get(phone=phone) except User.DoesNotExist: user = User(phone=phone) session = Session.objects.get_or_create() I expect that can add some data to Django session and it store in servers database, after I can understand witch user with witch device send request and receive response. then monitor and test my app with postman. (Sorry I know I'm not good in English, I hope I could explain my problem)