Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UpdateView teamplate_name_suffix is not working
I have the following code views.py class PageCreate(CreateView): model = Page fields = ['title', 'content', 'order'] success_url = reverse_lazy('pages:pages') class PageUpdate(UpdateView): model = Page fields = ['title', 'content', 'order'] teamplate_name_suffix = '_update_form' def get_success_url(self): return reverse_lazy('pages:update', args=[self.object.id]) + '?ok' page_form.html {% extends 'core/base.html' %} {% load static %} {% block title %}Crear página{% endblock %} {% block content %} {% include 'pages/includes/pages_menu.html'%} <main role="main"> <div class="container"> <div class="row mt-3"> <div class="col-md-9 mx-auto"> <div> <form action="" method="post">{% csrf_token %} <table> {{ form.as_table }} </table> <br> <input type="submit" value="Crear página" /> </form> </div> </div> </div> </div> </main> {% endblock %} page_update_form.html {% extends 'core/base.html' %} {% load static %} {% block title %}Actualizar página{% endblock %} {% block content %} {% include 'pages/includes/pages_menu.html'%} <main role="main"> <div class="container"> <div class="row mt-3"> <div class="col-md-9 mx-auto"> <div> {% if 'ok' in request.GET %} <p style="color:green;"> Pagina editada correctamente <a href="{% url 'pages:page' page.id page.tittle|slugify %}"></a> </p> {% endif %} <form action="" method="post">{% csrf_token %} <table> {{ form.as_table }} </table> <br> <input type="submit" value="Actualizar página" /> </form> </div> </div> </div> </div> </main> {% endblock %} urls.py path('create/', PageCreate.as_view(), name='create'), path('update/<int:pk>/', PageUpdate.as_view(), name='update') The problem is that when i go to the update page it's loading the … -
Django get foreign key model type for OneToMany field
So in Django 1.10 I am trying to extract the model for a specific attribute that is a foreign key in a one-to-many relationship with the parent class. For example: class some_class(models.Model): some_text = models.TextField(blank=True, null=True) class another_class(models.Model): a_field = models.TextField(blank=True, null=True) many = models.ForeignKey(some_class, models.SET_NULL, db_column='some_class_id', related_name='another_class_things', blank=True, null=True) If I was to do: the_class = some_class._meta.get_field('another_class_things').rel.to I get the error: 'ManyToOneRel' object has no attribute 'rel' This works alright when there is a one-to-one relationship, however it doesn't work for one-to-many relationships. What is an alternative to get the model of the attribute? (ie: return 'another_class' in the above situation) -
Deploying Django project on Apache/Ubuntu
I'm trying to deploy my Django project on Apache but it's very hard for me. I'm going to explain what I did these days and maybe you can see the fail. 1. Annotations: My project is located in james/DjangoRFV and I don't have a virtual env. I'm not sure if this is important, but this django project is in a remote server that I'm acceding using ssh, specifically port 2222. What I have it's an ip direction, like 172.33.52.8 (not real). 2. Deploying on apache: First I create the virtual host file like this, <VirtualHost *:80> ServerAdmin admin@DjangoRFV.localhost ServerName DjangoRFV.localhost ServerAlias www.DjangoRFV.localhost DocumentRoot /home/james/DjangoRFV ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/james/DjangoRFV/static <Directory /home/james/DjangoRFV/static> Require all granted </Directory> Alias /static /home/james/DjangoRFV/media <Directory /home/james/DjangoRFV/media> Require all granted </Directory> <Directory /home/james/DjangoRFV/DjangoRFV> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess DjangoRFV python-path=/home/james/DjangoRFV python-home=/home/james/DjangoRFV/env WSGIProcessGroup DjangoRFV WSGIScriptAlias / /home/james/DjangoRFV/DjangoRFV/wsgi.py </VirtualHost> Now I enable the virtual host file. cd /etc/apache2/sites-available sudo a2ensite djangoRFV.conf Some permissions sudo ufw allow 'Apache Full' Check syntax errors: sudo apache2ctl configtest 3. Modify wsgi.py: import os, sys #path a donde esta el manage.py de nuestro proyecto Django sys.path.append(‘/home/james/DjangoRFV/’) #referencia (en python) desde el path anterior al fichero settings.py #Importante hacerlo … -
Django nginx uwsgi can' work in linux normal user
I successful run Django nginx uwsgi in root few days ago. But I fail in normal user today. The error message follow this: detected binary path: /home/disney/IP_lookup/IP_lookup_venv/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/disney/IP_lookup/mysite your processes number limit is 128426 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) error removing unix socket, unlink(): Permission denied [core/socket.c line 198] bind(): Address already in use [core/socket.c line 230] I already read this article: Could not start uwsgi process But I don't know how to change my uwsgi.ini. my uwsgi.ini: [uwsgi] # Django-related settings # the base directory (full path) chdir = /home/disney/IP_lookup/mysite # Django's wsgi file module = mysite.wsgi # the virtualenv (full path) home = /home/disney/IP_lookup/IP_lookup_venv # process-related settings # master master = true # maximum number of worker processes processes = 2 # the socket (use the full path to be safe socket = /home/disney/IP_lookup/mysite/mysite.sock # ... with appropriate permissions - may be needed # chmod-socket = 777 uid = www-data gid = www-data # clear environment on exit vacuum = true -
How do I use a ModelChoiceField in the Django Admin
I am trying to figure out how to use a ModelChoiceField to get the select options from the database and display a field as a select box (single select) in the Django admin area on the model form page. The code I have in the modelform is shown below but the field is showing as a text field and obviously isn't populated with any of the options (yes they exist in the database SomeObjectHere table). I also need to know how to do the same with a multiple choice select (more than one selection) from .models import * from django import forms from django.forms import ModelForm, Textarea, RadioSelect, CheckboxInput,CheckboxSelectMultiple, TextInput, Select from references.models import * class MyModelForm(ModelForm): PropertyName = forms.ModelChoiceField(queryset=SomeObjectHere.objects.all()) class Meta: model = MyModel fields =('__all__') # exclude = ('',) widgets = { 'PropertyNameHere' : Select() } def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args,**kwargs) The Admin.py looks like this: class MyModelAdmin(admin.ModelAdmin): not really sure what i need to do here. I'm using grapelli which is using the media class class Media: js = [ '/static/grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js', '/static/grappelli/tinymce_setup/tinymce_setup.js', ] -
how to represent equivalent java class in python
I have a class relationship in java like this: class A (){ private string var1 } class B (){ private string var2 } class C (){ private string var3 List<A> aList = new ArrayList<A>(); List<B> bList = new ArrayList<B>(); } class D (){ private string varD List<C> cList = new ArrayList<C>(); } how do I represent such a relationship between class in python ?? -
Why isn't django.contrib.auth.authenticate() working here?
I'm writing a simple (for now) Django app. I'm having trouble with authentication: I'm trying to use all of the out-of-the-box components, and both in the app itself and in tests, I can't authenticate users. So, for example, here's a test that fails: from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.test import TestCase [...] class UserTestCase(TestCase): def setUp(self): self.testu = User(username="thename", password="thepassword", first_name="thefirstname") self.testu.save() def testAuthenticate(self): u = authenticate(username="thename", password="thepassword") self.assertEqual(u.first_name, "thefirstname") I get an AttributeError: 'NoneType' object has no attribute "first_name". I think this is because authenticate() is returning None (representing that there is no such user). This fails whether or not I include the line "self.testu.save()". I have other tests that pass, so I don't think the problem is with the test infrastructure. I can successfully create users and retrieve their information from the database. The only mention of User in models.py is: from django.contrib.auth.models import User I've read through a lot of documentation but can't figure out what's going on. Can anyone help? Thanks in advance. -
Django Rest framework serialier for categorywise data
I have a model named JobTite: class JobTitle(BaseModel): """ Store job titles used in benchmarking """ benchmark_role = models.ForeignKey( BenchmarkRole, on_delete=models.SET_NULL, related_name='job_titles', null=True, blank=True ) name = models.TextField() description = models.TextField(null=True, blank=True) count = models.IntegerField( validators=[MinValueValidator(0)], null=True, blank=True ) class Meta: constraints = [ models.UniqueConstraint(fields=['benchmark_role', 'name'], name='unique_job_title') ] def __str__(self): return "{}-{}".format(self.benchmark_role, self.name) I need to get the top 10 JobTtles for each benchmark_role and return a JSOn something like this: [{"benchmark_role_1": [ {name: "ABC", desc: 'DESC', count: 9}, {name: "def", desc: 'DESC', count: 6}, {name: "XR", desc: 'DESC', count: 4}, {name: "AS", desc: 'DESC', count: 2}, {name: "RE", desc: 'DESC', count: 3}, {name: "Q", desc: 'DESC', count: 1}, {name: "QW", desc: 'DESC', count: 0}, {name: "AS", desc: 'DESC', count: 0}, {name: "W", desc: 'DESC', count: 0}, {name: "EW", desc: 'DESC', count: 0}, ]}, {"benchmark_role_2": [ {name: "AAC", desc: 'DESC', count: 8}, {name: "dAf", desc: 'DESC', count: 6}, {name: "QW", desc: 'DESC', count: 4}, {name: "AS", desc: 'DESC', count: 2}, {name: "QE", desc: 'DESC', count: 3}, {name: "Q", desc: 'DESC', count: 1}, {name: "QW", desc: 'DESC', count: 0}, {name: "AS", desc: 'DESC', count: 0}, {name: "W", desc: 'DESC', count: 0}, {name: "EW", desc: 'DESC', count: 0}, ]}, ...] My curent … -
How to use rest api in kivy to upload a file to a django website
am currently working on a system that involves building a website an a mobile application. I am using kivy to build my application however am facing an issue with using the django rest api to upload files to the site through kivy. How can I go about it. This is my function in main.py for uploading the file def upload(self, filepass, filename): print(str(filename)) def upload(self, filepass, filename): print(str(filename)) try: requests.post('http://127.0.0.1:8000/upload/', filepass) except: toast('Could not upload file')def upload(self, filepass, filename): print(str(filename)) try: requests.post('http://127.0.0.1:8000/upload/', filepass) except: toast('Could not upload file') try: requests.post('http://127.0.0.1:8000/upload/', filepass) except: toast('Could not upload file') This is my api view in my views.py class FileUploadView(APIView): parser_class = (FileUploadParser,) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data['files']) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is my models.py for the database of the uploaded file class File(models.Model): file = models.ImageField(upload_to='landbroker/', default='default.png') def __str__(self): return self.file.name This is my serializers.py for the file upload from rest_framework import serializers from .models import File class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = "__all__" And finally my urls.py path('upload/', views.FileUploadView.as_view()) With all that, whenever I try to submit the image django outputs unsupported file format. Please help. -
How to insert an image to an excel file with xlsxwriter?
I have to write images with some other datas to an excel file in my Django project and I have tried the code below. for counter_i, cost in enumerate(costs): counter_i += 1 for counter_j, feature in enumerate(features): value = getattr(cost, feature) if feature == 'image': image = str(value) worksheet.insert_image(counter_i, counter_j, image, {'x_offset': 15, 'y_offset': 10}) else: worksheet.write(counter_i, counter_j, value) In this code, the "value" contains image's path. But I got errors such as warn("Image file '%s' not found." % force_unicode(filename)) Also I have tried to give the whole path such as C:/Users/username/.. but this time, I got an Permission Denied error. How can I fix this? -
Field 'id' expected a number but got <QueryDict:
When I Submit Form I Got This Errors TypeError at /employee/ Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['vfO31XU2Y8x9MBzfUZ7rnq4widBlrt2uu6aF63ZorSW9DO6Rv8gjNE72SIN0YY1p'], 'name': ['Training'], 'designation': ['1'], 'department': ['1'], 'phone': ['12345'], 'date_of_birth': ['2020-12-31'], 'card_number': ['124'], 'pin': ['1234']}>. Request Method: POST Request URL: http://127.0.0.1:8000/employee/ Django Version: 3.0.3 Exception Type: TypeError Exception Value: Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['vfO31XU2Y8x9MBzfUZ7rnq4widBlrt2uu6aF63ZorSW9DO6Rv8gjNE72SIN0YY1p'], 'name': ['Training'], 'designation': ['1'], 'department': ['1'], 'phone': ['12345'], 'date_of_birth': ['2020-12-31'], 'card_number': ['124'], 'pin': ['1234']}>. Why i got this errors ? What's wrong in my code :( The code snippets of views.py def employee_list(request): if request.POST and request.FILES: form = EmployeeForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user = RiverTimeUser.objects.create_user( username=request.POST.get('name'), pin=int(request.POST.get('pin')), password=request.POST.get('pin') ) data.save() messages.add_message(request, messages.SUCCESS, 'New Employee Added Successfuly') context = { 'object_list': Employee.objects.filter(department__institute=request.user.institute), 'form': EmployeeForm(request.user.institute) } return render(request, 'employee.html', context=context) -
Django/Nginx/Gunicorn/Supervisor: internationalisation is not applied
I try to deploy my Django project in a remote linux server (Ubuntu) I have followed an Openclassroom tutorial and it work except internationalisation I have had this problem when I deployed with alwaysdata because missing lines in my settings.py Here I checked all internationalisation settings are present (MIDDLEWARE, LANGUAGES, LOCAL_PATH) and it seems to be I try to set absolute path to my locale files (containing internationalisation files .po) but did not change anything but as gunicorn is running maybe change in settings;py have not been applyed ? architecture of my project: envs intensetbm_app | intensetbm-etool | | intenseTBM_eTool | | | wsgi.py | | | settings.py | | | ... | | manage.py | | locale | | | fr | | | | LC_MESSAGES | | | | | django.po | | ... intensetbm_static settings.py: import os import psycopg2.extensions from django.utils.translation import ugettext_lazy as _ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['192.168.80.6',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'widget_tweaks', 'bootstrap4', 'registration.apps.RegistrationConfig', 'monitor.apps.MonitorConfig', 'randomization.apps.RandomizationConfig', … -
Django jQuery-File-Upload upload Adding the user_id to the Model
I am using jQuery-File-Upload in Django based on this tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html I want to add the User_id to the Model. This View is using JSON data passed from the html jquery. Do I modify the json or can I add it in the Model? Thank you. MODEL: class Files(models.Model): file = models.FileField(upload_to="uploads/%Y/%m/%d/") created = models.DateTimeField ( auto_now_add = True ) VIEW: class BasicUploadView(View): def get(self, request): file_list = Files.objects.all() content = { 'files': file_list } return render(self.request, 'upload/index.html', content ) def post(self, request): user_id = request.user.id form = UploadForm(self.request.POST, self.request.FILES) if form.is_valid(): file = form.save() data = {'is_valid': True, 'name': file.file.name, 'url': file.file.url} else: data = {'is_valid': False} return JsonResponse(data) -
Django mock not getting called at all
I have test defined looking like below @patch('user.serializers.validate_sns_token', return_value=True) def test_can_create_user(self, validate): """ Test that user can be created without logging in :return: """ user_payload = self.generate_user_payload() resp = self.client.post( CREATE_USER_URL, user_payload, ) self.assertTrue(validate.called) self.assertEqual( resp.status_code, status.HTTP_200_OK, ) Inside the user.serializers.py file I have below function that I would like to mock def validate_sns_token(**kwargs): try: ... return True except ValueError as e: ... return False It's an external call to google api so I would like to always return True from it. Inside the serializer I am calling the create function like below def create(self, validated_data): ... is_token_valid = validate_sns_token( sns_id=sns_id, sns_type=sns_type, token=token, ) if is_token_valid is False: raise serializers.ValidationError('토큰이 유효하지 않습니다. 다시 로그인해주세요.', code='AUTH') ... return user Unfortunately, the validate.called is always False and the original validate_sns_token is still getting called. How do I write a test so that the original validate_sns_token is not called at all but its return value is set to True? -
ConnectionResetError while playing a video file over Django, with FileField and HTML5 video tag
I'm having a Django project, where a FileField is applied for storing a video file (mp4). The Video File is actually stored on AmazonS3. The video file is then showed on the corresponding HTML, though Django DetailView, with an HTML5 video tag. <video width='50%' controls> <source src="{{ object.video_sample.url }}" type="video/mp4"> Your browser does not support the video tag. </video> The video is played well both locally (local ip) on and on deployed server. However, I'm keep getting this annoying error message on terminal/logs: > Exception happened during processing of request from (...) Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in init self.handle() File ".../env/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File ".../env/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer I think that it related with the fact user leaves the HTML page while the video is still open. Do you know how to get it resolved? BR, Shahar -
How to send notifications on email associated with user
i want to send sports related informatin on the email of users living in particular city, that users are already registered.How can i do that. I want to do that with the help of vieset and router,without serializer. class Notification(models.Model): Title=models.CharField(max_length=100,blank=False,null=False) Message=models.TextField() Location=models.CharField(max_length=20,blank=False) Sport=models.ForeignKey(Sport,on_delete=models.CASCADE) def __str__(self): return str(self.Title) -
Using and editing Python Site-packages
I'm using a package that I would like to be able to edit directly instead of appending views and functions to the package from my project. How would I do this? Can I copy the package into my project/root - or is this bad? I tried moving the package and then the Scripts could not execute the commands for that package anymore. Whats the best practice for this kind of stuff? I am aware that moving the package will mean I can't update it, but that's not an issue, editing the package would just be easier than appending things to it. Open to all suggestions :) -
How do I send image to backend from React without using FormData?
I want to send image with additional data from React.js to Django backend. When I used FormData() to create my form data, it could not send the array (because it converted it to string). Here is my code: let formData = new FormData(); formData.append('text', postForm.text); formData.append('image', postForm.image, postForm.image.name); formData.append('privacy', postForm.privacy); formData.append('custom_list', postForm.customList); props.createPost(formData); when I used this, I got this error: {"custom_list":["Incorrect type. Expected pk value, received str."]} So, I tried to create my own object to send to backend, but it can't handle image data. The code is: const formData = { text: postForm.text, image: postForm.image, privacy: postForm.privacy, custom_list: postForm.customList } This gave the following error: {"image":["The submitted data was not a file. Check the encoding type on the form."]} Is their any way I can send both list and image simultaneously? -
Django nice publication date rendering (i.e., "an hour ago" vs. "February 10, 2020")
I am building a dictionary app using Django. The app has a feed where definitions are displayed, where each definition has a publication date. My problem: publication dates rendered on templates look like "published on February 10, 2020", or similar. For my purpose, this is okay for old definitions, but not for more recent ones. My goal: recent publication dates should be rendered as "published an hour ago", "published yesterday", or similar. I have not been able to find any Django built-in tag or filter that does this automatically. Is there an easy way to achieve this in Django? If not, can anybody suggest a solution? -
Django ForeignKey with brackets: model cannot be resolved
I need to use brackets to define my foreign key in Django. Unfortunately I get an error I can't fix.. raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'Deck' cannot be resolved This is my model: class DeckDevice(models.Model): deck = models.ForeignKey( "Deck", on_delete=models.CASCADE, related_name="deckdevice" ) #somemorecode my migration: #somemoremigrations migrations.CreateModel( name="DeckDevice", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("start", models.DateTimeField()), ("end", models.DateTimeField(blank=True, null=True)), ( "deck", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="film.Deck" ), ), ], ), -
Python - extract all variables from a dict into locals
Is there a simple and elegant way to extract all variables from a dict to the current module locals? I am using Django and we would like to load all values of the local_settings.py file which is something like: DEBUG=True KEY="VALUE" NUMKEY=1 ... from a json, which will be compatible: { "DEBUG": true, "Key": "VALUE", "NUMKEY": 1 } so I'm looking for a simple way to extract all in few lines into the local variables of the settings.py file. Thank you! -
Django with Azure blob shared access signature
I am using azure blob storage for my media files in my django application. I need to implement shared access signature. Please help me to proceed. I am unable to find any docs or material to refer. Any help is appreciated. I tried with django-storages[azure] and upload alone works if i set the connection string. -
Django,HTML , connecting template to js,css
I have a Django project that contains a landing page. I worked on it outside the project and the HTML page was able to route to the js and CSS files and it worked great. Once I copied the folder into the project's templates folder (as shown in the structure below), And added routes and views in the project as required The server ran okay and open the page, But it's showing only the HTML and cannot refer to raises errors when trying to refer to the js scripts. for example: Not Found: /templates/js/main.js [19/Mar/2020 08:22:12] "GET /templates/js/main.js HTTP/1.1" 404 2490 # home.hmtl <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="yovelcohen" content="Sumon Rahman"/> <meta name="keywords" content="HTML,CSS,XML,JavaScript"/> <meta http-equiv="x-ua-compatible" content="ie=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!-- Title --> <title>Triangulation Calculator</title> <!-- Plugin-CSS --> <link rel="stylesheet" href=".css/bootstrap.min.css"/> <link rel="stylesheet" href=".css/owl.carousel.min.css"/> <link rel="stylesheet" href=".css/linearicons.css"/> <link rel="stylesheet" href=".css/magnific-popup.css"/> <link rel="stylesheet" href=".css/animate.css"/> <!-- Main-Stylesheets --> <link rel="stylesheet" href=".css/normalize.css"/> <link rel="stylesheet" href=".style.css"/> <link rel="stylesheet" href=".css/responsive.css"/> <script src="js/vendor/modernizr-2.8.3.min.js"></script> </head> <body> <!-- MainMenu-Area-End --> <!-- Home-Area --> <header class="home-area overlay" id="home_page"> </header> <!-- Home-Area-End --> <!-- About-Area --> # some HTML stuff ... <!-- Footer-Area-End --> <!--Vendor-JS--> <script src="templates/js/vendor/jquery-1.12.4.min.js"></script> <script src="templates/js/vendor/jquery-ui.js"></script> <script src="templates/js/vendor/bootstrap.min.js"></script> <!--Plugin-JS--> <script src="templates/js/owl.carousel.min.js"></script> <script src="templates/js/contact-form.js"></script> … -
Permission error in oauath2 using access token django
I am trying to generate an access token like this in django-rest-framework: def generate_access_token(request, user): expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS'] scopes = oauth2_settings.user_settings['SCOPES'] application = Application.objects.get(name="test") expires = datetime.datetime.now() + timedelta(seconds=expire_seconds) access_token = AccessToken.objects.create(user=user, application=application, token=random_token_generator(request), expires=expires) token = { 'access_token': access_token.token, 'token_type': 'Bearer', 'expires_in': expire_seconds, 'scope': scopes } return token This is generating an access token, but when I am trying to use that access token to access other protected apis, it is giving me the following error:- { "detail": "You do not have permission to perform this action." } On the other hand, if I generate access token using the TokenView, that token is working fine. I am trying to manually create an access token using a user object returned on user registration and login. How can I get rid of this error, or what is the alternative to achieve this ? -
logout automatically in all tabs when logged out in one open tab with django
Is it possible to auto logout a user from all opened tabs(Popup window), if that user logoout from one of the open tab in the browser in django. If it is possible then How can I implement? Thanks in advance...