Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Value Error: Field 'id' expected a number but got 'create'
I was in the process of making a create gallery image field in Django for my project, but when I try to access the url, I'm getting a Field 'id' expected a number but got 'create'. error. And on postman, I'm getting a { detail: "Method \"POST\" not allowed." }. class Gallery(models.Model): SUBTLEPBR = "subtle" AMULET = "amulet" F8THFULPBR = "f8thfulpbr" user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) screenshot_by = models.CharField(max_length=200, null=False, blank=False) image = WEBPField( verbose_name=('Image'), upload_to=image_folder, default="placeholder.png" ) PACKS = [ (SUBTLEPBR, 'SubtlePBR'), (AMULET, 'Amulet'), (F8THFULPBR, 'F8thfulPBR'), ] pack = models.CharField(max_length=10, choices=PACKS) def __str__(self): return "Screenshot by "+ self.screenshot_by + " | " + self.pack @api_view(["POST"]) @permission_classes([IsAdminUser]) def createGalleryImage(request): user = request.user gallery = Gallery.objects.create( user = user, screenshot_by = "John Doe", pack = Gallery.SUBTLEPBR, ) serializer = GallerySerializer(gallery, many=False) return Response(serializer.data) path("gallery/create/", views.createGalleryImage, name="gallery-create"), The output that is supposed to happen is { "id": 51, "screenshot_by": "Person", "image": "/placeholder.png", "pack": "subtle", "user": 1 } -
smtplib.SMTPConnectError: (421, b'Service not available') event after 2-step verification and used generated app password as the HOST_USER_PASSWORD
I am trying to incorporate email confirmation to user registration in my project. The user is supposed to get a confirmation link in their email before successful registration. To achieve this, I used django.core.mail.backends.smtp.EmailBackend as the email backend but I got the error below: Internal Server Error: /account/register/ Traceback (most recent call last): File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\handlers\base.py", line 197, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\lenovo\Desktop\ecommerce4\account\views.py", line 88, in account_register user.email_user(subject=subject, message=message) File "C:\Users\lenovo\Desktop\ecommerce4\account\models.py", line 59, in email_user send_mail( File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail_init.py", line 87, in send_mail return mail.send() File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail\message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail\backends\smtp.py", line 124, in send_messages new_conn_created = self.open() File "C:\Users\lenovo.virtualenvs\ecommerce4-MU6fbcf2\lib\site-packages\django\core\mail\backends\smtp.py", line 80, in open self.connection = self.connection_class( File "C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 258, in init raise SMTPConnectError(code, msg) smtplib.SMTPConnectError: (421, b'Service not available') I allowed two step authentication to my gmail account and then created app password. I used the app password generated for my account as the HOST_USER_PASSWORD Below is the code how I configured the the setings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_HOST_USER='my gmail' EMAIL_HOST_PASSWORD='the generated app password' EMAIL_PORT=587 EMAIL_USE_TLS=True Below is the model.py for user import uuid from django.conf import settings from django.contrib.auth.models import (AbstractBaseUser, … -
How to pass the dictionary from redirect in django in python using POST method?
I am trying to redirect to a new html page in my django app from view and I also want to pass a dictionary by POST method . For this I have written the code as - return redirect('/fun_generated/',{'val0':val0}) But when I am trying to access the dictionary from the function as - def fun_generated(request): By using request.POST.get('val0') it is showing none. I have tried the kwargs as - doc = {'val0':val0} return redirect('/fun_generated',kwargs={'val0':val0}) and then access in the function as - def fun_generated(request, **kwargs): It is still not working I have also tried to use the url method as - encoded_string=urllib.parse.urlencode(doc) return redirect(f'/fun_generated?%s'%encoded_string) but this is using the GET method also when I am trying to access by using this GET method as - request.GET.get('reason_data') It is giving the data as ['vaue']. I don't know where these [] come from and how can I pass using POST method? -
Django Password Reset Error: The URL path must contain 'uidb64' and 'token' parameters
I was trying to implement password reset with email in django. These are my views: class UserPasswordResetView(PasswordResetView): template_name = "accounts/password_reset_form.html" email_template_name = "accounts/password_reset_email.html" success_url = reverse_lazy("accounts:password_reset_done") class UserPasswordResetDoneView(PasswordResetDoneView): template_name = "accounts/password_reset_done.html" class UserPasswordResetConfirmView(PasswordResetConfirmView): template_name = "accounts/password_reset_confirm.html" success_url = reverse_lazy("accounts:password_reset_complete") class UserPasswordResetCompleteView(PasswordResetCompleteView): template_name = "accounts/password_reset_complete.html" urls.py: path("reset/", UserPasswordResetView.as_view(), name="password_reset"), path( "reset/done/", UserPasswordResetDoneView.as_view(), name="password_reset_done" ), path( "confirm/<uidb64>/<token>/", UserPasswordResetConfirmView.as_view(), name="password_reset_confirm", ), path( "confirm/complete/", UserPasswordResetConfirmView.as_view(), name="password_reset_complete", ), Everything goes well to password confirm phase. But after I submit the form, instead of showing the password_reset_complete.html, it shows this error: ImproperlyConfigured at /accounts/confirm/complete/ The URL path must contain 'uidb64' and 'token' parameters. It says it's missing those parameters in password_reset_complete url. So I tried adding them to the url: path( "confirm/complete/<uidb64>/<token>/", UserPasswordResetConfirmView.as_view(), name="password_reset_complete", ), And it shows this new error: NoReverseMatch at /accounts/confirm/MQ/set-password/ Reverse for 'password_reset_complete' with no arguments not found. 1 pattern(s) tried: ['accounts/confirm/complete/(?P<uidb64>[^/]+)/(?P<token>[^/]+)/\\Z'] Despite raising these errors, password is actually reset. The only problem is with displaying password reset complete template. -
django orm: use annotate case on prefetch result
this is a near replica of my models: class To(models.Model): pass class FromA(models.Model): to = models.ForeignKey(To) class FromB(models.Model): to = models.ForeignKey(To) is there a way to write a query like this? To.objects.annotate(from=Case( When(froma__isnull=False, then=Prefetch("froma")), When(fromb__isnull=False, then=Prefetch("fromb")) )) -
how do convert a django template variable into a javascript file
hi i created a django cart funcrion i need to create a java script function when i checkout from my page my cart should be empty when i post my checkout data has been saved but my boolean variable which is defined into a view function it not accessable into java script code **checkout.html ** <script> if (localStorage.getItem('cart') == null) { var cart = {}; } else { cart = JSON.parse(localStorage.getItem('cart')); }; $('#itemsJson').val(JSON.stringify(cart)); {% if thank %} alert("Thanks for ordering with us. Your order id is {{id}}. Use it to track your order using our order tracker") localStorage.clear(); document.location="/shop"; {%endif%} </script> there thank is a variable i need when form is submit my cart should be local storage.clear() view.py def checkout(request): thank=False if request.method=="POST": items_json= request.POST.get('itemsJson', '') name=request.POST.get('name', '') email=request.POST.get('email', '') address=request.POST.get('address1', '') + " " + request.POST.get('address2', '') city=request.POST.get('city', '') state=request.POST.get('state', '') zip_code=request.POST.get('zip_code', '') phone=request.POST.get('phone', '') order = Order(items_json= items_json, name=name, email=email, address= address, city=city, state=state, zip_code=zip_code, phone=phone) print(order) order.save() update=OrderUpdate(order_id=order.order_id,update_desc='Your Order Has Been Placed') update.save() thank=True id=order.order_id return render(request, 'myproj/checkout.html', {'thank':thank, 'id':id}) return render(request, 'myproj/checkout.html') -
invalid literal for int() with base 10: b'10 00:00:00' Request Method:get
I was trying to do get request to the url http://127.0.0.1:8000/books/list/ but im now facing an erorr invalid literal for int() with base 10` #my views.py from django.shortcuts import render from book_api.models import Book from django.http import JsonResponse from book_api.serializer import BookSerializer from rest_framework.response import Response from rest_framework.decorators import api_view # Create your views here. @api_view(['GET']) def book_list(request): books=Book.objects.all() serializer=BookSerializer(books,many=True) return Response(serializer.data) @api_view(['POST']) def book_create(request): serializer=BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) #my serializer.py from rest_framework import serializers from book_api.models import Book class BookSerializer(serializers.Serializer): id=serializers.IntegerField(read_only=True) title=serializers.CharField() number_of_pages=serializers.IntegerField() publish_date=serializers.DateField() quantity=serializers.IntegerField() def create(self,data): return Book.objects.create(**data) #book_api.urls from django.contrib import admin from django.urls import path from book_api.views import book_list,book_create urlpatterns = [ path('',book_create), path('list/',book_list) # book/urls.py """BOOK URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include … -
Forbidden. You don't have permission to access this resource. (Django Apache2)
I am trying to deploy my Django project through Ubuntu Apache2 but I am getting Forbidden You don't have permission to access this resource error. I cannot seem to find the solution Error: Server Error My config file `Alias /static /home/rapicare/rapid-care-website/rapidCare/static <Directory /home/rapicare/rapid-care-website/rapidCare/static> Require all granted Alias /media /home/rapicare/rapid-care-website/rapidCare/media <Directory /home/rapicare/rapid-care-website/rapidCare/media> Require all granted </Directory> <Directory /home/rapicare/rapid-care-website/rapidCare/rapidCare> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django_app python-path=/home/rapicare/rapid-care-website/rapidCare python-home=/home/rapicare/rapid-care-website/venv WSGIProcessGroup django_app WSGIScriptAlias / /home/rapicare/rapid-care-website/rapidCare/rapidCare/wsgi.py` My Directoy permissions rapidcare@rapidcare:~$ ls rapid-care-website -la total 28 drwxrwxr-x 5 rapidcare www-data 4096 Feb 5 09:11 . drwxr-x--x 5 rapidcare rapidcare 4096 Feb 5 16:48 .. -rw-rw-r-- 1 rapidcare rapidcare 0 Feb 4 11:52 .editorconfig drwxrwxr-x 8 rapidcare rapidcare 4096 Feb 5 09:14 .git -rw-rw-r-- 1 rapidcare rapidcare 651 Feb 4 11:52 .gitignore drwxrwxr-x 7 rapidcare www-data 4096 Feb 4 22:12 rapidCare -rw-rw-r-- 1 rapidcare rapidcare 249 Feb 4 11:52 requirements.txt drwxrwxr-x 5 rapidcare www-data 4096 Feb 4 22:12 venv rapidcare@rapidcare:~/rapid-care-website$ ls -la rapidCare/ total 388 drwxrwxr-x 7 rapidcare www-data 4096 Feb 4 22:12 . drwxrwxr-x 5 rapidcare www-data 4096 Feb 5 09:11 .. -rw-rw-r-- 1 rapidcare www-data 360448 Feb 4 12:55 db.sqlite3 -rwxrwxr-x 1 rapidcare rapidcare 665 Feb 4 11:52 manage.py drwxrwxr-x 3 rapidcare www-data … -
How to filter with rest api django?
I have this model: class Item(models.Model): category = models.CharField(max_length=255) subcategory = models.CharField(max_length=255) name = models.CharField(max_length=255) amount = models.PositiveIntegerField() def __str__(self) -> str: return self.name serializer: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('category', 'subcategory', 'name', 'amount') views.py: @api_view(['GET']) def view_items(request): queryset = Item.objects.all() serializer = ItemSerializer(queryset, many=True) # checking for the parameters from the URL if request.query_params: items = Item.objects.filter(**request.query_params.dict()) else: items = queryset # if there is something in items else raise error if items: return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) @api_view(['GET']) def ApiOverview(request): api_urls = { 'all_items': '/', 'Search by Category': '/?category=category_name', 'Search by Subcategory': '/?subcategory=subcategory_name', } return Response(api_urls) urls.py: urlpatterns = [ path('', CategoryViewSet.ApiOverview, name='home'), path('all/', views.view_items, name='view_items'), ] So if I go to: http://127.0.0.1:8000/djangoadmin/all/ [ { "category": "food", "subcategory": "vegetaries", "name": "potato", "amount": 4 }, { "category": "food", "subcategory": "vegetaries", "name": "ananas", "amount": 5 }, { "category": "food", "subcategory": "fruit", "name": "apple", "amount": 3 } ] So that works. But now I want to return where subcategory=vegetaries. So I try like: http://127.0.0.1:8000/djangoadmin/all/?subcategory=vegetaries But then it returns all items: [ { "category": "food", "subcategory": "vegetaries", "name": "potato", "amount": 4 }, { "category": "food", "subcategory": "vegetaries", "name": "ananas", "amount": 5 }, { "category": "food", "subcategory": "fruit", "name": … -
SMTPServerDisconnected when sending email from a Django App on Heroku with Mailgun
I'm attempting to send email from a very simple Django app. The app is hosted on Heroku, and I have the Mailgun add-on installed. However, whenever I attempt to actually send an email using Mailgun, I get a SMTPServerDisconnected error, with the message Connection unexpectedly closed. I've gone through almost every tutorial that I can find on the subject, and have still had no luck. My settings.py is exactly as described in the Heroku Mailgun documentation: EMAIL_USE_TLS = True EMAIL_HOST = os.environ.get('MAILGUN_SMTP_SERVER') EMAIL_PORT = os.environ.get('MAILGUN_SMTP_PORT', '') EMAIL_HOST_USER = os.environ.get('MAILGUN_SMTP_LOGIN', '') EMAIL_HOST_PASSWORD = os.environ.get('MAILGUN_SMTP_PASSWORD', '') The os environment variables referenced are managed by Heroku. When I've searched for similar problems, every other question has been using Port 465, however, my port is on 587, which shouldn't have this issue as far as I know. Currently, I'm using the sandbox domain provided by Mailgun just to attempt to send a test email to a verified recipient email. The following code is used in my views.py to actually send the email, using the django django.core.mail.send_mail() function. subject = "Thank you for RSVP-ing!" message = f'Hello World!' email_from = "mailgun@blannholley.com" recipient_list = [request.POST.get('email'), ] send_mail(subject, message, email_from, recipient_list, fail_silently=False) Any help would be greatly … -
How to passing a value from one Django view to another view?
Good day! I have a value - obtained after saving a Django form. After saving the form - I redirect the Django application to another view. Along with redirecting to another view, I want to pass the value that was in the previous view. How can this be done - passing a value from one Django view to another view? I'm trying to do this one by one, but I'm getting an error. If you have the opportunity, I would be grateful for any information or help. view_1 def form_1(request): context = {} form_2 = Form_new_form1_1(request.POST or None) if form_2.is_valid(): model_instance = form_2.save(commit=False) values_name = model_instance.name nm_kot = values_name request.session['nm_kot'] = nm_kot return redirect("form_1_2") context['form_2'] = form_2 return render(request, "form_1.html", context) view_2 def form_1_2(request): context = {} nm_kot = request.session['nm_kot'] nomer = nm_kot name = nomer return redirect("tabl_1") error response = self.process_response(request, response) raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Model_Model is not JSON serializable [05/Feb/2023 18:00:20] "POST /zamer_form_1 HTTP/1.1" 500 114735 -
Django cannot embed a Youtube url in a frame
I am trying to embed a youtube URL into a frame in a Django template. Each time I receive the same message in the console: Refused to display 'https://www.youtube.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'. I have tried inserting two decorators before the view: @frame_deny_exempt @xframe_options_exempt No effect. In a final test I inserted this statement into settings.py just to see if it would turn off the xframe check: X_FRAME_OPTIONS = 'ALLOWALL' The same error appears. I also tried removing the XFrameOptions middleware, no change. This is in a local testing environment so I am using the Django web server, my production server (which I have not tried moving this to for obvious reasons) is an Azure instance running NGINX -
How to download in db zip file in existing view in django?
I want to add download button in existing view. For example, I have a list board of fruits, and when I click on them one by one, I move to the detail page, such as the apple page, the strawberry page, and the grape page. I want to create a download button for each detail page, and when I press the download button, I want the user to download the apple.zip, drawberry.zip, and shape.zip files in database. But I don't know how to do this in a view that's already been created. My current view is as follows: class FruitsDetailView(LoginRequiredMixin, DetailView): template_name = 'fruits/detail.html' login_url = 'login' model = Fruits def get_context_data(self, **kwargs): pk = self.object.pk context = super().get_context_data(**kwargs) ... ... context['list'] = json.dumps(trace) return context I'm only exporting the context in this way, can I add a response related to the download here? In the case of all the articles I looked for, I was creating a separate View exclusively for download. But that's not the way I want it to be. I'm a beginner at django, so I don't know where to start. I'd appreciate if you give me a hint. -
Heroku Deployment Failed: OSError: libtorch_hip.so: cannot open shared object file: No such file or directory
Any ideas on why my app won't deploy? Build is succeeding -- deploy is failing. Here are my requirements.txt. -f https://download.pytorch.org/whl/torch_stable.html Django==4.1.4 djangorestframework==3.14.0 requests==2.28.1 whisper==1.0 django-cors-headers==3.13.0 psycopg2==2.9.5 gunicorn==20.1.0 dj-database-url>=1.0,<2.0 whitenoise>=6.0,<7.0 torch==1.13.1+cpu speechbrain pyannote.audio pyannote.core I'm using torch==1.13.1+cpu because torch==1.13.1 causes the compressed slug size on Heroku to be >500MB, which isn't allowed. Full stack trace below: /app/.heroku/python/lib/python3.8/site-packages/torchaudio/_internal/module_utils.py:99: UserWarning: Failed to import soundfile. 'soundfile' backend is not available. warnings.warn("Failed to import soundfile. 'soundfile' backend is not available.") Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 97, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/app/.heroku/python/lib/python3.8/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) … -
how to get relationship with one-to-many on same table?
I am using django and rest api. And I have two models: class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) images = models.ImageField(upload_to="photos/categories") category = models.ForeignKey("Category", on_delete=models.CASCADE, related_name='part_of', blank=True, null=True) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) description = models.TextField(max_length=1000, blank=True) legislation = models.TextField(max_length=1000, blank=True) review = models.TextField(max_length= 000, blank=True) eaza = models.TextField(max_length=1000, blank=True) class Meta: verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.name class Animal(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) images = models.ImageField(upload_to="photos/categories") category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='animals') date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) description = models.TextField(max_length=1000, blank=True) legislation = models.TextField(max_length=1000, blank=True) review = models.TextField(max_length=1000, blank=True) eaza = models.TextField(max_length=1000, blank=True) class Meta: verbose_name = "animal" verbose_name_plural = "animals" def __str__(self): return self.name And my serializer looks: class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ['id','name', 'description'] class CategorySerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True) class Meta: model = Category fields = ['id','category_id','name', 'description', 'animals'] and views.py: class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() @action(methods=['get'], detail=False) def mainGroups(self,request): mainGroups = Category.objects.filter(category_id__isnull=True) serializer = self.get_serializer(mainGroups, many=True) return Response(serializer.data) and urls.py: router = routers.DefaultRouter() router.register('groups', CategoryViewSet) urlpatterns = [ path('', include(router.urls)) ] So if I go to: http://127.0.0.1:8000/djangoadmin/groups/ I get as output: [ { "id": 11, "category_id": null, "name": "zoogdieren", "description": … -
Django block content
I am trying out block content in my django project but when i type in my code in a html file like so <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="a"> {% block content %} {% endblock %} </div> </body> </html> {% block content %} {% endblock %} these two codes won't work and they don't turn yellow as they should. could somebody help me? -
How can I Automatically post my django website blog on my fb page
I have a django blog website whenever I post a blog I want my blog to be posted on my fb page automatically how can I do that? Can Anyone help? Post my django website blog on my fb page automatically. -
Is it good practice to evoke object and re-assign value in Python/Django?
views.py from rest_framework import views from rest_framework.response import Response from .models import Category from .services.get_categories import cached_categories from .serializers import CategorySerializer class CategoryTreeList(views.APIView): def get(self, request, format=None): queryset = Category.objects.all() cached_categories(queryset) serializer = CategorySerializer(cached_categories.get_cached_root_nodes(), many=True) return Response(serializer.data) serializers.py from .models import Category from rest_framework import serializers from .services.get_categories import cached_categories class CategorySerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Category fields = ('id', 'name', 'children', ) def get_children(self, obj): children = cached_categories.get_children(obj) if children: return CategorySerializer(children, many=True).data else: return [] get_categories.py from ..models import Category class CachedCategories: def __init__(self): self.queryset = None def __call__(self, queryset): self.queryset = queryset def split_on_dicts(self): objects_by_depth = {} for i in [obj.depth for obj in self.queryset]: objects_by_depth.update({f"{i}": [obj for obj in self.queryset if obj.depth == i]}) return objects_by_depth def get_children(self, parent: Category): categories = self.split_on_dicts().get(f"{parent.depth + 1}") children = [] if categories: for obj in categories: if obj.path.startswith(parent.path) and \ obj.depth == parent.depth + 1: children.append(obj) return children def get_cached_root_nodes(self): return self.split_on_dicts().get("1") cached_categories = CachedCategories() Explaining what I want. I built django app with nested categories. And I wanted to pass categories to serializator with just one query. So I did it. Then, I understood that my class CachedCategories (in get_categories.py) works only once, when … -
I am saving EmailDb filed username and userpassword to another Emails models but it is saving null data in Emails db with refresh django
Null value or empty value saved with each refresh, even click button submit duplicate value, please find the following models and views file. please look at envlope button in the image that is submit button which create another model db called Emails. fdisply.html {% for i in obj %} <tr> {% if i.id %} <th scope="row">{{forloop.counter0|add:obj.start_index}}</th> <td>{{i.institution}}</td> <td>{{i.fullname}}</td> <td>{{i.email}}</td> <td>{{i.contact}}</td> <td>{{i.position}}</td> <td><img src={{i.uploaddata.url}} class="img-fluid img-thumbnail" alt={{i.fullname}} style="width:100px; height: 60px"></td> <td> <a href="{% url 'update' i.id %}" class="btn btn-warning btn-sm"><i class="fa-regular fa-pen-to-square"></i></a> <form action="{% url 'delete' i.id %}" method="POST" class="d-inline"> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm"> <i class="fa-regular fa-trash-can"></i> </button> </form> <!-- sent data --> <form method="POST" class="d-inline"> {% csrf_token %} <div class="d-none"> <input type="text" name="email" id="email" class="form-control w-50 form-row" value="{{i.useremail}}" required> <input type="text" name="password" id="password" class="form-control w-50 form-row mt-1" value="{{i.userpassword}}" required> </div> <button type="submit" class="btn btn-danger btn-sm"> <i class="fa-solid fa-envelope-circle-check"></i> </button> </form> </td> </tr> {% endif %} {% endfor %} models.py class EmailDb(models.Model): institution = models.CharField(max_length=300, blank=True, null=True) fullname = models.CharField(max_length=50, blank=True, null=True) contact = models.IntegerField() email = models.CharField(max_length=300, blank=True, null=True) position = models.CharField(max_length=100, blank=True, null=True) uploaddata = models.FileField(upload_to='appointment_letter') useremail = models.CharField(max_length=100, blank=True, null=True) userpassword = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.fullname class EmailS(models.Model): ename = models.CharField(max_length=100, … -
Assertion error upon using customuser model with allauth
I tried building a custom user model while using django allauth, and while trying to makemigrations for the model, I was getting an error saying that their is no username field in my model, upon doing what I could find on that problem here, I'm getting this error:- Traceback (most recent call last): File "/project-sirji/manage.py", line 23, in <module> main() File "/project-sirji/manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/usr/local/lib/python3.11/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/usr/local/lib/python3.11/site-packages/allauth/account/models.py", line 9, in <module> from . import app_settings, signals File "/usr/local/lib/python3.11/site-packages/allauth/account/app_settings.py", line 373, in <module> app_settings = AppSettings("ACCOUNT_") ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/allauth/account/app_settings.py", line 21, in __init__ not self.AUTHENTICATION_METHOD == self.AuthenticationMethod.EMAIL ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AssertionError Here's my models.py file:- from django.db import models from … -
PageSpeed speed index slow on practically empty React app
I am using Django on the backend and running React on the frontend inside Django app. I have created very basic frontend with loading animation until React loads in and few components with navigation and heading. That's basically it. I wanted to have a very basic starting point and test it for page speed so I deployed the project to railway and tested it out. But even after fixing all the problems that PageSpeed Insight suggested I can't get the mobile version above 88. Under the network tab I can see that main.js is by far the biggest content download but at the same time 324kB doesn't seem like too much. I don't know what else to improve anymore as it's such a basic app. What is causing the main.js to be downloaded so slowly? -
Dj-rest-auth set HTTP-only JWT cookies [closed]
I know some of you might have been searching for answers on how to set JWT HTTP-only cookies in response. I finally found an answer how to do it, and it's actually easy. You can visit my repo and scroll down to the README.MD file -
Getting 401 error : "invalid_client" in django-oauth-toolit
I am trying to have an Ouath2 access token based authentication. I am using django-oauth-toolkit for that. I have registered my app on http://localhost:8000/o/applications. However, When I tried to hit the URL http://localhost:8000/o/token/ from the react-app . I got 401. Here is my the useEffect hook that I used for calling that URL : useEffect(() => { fetch("http://localhost:8000/o/token/", { body: new URLSearchParams({ grant_type: 'client_credentials', client_id: 'my_client_id', client_secret: 'my_client_secret' }), headers: { "Content-Type": "application/x-www-form-urlencoded" }, method: "POST" }).then((res)=>{ console.log(res) }) }, []) Will look forward to some comments and solutions. -
Django webpack not loading images from static files
I'm in the process of making a website using django and react. I'm using client side rendering in react, instead of handling all the urls with django, and I stumbled upon the problem of not being able to refresh pages from urls other than the base url. From what I understood the easiest solution was webpack and it's historyApiFallback. Anyway, now that I've configured webpack, historyApiFallback doesn't work, and my static images will no longer load... Hopefully someone can help me out here, need it big time. webpack.config.js const path = require("path"); const BundleTracker = require('webpack-bundle-tracker'); const HtmlWebpackPlugin = require("html-webpack-plugin"); var config = { context: __dirname, entry: './src/index.js', output: { path: path.join(__dirname, 'assets/dist'), filename: "main.js", publicPath: '/' }, devServer:{ historyApiFallback: true }, plugins: [ new BundleTracker({ filename: './webpack-stats.json' }), new HtmlWebpackPlugin({ template: './public/index.html' }) ], devtool: 'hidden-source-map', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(png|jpg|jpeg|gif)$/, type: 'asset/resource', use: [ 'url-loader' ] }, ] } } module.exports = () => { return config }; settings.py FRONTEND_DIR = os.path.join(BASE_DIR, 'frontend') STATIC_URL = 'static/dist/' STATIC_ROOT = os.path.join(FRONTEND_DIR, "assets/dist/") STATICFILES_DIRS = ( os.path.join(FRONTEND_DIR, "static/dist/"), ) MEDIA_URL = '/Images/' … -
How can I solve this "violates not-null constraint"?
I alway get this error, even I put default value on the avg_winning_trade: django.db.utils.IntegrityError: null value in column "avg_winning_trade" of relation "trading_summary" violates not-null constraint DETAIL: Failing row contains (43897354-d89b-4014-a607-a0e6ee423b52, 1, 2023-02-05 11:09:56.727199+00, null, 1, 19, 1, 0.00, null, -1.01, -1.01, 0, 0, 0.00, 0%, 0.00). The second null value is avg_winning_trade who cause the error here, I don't know why it is null here this is my model class Summary( ActivatorModel, Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) starting_balance = models.DecimalField(default=0, max_digits=10, decimal_places=2) total_number_of_trades = models.PositiveIntegerField(default=0) total_number_of_winning_trades = models.PositiveIntegerField(default=0) total_number_of_losing_trades = models.PositiveIntegerField(default=0) total_number_of_be_trade = models.PositiveIntegerField(default=0) largest_winning_trade = models.DecimalField(default=0, max_digits=10, decimal_places=2) largest_losing_trade = models.DecimalField(default=0, max_digits=10, decimal_places=2) avg_winning_trade = models.DecimalField(default=0, max_digits=10, decimal_places=2) avg_losing_trade = models.DecimalField(default=0, max_digits=10, decimal_places=2) total_trade_costs = models.DecimalField(default=0, max_digits=10, decimal_places=2) trade_win_rate = models.CharField(max_length=10) This is the table Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target | Description --------------------------------+--------------------------+-----------+----------+---------+----------+-------------+--------------+------------- id | uuid | | not null | | plain | | | status | integer | | not null | | plain | | | activate_date | timestamp with time zone | | | | plain | | | deactivate_date | timestamp with time zone | | | | plain | | …