Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use android studio in place of Pycharm for learning Django .. If No.. why? and if Yes ..how?
I am learning Django and the tutorial requires downloading Pycharm, which looks almost similar to my android studio IDE. So, can I do the same with android studio or I will have to download Pycharm ? -
Django, how to return a file after form submit?
I want to let the user submit a form with some filter criteria and respond with a csv file. This is my code: template: <form action="{% url 'filter_tracks' %}" method="get" id="filter-form"> <various filter params> ... <a class="md-btn" href="javascript:void(0)" onclick="$('#filter-form').submit();" id="csv_btn">Export</a> </form> views.py filename = "TRACKS_EXP{x}_{z}.csv".format(x=int(time.time()), z=lang) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{x}"'.format(x=filename) response.write(u'\ufeff'.encode('utf8')) writer = csv.writer(response, delimiter=',', dialect='excel', quotechar = "\"", lineterminator='\r\n',) for track in track_list: writer.writerow([...]) return response Although it works, I get the data inside my HTML page and not in a downloadable file. What am I doing wrong? -
Error while migrating Key (Category_id)=(1) is not present in table (after makemigration i put the default value=1 so problem came)
class Category(models.Model): type = models.CharField(max_length=100) def __str__(self): return self.type class Destination(models.Model): category = models.ForeignKey(Category,models.CASCADE) name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default = False) sittayma = models.BooleanField(default= True) vid = models.FileField(upload_to='Video') -
How to assign objects in Foreign Keys in DRF?
My model: class Status(models.Model): COURSE_STATUS = ( ('COMPLETED', 'Completed'), ('ASSIGNED', 'Assigned'), ('PROGRESS', 'In progress'), ) course_status = models.CharField(max_length=9, choices=COURSE_STATUS, default='ASSIGNED' ) course_completion_date = models.DateField(blank=True, null=True, ) course = models.ForeignKey(TrainingCourse, on_delete=models.CASCADE, related_name="courses") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="students") Serializer: class AssignUserSerializer(serializers.ModelSerializer): class Meta: model = Status fields = '__all__ View: class StatusView(ModelViewSet): serializer_class = AssignUserSerializer queryset = Status.objects.all() permission_classes = [AllUsersProfileOnly, IsAuthenticated] I wanna make POST REQUEST and create and add to some users{id} to specific course such a "id": 35, "course_status": "PROGRESS", "course_completion_date": "2010-09-09", "course": 29, **"user": 3,** "id": 36, "course_status": "PROGRESS", "course_completion_date": "2010-09-09", "course": 29, **"user": 4,** now I got error like "Incorrect type. Expected pk value, received str." if try to send more than one id into user field error from Postman -
Problem in displaying 3 columns in my Django Blogapp....Only one column is shown...Its in masonry grid system
I made a blogapp using Django framework. Iam facing problem in displaying the posts.I want posts to be displayed in 3 columns but its showing in just 1 column...Please help me in editing my code... This is the code: **** {{ post.title }} {{ post.category }} {{post.created_date}} {{ post.text | slice:":200"}} -
SocketIo integration with Django
I have been trying to integrate socketio with Django, And I am getting the following error. [31/Mar/2020 14:50:27] "GET /socket.io/?EIO=3&transport=polling&t=N4n4ds4&b64=1 HTTP/1.1" 200 117 [31/Mar/2020 14:50:27] "POST /socket.io/?EIO=3&transport=polling&t=N4n4dsj&b64=1&sid=9053be92266c46148304c09833b2ebe8 HTTP/1.1" 200 2 Traceback (most recent call last): File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/django/contrib/staticfiles/handlers.py", line 68, in __call__ return self.application(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/middleware.py", line 60, in __call__ return self.engineio_app.handle_request(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/socketio/server.py", line 558, in handle_request return self.eio.handle_request(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/server.py", line 377, in handle_request environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/socket.py", line 108, in handle_get_request start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/socket.py", line 152, in _upgrade_websocket return ws(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/async_drivers/eventlet.py", line 16, in __call__ raise RuntimeError('You need to use the eventlet server. ' RuntimeError: You need to use the eventlet server. See the Deployment section of the documentation for more information. [31/Mar/2020 14:50:27] "GET /socket.io/?EIO=3&transport=websocket&sid=9053be92266c46148304c09833b2ebe8 HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52220) Traceback (most recent call last): File "/usr/local/opt/python/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/opt/python/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/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/murali/yourenv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/murali/yourenv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: … -
How to deploy bootstrap theme "QuixLab" in django?
I know similar questions have been answered before but believe me this is not replication. I have gone through each and every bit of answer but not able to solve my problem. I am just trying to deploy a bootstrap theme in django. I have done everything, that should be done but still css and jquery is not getting picked up in html forms. Settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] index.html , all links have been set like these: <link href="{% static 'assets/css/lib/font-awesome.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/lib/themify-icons.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/lib/menubar/sidebar.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/lib/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/style.css' %}" rel="stylesheet"> <script src="{% static 'assets/js/lib/owl-carousel/owl.carousel.min.js' %}"></script> <script src="{% static 'assets/js/lib/owl-carousel/owl.carousel-init.js' %}"></script> <script src="{% static 'assets/js/scripts.js"></script> Everything is in its place but css is not getting picked up while I have seen that all images are getting picked up that means static folder is getting accessed properly. When I see terminal, I finds lines like these: [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/weather/jquery.simpleWeather.min.js HTTP/1.1" 404 1773 [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/weather/weather-init.js HTTP/1.1" 404 1737 [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/owl-carousel/owl.carousel.min.js HTTP/1.1" 404 1764 [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/owl-carousel/owl.carousel-init.js HTTP/1.1" 404 1767 For testing, I deploy another … -
Updating the axis of a highcharts chart object using jquery after inital render (django)
I can seem to figure out a basic question I’ve got a highcharts chart in my django app that is getting loaded in the template. The data for the chart is getting populated via ajax. I’d like to add a button above the chart which if clicked toggles the axis to logarithmic (instead of the default, linear) but I can’t seem to make this work Here’s my code HTML <button id="target" type='button' > switch to log </button> <div id="container1" style="width:100%; height:400px;"></div> Javascript <script> $(document).ready(function() { var chartOptions = { chart: { renderTo: 'container1', type: 'line', }, title: {text: null}, xAxis: {title: {text: null}, labels: {rotation: -45}}, yAxis: {title: {text: 'Item counts'}, type: 'linear', stackLabels: {enabled: true}, }, plotOptions: {column: {dataLabels: {enabled: false}, stacking: 'normal'}}, series: [{}], }; var chartDataUrl = "{% url 'global_trend_chart' %}" ; $.getJSON(chartDataUrl, function(data) { chartOptions.xAxis.categories = data['chart_data']['date']; chartOptions.series[0].name = 'Global counts'; chartOptions.series[0].data = data['chart_data']['item_counts']; var chartA = new Highcharts.Chart(chartOptions); }); $( "#target" ).click(function() { chartA.update({ yAxis: { type: 'logarithmic', } }); }); } ); </script> I appreciate the help -
I can't add a record from the django form into a database
I have this function in views.py file that responsible for adding a record into the Database def add_academy(request,pk): child = get_object_or_404(Child_detail, pk=pk) academic = Academic.objects.get(Student_name=child) form = AcademicForm(request.POST, instance=academic) if form.is_valid(): form.save() return redirect('more',pk=pk) #it will redirect but can't create a new record else: form=AcademicForm() context = { 'academic':academic, 'child':child, 'form':form, } return render(request,'functionality/more/academy/add.html',context) And here is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class','Date','Average_grade','Overall_position','Total_number_in_class' labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) And here is my model.py file class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) Date = models.DateField() Average_grade = models.CharField(max_length = 10) Overall_position = models.IntegerField() Total_number_in_class = models.IntegerField() def __str__(self): return str(self.Student_name) And also this is my template will be used to display form <div class="card-body"> <form action="" method="POST" autocomplete="on"> {% csrf_token %} <div class="form-group"> {{form | crispy}} <input type="submit" value="Save" class="btn btn-primary btn-block"> </form> </div> -
How do I redirect away from the login page, if the user is already logged in and goes to login page in Django?
I'm using built in authentication system of Django 2.1. Example Case: User logs in by providing his credentials, once he is directed to the home page and presses browser's back button he'll land in the login page again. It'll again ask for the credentials but actually the user is already logged in. How do we redirect the user to the home page in this case? -
Slider in django website using bootstrap4 carousel
i want to create a carousel slider in my django website where i could easily add/remove images from my admin panel. <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% for obj in projects %} {% if forloop.first %} <div class="carousel-item active "> {% else %} <div class="carousel-item "> {% endif %} <img class="d-block w-100 h-50" class="h-50 d-inline-block" src="{{ obj.thumbnail.url}}" alt="{{obj.title}}"> </div> {% endfor %} </div> -
django_session table is not found after making migrations?
enter image description here I changed model and deleted migrations, pycache folders as well sqlite db file of the application in the project. then tried python manage.py makemigrations appname python manage.py migrate appname -
issue with rendering chart with django and chart.js
I am learning how to integrate charts in django app with chart.js as well as the rest framework from django and I am running into an issue that I have no clue how to go about. when running the server, I don't any error, simply a blank page and I cannot figure out why my chart is not displaying. Here attached my html page, view.py and urls.py because I think that the issue is somewhere in here! from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from .models import top_sellers, Classification, ClassificationSerializer,stock_anormal, stock_negatif, niveau_service from django.views.generic import View from django.http import JsonResponse class HomeView(View): def get(self, request, *args, **kwargs): return render(request, 'dashboard/base.html', {}) def get_classification(request, *args, **kwargs): labels = ["red", "blue"] data = { 'labels' : labels, 'class' : ['AA, A'], 'inventory_dollars' : [12,15]} return JsonResponse(data) {% extends 'dashboard/base.html' %} <script> {% block jquery %} var endpoint= '/class/' var defaultData = [] var labels = ["red", "blue"] $.ajax({ method: "GET", url: endpoint, sucess: function(classification){ labels = data.labels defaultData = data.defaul console.log(data) }, error: function(error_data){ console.log("error") console.log(error_data) } }) var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: '# of … -
Django - Images aren't loading in second app
I got two apps 1. main, 2. contact inside my Django project. Both use the base.html file to get the head and the footer. Inside the footer is a image which perfectly work in the main app but inside the contact app it is not shown, there is no images displayed. I tryed to change the settings but everything was set correct. I implement the static and media root STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and inside the urls.py I do urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('contact/', include('contact.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) If i open the inspector in firefox the path is the right one but the console throws a 404 GET http://localhost:8000/static/media/contact/contact_image.jpg 404 (Not Found) How couldnt it work when the media folder is in the root of the app and the settings are the same in both apps? -
Samesite error in Django app while using Datatables Cloudflare CDN file
Can someone tell me how to resolve the warning/error on my django site? A cookie associated with a cross-site resource at http://datatables.net/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. 127.0.0.1/:1 A cookie associated with a cross-site resource at http://cloudflare.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. 127.0.0.1/:1 A cookie associated with a cross-site resource at https://cloudflare.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. (index):329 Uncaught ReferenceError: $ is not defined at (index):329 Console Log -
Django merging between two querysets by adding an element from one queryset to the other every nth element
Assume I have in my model "movies" of several types: E.g.: Action, Drama, Fantasy etc... In my template I would like to list the 50 most recent movies (sorted by date). Which is rather straight forward E.g.: Movies.order_by('-date')[0:50] However, I have an additional requirement: I would like to list Action movies (sorted by date) every 3 movies of other types: E.g.: (0) Drama 12/3 (1) Adventure 11/3 (2) Science 10/3 **(3) Action 11/3** (4) Sci-Fi 9/3 (5) Sci-Fi 8/3 (6) Adventure 4/3 **(7) Action 8/3** (8) Drama . . . (50) ... In other words, merge two query sets: movies sorted by date of all movies excluding action movies. movies sorted by date of only actions movies. The new query set (or list?) should be 3 items from the first query set and 1 item from the other query set. -
Visual Studio - Error: Unable to download installation files
I'm following a nice tutorial on hosting Django on Apache, for that I need to install mod_wsgi using pip. This needs c++ 14.0 or higher .. I've been trying to install visual studio community edition and it's tools using the microsoft installer. However, a bugging error keeps chacing me: "Unable to download installation files. Check your internet connection and try again" Now my internet connection is fine, I also did many attempts to restart, and re-download - cmd commands for offline installation and many many attempts. I need help here as It is driving me crazy!:D can anybody please help? all the best -
How to access ForeignKey child model's ID? int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method
i keep getting error: Line number: 1 - int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' Im trying to access the child models id to sort by the company instance for each store. It works if i upload the data through the child model but trying to do the opposite throws errors? model.py class Parent(models.Model): store = models.IntegerField(primary_key=True) state = models.CharField(max_length=250, blank=True) # pylint: disable=R0903 def __str__(self): return '{}'.format(self.store) class Child(models.Model): id = models.BigIntegerField(primary_key=True) store = models.ForeignKey('Parent', on_delete=models.CASCADE, null=True) company = models.CharField(max_length=250, blank=True) rank = models.IntegerField(blank=True, default='') # pylint: disable=R0903 def __str__(self): return '{}'.format(self.company) admin.py class ParentResource(resources.ModelResource): state = fields.Field(attribute='state', column_name='State') store = fields.Field(attribute='store', column_name='Store') company = fields.Field(attribute='company', column_name='Company', widget=ForeignKeyWidget(Child, 'company')) class Meta: model = Parent import_id_fields = ('store', 'state',) fields = ('store', 'state', 'company',) def before_import_row(self, row, **kwargs): company = row.get('Company') store = row.get('Store') store = Parent.objects.get_or_create(store=store) rank = row.get('Rank') company = Child.objects.get_or_create(store=store[0], company=company, rank=rank, id=id) class ParentAdmin(ImportExportModelAdmin): inlines = [ChildInline] resource_class = ParentResource list_display = ['store', 'state'] class Meta: model = Parent -
Django overwrite header value in request object
I am writing middleware that, when it receives a request containing a header 'foo', modifies its value, before passing the request on. Django makes direct assignment illegal, so these do not work: request.headers['Foo'] = 'bar' request['Foo'] = 'bar' I do have a working solution, but it's a bit hacky: request.headers.__dict__['_store']['foo']=('Foo','bar') Is there a cleaner way of doing it that I've missed? -
Keep a list of users who accessed specific url in model
What I'm trying to do is every time a user visits a URL related to the object, a viewed_by field gets updated with that specific user's ID number. I've had a look at this documentation but I feel like it doesn't really fit exactly what I need. I'm not sure about the implementation, which is why I'm asking this question, but this is how I'd imagine it or something like this. class Documents(models.Model): document = models.FileField(upload_to=my_upload) document_name = models.CharField(max_length=100) document_viewed_by = ??? #ids of each user that viewed the document -
annotate with RawSQL by entry
Is it possible to get the query of the RawSQL to work with one entry at a time? I'll give an example of my problem: I have a DateRangeField in a model (it's a Postgres field) date = DateRangeField(null=True) What I'm aiming to get is the days inside the range. I tried doing the next Django ORM query models.my_model.objects.annotate(diff_days=RawSQL("""SELECT UPPER(date)-LOWER(date) FROM my_model_db_name""",[])) Which of course led to the following error (because the query FROM is the whole table) django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression and that's because RawSQL is expecting a single result (e.g. put SUM or COUNT in the SELECT expression) and that's because of the query executed by the entire table instead of the current object. Is there a way to implement it into Django ORM? The other solution is, of course, to get the executed result and then calculate it by raw. -
HOW TO REDIRECT TO ANOTHER PAGE THAT CONTAINING ID IN DJANGO
I have this function in view.py file that i pass an ID on it and it render a certain page def more_about_child(request,pk): child = get_object_or_404(Child_detail,pk=pk) academic = Academic.objects.filter(Student_name=child) context={ 'child':child, 'academic':academic, } return render(request,'functionality/more/more.html',context) And this urls.py file belongs to above views.py file from . import views from django.urls import path urlpatterns=[ #more_about_child path('more/<int:pk>/',views.more_about_child,name='more'), ] Then i have this function that i want to redirect to a page that contain an id in the above urls.py file def add_academy(request,pk): child = get_object_or_404(Child_detail, pk=pk) academic = Academic.objects.get(Student_name=child) form = AcademicForm(request.POST, instance=academic) if form.is_valid(): form.save() return redirect('more') #it fails to redirect to this url,because it contain an ID in it else: form=AcademicForm() context = { 'academic':academic, 'child':child, 'form':form, } -
remove None variable from Object filter
remove None variable from Object filter i have many variable for search with object filter Some of this variable is None how i can handle this variable from objects filter, None variable remove from object filter for example: centerLat = request.GET.get('centerLat') centerLng = request.GET.get('centerLng') typeCheck = request.GET.get('typeCheck') typeCheck2 = request.GET.get('typeCheck2') typeCheck3 = request.GET.get('typeCheck3') myfilters = myobject.objects.filter(lat=centerLat, lng=centerLng, type1=typeCheck, type2=typeCheck2) i need if variable is none dont use in objects filter -
django2.11 QuerySet.dates use kind as "week" not returns a list of all distinct year/week values
Environment: Win10 + python3.6.8 + django2.11 I have a query: models.DpoOps.objects.dates('start_time', 'week') In it's document, "week" returns a list of all **distinct** year/week values for the field. All dates will be a Monday. -- https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.query.QuerySet.dates But in my practice, if I use 'week' as kind, it's result isn't unique, it has repeated-returns. i.e. models.DpoOps.objects.dates('start_time', 'year') <QuerySet [datetime.date(2020, 1, 1)]> models.DpoOps.objects.dates('start_time', 'month') <QuerySet [datetime.date(2020, 2, 1), datetime.date(2020, 3, 1)]> models.DpoOps.objects.dates('start_time', 'day') <QuerySet [datetime.date(2020, 2, 26), datetime.date(2020, 3, 2), datetime.date(2020, 3, 3), datetime.date(2020, 3, 4), datetime.date(2020, 3, 5), datetime.date(2020, 3, 9), datetime.date(2020, 3, 16), datetime.date(2020, 3, 17), datetime.date(2020, 3, 18), datetime.date(2020, 3, 19), datetime.date(2020, 3, 29)]> models.DpoOps.objects.dates('start_time', 'week') <QuerySet [datetime.date(2020, 2, 24), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), '...(remaining elements truncated)...']> Did i misunderstand it's means? -
customize the get_payload function in django-graphql-jwt
please, how can I customise the get_payload function in django-graphql-jwt? def get_payload(token, context=None): try: payload = jwt_settings.JWT_DECODE_HANDLER(token, context) except jwt.ExpiredSignature: raise exceptions.JSONWebTokenExpired() except jwt.DecodeError: raise exceptions.JSONWebTokenError(_('Error decoding signature')) except jwt.InvalidTokenError: raise exceptions.JSONWebTokenError(_('Invalid token')) return payload