Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django PythonAnywhere (2003, "Can't connect to MySQL server (timed out)")
I'm trying to setup a Django project and I can't seem to connect to MySQL database made in PythonAnywhere. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'username$dbname', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'username.mysql.pythonanywhere-services.com', } } I cant enter the database in the PythonAnywhere Bash with my user, host, name and password, but when i try to do it in django it appears as follows: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'username.mysql.pythonanywhere-services.com' (timed out)") -
how to manage MySQL and MongoDB at the same time with django
I have an affiliate site where the data for products is arbitrary such as length of clothes and using MySQL will not be flexible and a good option there. I want something dynamic such as MongoDB. I know about "djongo" but it converts every query to Mongo. I found this How to Hybrid Mysql and MongoDB in Django and it gave me hope that I may be able to use mongo for the products and keep the rest such as Auth, User management etc in MySQL. If you know anything then please let me know. Is it even possible? Can I use PyMongo to access mongoDB database and query data easily between both databases such as using relations(i.e Foreginkey, OneToOne etc) The reason I provided none of my code is that I only want to know the concept. -
Is the implementation of my add to cart / remove from cart secure?
I am building an ecom website and in order to implement an add_to_cart function I've done the following. Clicking the add to cart button calls the javascript add_to_cart function that I wrote: <button type="button" onclick = "add_to_cart({{ product.pk }})">Add to Cart</button> This is the function: function add_to_cart(product_pk) { let url = '/add-to-cart/' + product_pk.toString() $.ajax({ type: 'GET', url: url, processData: false, contentType: false }) } the urls for this look like this: path('add-to-cart/<str:product_pk>', views.add_to_cart, name='add_to_cart') and finally my view looks like this: def add_to_cart(request, product_pk): cart = request.session['cart'] cart.append(product_pk) request.session['cart'] = cart context = {'length_of_cart': len(cart)} return HttpResponse(content = dumps(context), content_type='application/json') tldr: Click button, button calls js, js makes get request to url, url triggers view, logic in view adds product to cart. I feel like this is pretty "hacky". Are there any security issues involved with what I've done here? -
Modifiying django defaultrouter URL
So I want the URL /users/ to retrieve not a list of users but only the current user username. What I did for achieving this is adding the list method and overwriting it, like this: def list(self, request, *args, **kwargs): """ Override list method so it only returns current user username. """ data = {"username": request.user.username} return Response(data, status=status.HTTP_200_OK) But I feel like it's not the correct solution because list it's supposed to retrieve all the users. There is a way in which I could change the Django default router behaviour? So the URL /users/ executes a different method, not list(). urls.py from django.urls import include, path from rest_framework.routers import DefaultRouter from users.views import UserViewSet router = DefaultRouter() router.register(r'users', UserViewSet, basename='users') urlpatterns = [ path('', include(router.urls)) ] Or maybe doing this is just fine and I should let it be how it is right now. -
Google Cloud Storage doesn't upload to the correct media and static directory in the bucket
I have created an app in Django and want to use Google Cloud Storage to keep my statics and media files. However, when running python manage.py collectstatic It uploads all the statics to the google cloud bucket root instead of the directory "static" in the bucket. This is my core/settings/local.py from .base import * # noqa ALLOWED_HOSTS = ["*"] DEBUG = True INSTALLED_APPS += ["django_extensions", ] DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_BUCKET_NAME = "name-bucket" and here is my core/settings/base.py import os from pathlib import Path import dj_database_url from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "whitenoise.runserver_nostatic", "django.contrib.staticfiles", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] STATIC_FILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_FINDER = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media" How can I get to upload my statics to a folder called "static" in my bucket instead in the root? -
How to pull data from database in Quill format and feed to a Quill form using Django-quill-editor
I have a Quill form that works to submit the Quill data to the database. Now when I call the form, I want to take data already in that form and display it in the Quill form to the user. I tried using .setContents() like so, <script type="text/javascript">note_field.setContents({{ note_data }})</script> but it throws a Javascript error, (index):26 Uncaught SyntaxError: Unexpected token '&' I can get the object to display separately on the page, I just can't figure out how to get it back in the Quill form to edit it. Here is my form code: <!DOCTYPE html> <html> <head> {{ form.media }} <title>Note</title> </head> <body> <form action="" method="POST"> {% csrf_token %} {{ form.note_field }} </form> <script type="text/javascript">note_field.setContents({{ note_data }})</script> </body> </html> Here is my views.py from django.shortcuts import render, get_object_or_404 from django.template import loader from .forms import QuillPostForm from .models import Note def note(request, note_id): note = get_object_or_404(Note, pk=note_id) return render(request, 'notes/note.html', {'form': QuillPostForm, 'note_data': note.note_field}) My models.py from django.db import models from django_quill.fields import QuillField class Note(models.Model): note_field = QuillField() date_created = models.DateTimeField('date created') date_last_edited = models.DateTimeField('date last edited') And my forms.py from django import forms from .models import Note class QuillPostForm(forms.ModelForm): class Meta: model = Note fields = … -
How can I setup celery beat in docker?
in settings.py CELERY_TIMEZONE = 'Europe/Minsk' CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL') CELERY_RESULT_BACKEND = os.environ.get('CELERY_BROKER_URL') CELERY_BROKER_URL = redis://redis:6379 config/celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'pulling-games-to-database': { 'task': 'gamehub.tasks.pull_games', 'schedule': 604800.0, } } docker-compose.yml version: '3' services: db: build: context: ./docker/postgres dockerfile: Dockerfile env_file: - ./.env.db volumes: - ./docker/postgres/init.sql:/docker-entrypoint-initdb.d/init.sql restart: always ports: - '5432:5432' redis: image: redis ports: - '6379:6379' celery: build: . command: celery -A config worker -l info volumes: - .:/code depends_on: - db - redis celery-beat: build: . command: celery -A config beat -l info volumes: - .:/code depends_on: - db - redis app: build: context: ./ dockerfile: Dockerfile env_file: - ./.env volumes: - ./:/usr/src/app depends_on: - db - redis ports: - '8000:8000' restart: always nginx: build: context: ./docker/nginx dockerfile: Dockerfile depends_on: - app - db ports: - '80:80' When I run this by sudo docker-compose build --no-cache sudo docker-compose up I do not see any errors. As well as I do not see celery output. My task puts data to the database periodically. This data must be shown at main page. But it does not. I'm pretty sure that database is … -
Django allauth OSError: [Errno 99] Address not available
I'm trying to implement django-allauth and faced this problem. For this project I'm using Docker as well. When I click "Sign up using VK" it redirects me to http://127.0.0.1:8000/accounts/vk/login/callback/?code=...random code... with this error. After going to sign up page again and clicking the same button it successfully redirects me to profile page which means the user was created. I couldn't find any solutions using Google so hope you can help. I don't think that was because of bad configuration because I've tested similar configuration on empty django project which was not containerized and everything worked properly. Maybe it's because inside docker container there's venv installed. Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/vk/login/callback/?code=5d6083ab180253fa42&state=JDhRkbbzqV2m Django Version: 3.2.8 Python Version: 3.9.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'coreapp', 'crispy_forms', 'rest_framework', 'corsheaders', 'easy_thumbnails', 'django_cleanup', 'storages', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.vk'] Installed Middleware: ['whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/allauth/socialaccount/providers/oauth2/views.py", line 77, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/allauth/socialaccount/providers/oauth2/views.py", line 147, in dispatch return complete_social_login(request, login) File "/py/lib/python3.9/site-packages/allauth/socialaccount/helpers.py", line 151, in complete_social_login … -
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte UnicodeDecodeError
i am working with djangorestFramework and in the serializers i have an image which when i fetch it tells me that 'utf-8' error: from rest_framework import serializers from backend.models.productos import Productos from backend.models.categoria import Categoria from backend.serializers.CategoriaSerializers import Categoriaserializers class ProductosSerializers(serializers.ModelSerializer): #Categorias = Categoriaserializers() class Meta: model = Productos fields = "__all__" this on localhost:8000/products returns this: [ { "id_productos": 8, "codigo": 12, "producto": "Carro", "imagen": "http://localhost:8000/media/productos/bulgakov-mijail-el-maestro-y-margarita.jpg", "stock": 0, "precio_compra": 0.0, "precio_venta": 0.0, "venta": 0, "fecha": "2021-10-12T16:02:06.167755Z", "id_categoria": 2 } ] but in addition to that, I need to bring in the product category and I do it this way: from rest_framework import serializers from backend.models.productos import Productos from backend.models.categoria import Categoria from backend.serializers.CategoriaSerializers import Categoriaserializers class ProductosSerializers(serializers.ModelSerializer): Categorias = Categoriaserializers() class Meta: model = Productos fields = "__all__" #fields = ["id_productos","codigo","producto","imagen","stock","precio_compra","precio_venta","venta","fecha","Categorias"] def to_representation(self, obj): productos = Productos.objects.get(id_productos=obj.id_productos) categorias = Categoria.objects.get(productos=obj.id_productos) return{ 'id_producto': productos.id_productos, "codigo": productos.codigo, "producto" : productos.producto , "imagen": str(productos.imagen), "stock": productos.stock, "precio_compra" : productos.precio_compra, "precio_venta": productos.precio_venta, "venta": productos.venta, "fecha": productos.fecha, "Categorias":{ "id_categoria": categorias.id_categoria, "categoria": categorias.categoria, "fecha": categorias.fecha } } and I get this back [ { "id_producto": 8, "codigo": 12, "producto": "Carro", "imagen": "productos/bulgakov-mijail-el-maestro-y-margarita.jpg", "stock": 0, "precio_compra": 0.0, "precio_venta": 0.0, "venta": 0, "fecha": "2021-10-12T16:02:06.167755Z", "Categorias": { "id_categoria": … -
django update user form
here the problem with form, all fields are applied except for the avatar field. i can't see the reason why. forms class UserEditForm(forms.ModelForm): class Meta: model = User fields = ['username', 'name', 'email', 'bio', 'avatar'] exclude = () widgets = { 'avatar': forms.FileInput(), 'bio': forms.Textarea(), } views @login_required(login_url='login') def edit_profile(request): user = request.user form = UserEditForm(instance=user) if request.method == 'POST': form = UserEditForm(request.POST, request.FILES, instance=user) if form.is_valid(): form.save() return redirect('get_author', pk=user.id) return render(request, 'account/edit_profile.html', {'form': form}) template <form class="form-horizontal" role="form" method="POST" action=""> {% csrf_token %} <div class="col-md-3"> <div class="text-center"> <img src="{{ request.user.avatar.url }}" class="avatar img-circle" alt="avatar" style="width: 100px; height: 100px;"> <h6>Upload a different photo...</h6> {{ form.avatar }} </div> </div> ... other fields thanks for ur help -
How to use multiprocessing in Python with Django to create thousands of model instances from xml file?
I have a script that parses data from an xml file into Django models. It works ok but recently we've been encountering files with dozen of thousands of models to create which is incredibly slowing down the process (up to 40 min to upload a single 20MB file). I would like to try and use multiprocessing to speed it up as much as I can but I am new to this package. This is the current setup: create_profiles_from_xml: is a function that loops through the data extracted from the xml, called xml_members, popping one element at a time (it has to be like that due to a relationship that can be created with the next element or not). create_profile: is a just a function that handles the data to match with the model fields and then call the .create() method, that's why I omitted the details of this function here. def create_profiles_from_xml(xml_members, device): profiles = [] while len(xml_members) > 0: parent_member = members.pop(0) profile = create_profile(parent_member, parent=None) if profile: profiles.append(profile) return profiles And here is what I tried to do with the multipocessing from multiprocessing import Pool def create_profiles_from_xml(xml_members, device): profiles = [] pool = Pool(processes=cpu_count()) profiles = pool.imap_unordered(create_profile, xml_members) … -
How to access values from a form powered by typeform in python
I'm trying to use Typeform in my Python/Django website, and I wanted to know if there is a way to access the data from the form and do something with it. -
TypeError at /pet/3/ petAPI() got an unexpected keyword argument 'pk' Django
I am a newbie to Django and its REST Framework, I am trying to design an API that allows me to perform the basic operations of the CRUD, both the GET, POSt and PUT methods work correctly, however when I try to implement the DELETE method I get a very particular error: This is my main urls.py file: from django.conf.urls import url from django.urls import path from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView) from pethomeApp import views urlpatterns = [ path('login/', TokenObtainPairView.as_view()), path('refresh/', TokenRefreshView.as_view()), path('user/', views.UserCreateView.as_view()), path('pet/', views.petView.petAPI), path('pet/<int:pk>/', views.petView.petAPI), ] This is my petViwe.py file: from rest_framework import status, views from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from pethomeApp.models import Pet from pethomeApp.serializers import PetSerializer # Create your views here. @csrf_exempt def petAPI(request, id=0): if request.method == 'GET': if id == 0: pets = Pet.objects.all() serializer = PetSerializer(pets, many=True) return JsonResponse(serializer.data, safe=False) else: pet = Pet.objects.get(id=id) serializer = PetSerializer(pet) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = PetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse("Added successfuly", safe=False) return JsonResponse("Failed to add", safe=False) elif request.method == 'PUT': data = JSONParser().parse(request) pet = Pet.objects.get(id_pet=data['id_pet']) serializer = PetSerializer(pet, data=data) if serializer.is_valid(): serializer.save() … -
How to send a reset password email in Django on User creation?
I want to be able to let an admin create user accounts and then, instead of setting up a password for the user, the user would automatically receive a reset password email. The view for the user creation, which also includes a Member model, is the following: def newmember(request): if request.method == 'POST': nu_form = NewUser(request.POST) nm_form = NewMember(request.POST) if nu_form.is_valid() and nm_form.is_valid(): nusave = nu_form.save() nmsave = nm_form.save(commit = False) nmsave.user = nusave nmsave.save() return redirect(members) else: print(nu_form.errors) print(nm_form.errors) else: nu_form = NewUser() nm_form = NewMember() context = { 'nu_form': nu_form, 'nm_form': nm_form} return render(request, 'web/newmember.html', context) How can I make so that upon creation of a new user, Django automatically sends an email to that new user requestion a password reset? -
overriding Django change_list_results
I am customizing my admin panel a little and want to add an additional column to it, so as per the docs I have to override the change_form_results.html file but how do I do it? all I see is this code in it <tbody> {% for result in results %} {% if result.form and result.form.non_field_errors %} <tr><td colspan="{{ result|length }}">{{ result.form.non_field_errors }}</td> </tr> {% endif %} <tr>{% for item in result %} {{ item }} {% endfor %}</tr> {% endfor %} </tbody> what change am i suppose to make to above code -
Django postgres raise notice
Let's say that I have a postgres function that raise multiple notices. Example: function testnotice ... raise notice 'test' raise notice 'test-2' When I execute this function from django, cursor.execute("select testnotice()") Is there any posibility to retrive the notifications ? I tried the answer from: Python2 print postgresql stored procedure raise notice But I get AttributeError: 'DatabaseWrapper' object has no attribute 'notices' on Python 2.7 Any helpful ideas ? Thank you. -
Set unique primary key based on foreignkey
I have a model defined as - class sales_order(models.Model): customer=models.ForeignKey() item=models.ForeignKey() branch=models.ForeignKey() --- ---other fields Now for each branch, I want to start the primary key from 1 ("id" for eg.), but the default functionality of Django will increment the id irrespective of any other data. I'm ok even if id keeps on incrementing as it does, and then I set my own field making it unique per branch and this field should auto increment without the user passing the data by checking the previous value from the database such as - class order_serializer(serializers.ModelSerializer): class Meta: validators = [ UniqueTogetherValidator( queryset=sales_order.objects.all(), fields=['myOwnDefinedField', 'branch'] ) ] I'm in a state of no idea how to achieve this. Using Django 3.1.5. Any help? -
How to change ImageField into FileField in Django?
I have a ImageField in one of the models, is there any way to change that field into FileFiled? If converted how can one identify image during upload? What is the difference between ImageField and FileField in django? -
Django : passing parameter or context with the function redirect and id encoded by hashids
I am a newbie and I need your help ! But maybe it's a complicated question even for experts, who knows! The following code works perfectly to generate a table (using a datepicker form to select the table's day) from the homepage, and with the ID page encoded with hashids in the URL, it redirects to the table URL generated for the day selected. For example, when a specific table is created for a particular day selected by the user, the page is redirected to http://127.0.0.1:8000/O3GWpmbk5ezJn4KR where "O3GWpmbk5ezJn4KR" is one table id encoded with hashids, this works fine. However, I would like to pass a variable with redirect(), the day selected in the datepicker used to create the table, in order to display the date on the html page rendered with the table generated. I tried the reverse function to pass the day variable with redirect, but if failed due to the hashid encoded URL not being recognized by the reverse function (example of error message obtained in the Shell : django.urls.exceptions.NoReverseMatch: Reverse for '/VvJ4openRe7Az1XP' not found. '/VvJ4openRe7Az1XP' is not a valid view function or pattern name.) Have you any idea to help ? Would appreciate any hint ! Best … -
Why getting "This site can’t be reached" when trying to deploy django appplication on heroku?
I am learning how to deploy django application to heroku and to do so,i have completed the following steps:- 1 cloned a git repo which i want to host 2 Install Heroku CLI 3 Run command --> heroku login 4 heroku create <my_app_name> 5 Add to remote --> heroku git:remote -a <my_app_name> Now to push to heroku we need to test it locally,so i installed waitress 6 waitress installed 7 Run waitress using following command waitress-serve -port=8000 <path_to_wsgi.py file>:application Upto this point i have't get any error,waitress starts running:- PS C:\Users\akcai\OneDrive\Desktop\heruko\polling_application> waitress-serve --port=8000 EVCFinder.wsgi:application INFO:waitress:Serving on http://0.0.0.0:8000 urls.py in django application:- urlpatterns = [ path('/admin/', admin.site.urls), path('signup/', user_registration, name="sign_up"), path('login/', user_login, name='login'), path('logout/', user_logout, name='logout'), also in setting.py i have added allowed host as follow:- ALLOWED_HOSTS = ["*"] when i tried to access urls http://0.0.0.0:8000 OR http://0.0.0.0:8000/admin/ got following error:- This site can’t be reached The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID Thanks in advance, Any help will be highly appreciated Hope to here from you soon. -
Django: Making python script run on button click and display output on html page
I have been working on making a python script that will run by clicking a button and then displaying the output in the Django html page. so far I have managed to make a button that will run the script but I am not able to display any results below is the code I have used, it runs the python script in shell but goes no further. In my Views.py def Yellow(request): inp = request.POST.get('param') out = run(['python', '/yellow_page_updated.py', inp], stderr=subprocess.DEVNULL) print(out.stderr) print("Finished!!") return render('Yellow_Page.html', {'data1': out}) In my Urls.py url(r'^Yellow', views.Yellow, name="Yellow") if anybody can help or point me in the right direction i would be very grateful. Thanks for taking a look -
RestAPI unable to download a file sent from Django API to sveltekit client - Fatal error reading a PNG image file
I have a Django Get APIView which returns a FileResponse with a png image data. When it is downloaded on the sveltekit client side then its not being read. It complains that it is not a png file. Not sure what is wrong. Here is the server code: from django.http import FileResponse, HttpResponse import mimetypes # from django.core.files import File mime_type, _ = mimetypes.guess_type('qrcode.png') response = HttpResponse(open('qrcode.png', 'rb'), content_type=mime_type) # response = FileResponse(open('qrcode.png', 'rb'), content_type=mime_type) # response = HttpResponse(open('qrcode.png', 'rb')) # response = HttpResponse(open('qrcode.png', 'rb'), content_type='application/png') # response = HttpResponse(FileWrapper(img), content_type='application/png') response['Content-Disposition'] = 'attachment; filename=qrcode.png' return response I have commented all the possibilities that I tried. Now here is the client side code: if (res.status == 200){ qrimage = await res.data; console.log(typeof(qrimage)); // const blob = new Blob(qrimage); // let url = window.URL.createObjectURL(blob); // let url = window.URL.createObjectURL(qrimage); let a = document.createElement("a"); // console.log(url); a.href = 'data:image/png;'+qrimage; a.target = '_blank'; a.download = 'qrcode.png'; a.click(); // }); } Thank you for help and comments. -
Django - Endpoint JSON empty
When I test my Endpoint i get the right amount of json packages but they are all empty. in the database the entries are correct. When i enter somethin like : /flush/?devid=2&startdate=11/10/21&enddate=29/10/21&resolution=1 i get a json with two elements but both are empty. where did I fail? i created a model: from django.db import models class Flush(models.Model): id = models.AutoField(db_column = 'ID', primary_key = True) devid = models.IntegerField(db_column = 'DEVICE ID',default = 0) time = models.DateTimeField() temp = models.IntegerField() status = models.IntegerField() class Meta: db_table = 'SpuKas' created a view: class FlushView( APIView, ): def get(self,request): devId = int(request.GET.get('devid', '1')) startDate = datetime.strptime(request.GET.get('startdate', '01/01/00'), '%d/%m/%y') endDate = datetime.strptime(request.GET.get('enddate', '01/01/00'), '%d/%m/%y') resolution = int(request.GET.get('resolution', '1')) queryset = Flush.objects.filter(devid=devId, time__range=(startDate, endDate + timedelta(days=1)))[0:1844674407> readSerializer = FlushSerializer(queryset, many = True) return Response(readSerializer.data) and serialized it in the serializers.py: from .models import Flush class FlushSerializer(serializers.Serializer): class Meta: model = Flush fields = '__all__' -
TypeError: decode() got an unexpected keyword argument 'verify' djangorestframework simple jwt
I'm using djoser for authentication and I'm getting TypeError: decode() got an unexpected keyword argument 'verify'. The /jwt/create/ endpoint is working and returning the access and refresh tokens but I can't verify or get the user's details (/auth/users/me/). The same code works in my previous project. Any idea what could be causing the error? {Traceback (most recent call last): File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 414, in initial self.perform_authentication(request) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 324, in perform_authentication request.user File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\request.py", line 227, in user self._authenticate() File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\request.py", line 380, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\authentication.py", line 40, in authenticate validated_token = self.get_validated_token(raw_token) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\authentication.py", line 94, in get_validated_token return AuthToken(raw_token) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\tokens.py", line 43, in init self.payload = token_backend.decode(token, verify=verify) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\backends.py", line 90, in decode return jwt.decode( TypeError: decode() got an … -
Creating months based on start date and end date value in django
I have been working on an application where user is required to create monthly tasks, so I made a model named AcademicYear and Months, now I want to take only the start_month and end_month input from user, and based upon the values of these fields, I want to create months automatically once the year object is create. class AcademicYear(SingleActiveModel, models.Model): title = models.CharField(max_length=10) start_month = models.DateField() end_month = models.DateField() def __str__(self): return str(self.title) class Months(models.Model): year = models.ForeignKey(AcademicYear, on_delete = models.PROTECT, related_name='year') months = models.CharField(max_length = 20) ??? what could be the logic or a solution which can be applied here?