Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Slug Size Exceeded by 800MB For Django Project
This is my first time using Heroku to deploy a Django application and the slug size exceeds by 800MB. Error Log I used to have around 360 jpeg images in my folder but moved it to S3, and it went from 1.5GB to 1.3GB. I'm probably getting something completely wrong, but I can't seem to figure it out. There are a few aspects that I feel like is causing this. First, in one of the Django models, I have a field that serves pickle objects. I needed this because I need it to store the rgb data (numpy) for every image. It is 64*64pixels and it may be taking a lot of space. enter image description here The second is the 360 images that I had and pushed to Github. This is the command to show the files and folders in the current directory, ordered by (uncompressed) size: enter image description here If would be greatly appreciated if anyone could guide me to where I should look. Please tell me if I need to provide anything else. Thank you! -
I want to pluging openedx xblock ckeditor in xblock package please if any one do same thing then help me out
Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock SyntaxError: Unexpected token '>' at eval (<anonymous>) at Function.globalEval (jquery.js:343) at domManip (jquery.js:5291) at jQuery.fn.init.append (jquery.js:5431) at child.loadResource (xblock.js:236) at applyResource (xblock.js:199) at Object.<anonymous> (xblock.js:202) at fire (jquery.js:3187) at Object.add [as done] (jquery.js:3246) at applyResource (xblock.js:201) "SyntaxError: Unexpected token '>'\n at eval (<anonymous>)\n at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)\n at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)\n at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)\n at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)\n at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)\n at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)\n at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)" -
Django - Batch Actions in a ListView - Select Rows and Return a Zip Archive in Response
Ok, first off, I know this is not the best way to handle serving files on a prod server. But this site will be accessed by a small group of users, the request for these files should be minimal, and the static files being served are very small - so I am trying to keep things simple. I have a ListView Table where the user can select rows and then perform batch actions on the objects (eg. Delete, Export CSVs, Send CSV data to another location, etc). I've created a class based view to handle each of these batch actions. The only action that I can't get to work is when the user requests a download of a ZIP archive of the CSV data. When the ZIP export action is selected from the ListView, the selected rows are written as individual CSV files into to a static file location, and then zipped into a single ZIP archive. But the FileResponse never returns the archive to the user as a download. I've tried different ways of handling the response - redirecting to a new URL, reverse to the ListView, different URL patterns, etc. the method shown below that handles the create … -
NoReverseMatch at /course/ Reverse for 'course_detail' not found. 'course_detail' is not a valid view function or pattern name
I am trying to return all courses from the database to my course url and i got this error NoReverseMatch at /course/ Reverse for 'course_detail' not found. 'course_detail' is not a valid view function or pattern name. here is my code `class Courses(models.Model): category = models.ForeignKey(Category, related_name='courses', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100) description = models.TextField() cover = models.ImageField(blank=True, null=True, upload_to="courses_cover/") slug = models.SlugField() # Courses content content_url = models.URLField(blank=True, null=True) content_file = models.FileField(blank=True, null=True) price = models.PositiveIntegerField(default=1) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return reverse('courses:course_detail', args=[self.id, self.slug]) def price_display(self): return "{0:.2f}".format (self.price / 100) code for the views.py def course_list(request, category_slug=None): category = None categories = Category.objects.all() courses = Courses.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) courses = courses.filter(category=category) return render(request,'courses/content/list.html', {'category': category, 'categories': categories, 'courses': courses}) def course_detail(request, id, slug): course = get_object_or_404(Courses, id=id, slug=slug, available=True) return render(request, 'courses/content/detail.html', {'course': course}) ` code for the course urls app_name = "courses" urlpatterns = [ path('', views.course_list, name='course_list'), ] -
Unable to import firebase module inside firebase-messaging-sw.js
Im working on firebase messaging service to send push notification via django web application to web app on Andriod,IOS and website as well, I managed to get token and run sw ,however i can't running sw and get messages due to importing module issue, I tried all import statements and none has worked with me!!, when i run the below lines i got this error "Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js'); and when i run these ones i got this error "Cannot use import statement outside a module": import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"; import { getMessaging } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js"; Note I do not have any error when accessing localhost:/firebase-messaging-sw.js and download window open to download firebase-messaging-sw.js file please findfirebase-messaging-sw.js files for your reference: // import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"; // import { getMessaging } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js"; importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging.js'); self.importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js'); // import { initializeApp } from "./node_modules/@firebase/app"; // import { getMessaging } from "./node_modules/@firebase/messaging/sw"; // import { getMessaging } from "./firebase/@firebase/messaging/sw"; // Initialize the Firebase app in the service worker by passing in // your app's Firebase config object. // https://firebase.google.com/docs/web/setup#config-object const BikumApp = firebase.initializeApp({ apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx', authDomain: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx', databaseURL: 'xxxxxxxxxxxxxxxxxxxxxxxxxx', projectId: 'xxxxxxxxxxxxxxxxxxxxxx', storageBucket: 'xxxxxxxxxxxxxxxxxxxxxxx', … -
How do I perform a nexted query on django models
so i have these 2 model Profile (have one to one relationship with my default django User model) Item ( also have one to one relationship with my default django User model) from Item model, how do i get access to Profile model using User model please see my code below My Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=200,null=True) ``` My View def home(request): all_item_lists = Item.objects.all() context = { 'all_item_lists':all_item_lists } return render(request, 'findit/home.html', context) My Template {% for list in all_item_lists %} <!-- how want to get the phone number of the user that posted this Item --> <span>{{list.owner.first_name }}</span> {% endfor %}``` -
Importing from views directory
In my project I have an app called api where I keep my viewsets in a directory called views. I keep getting ModuleNotFoundError: No module named 'api.views.book'; 'api.views' is not a package where I import in my api/urls.py api/urls.py from rest_framework import routers from api.views.book import BookViewset router = routers.DefaultRouter() router.register(r'books', BookViewset, 'books') api_urls = router.urls In my main urls.py I'm doing this: urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from api.urls import api_urls urlpatterns = [ path('api', include(api_urls)), path('admin/', admin.site.urls), ] I didn't get an error until I imported api_urls -
Django Serializer from ManyToManyField using through
I'm trying to serialize the User model from Django, including a manyToMany relation I created. Here are my models: class CompanyAccount(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) user_ids = models.ManyToManyField(User, through='CompanyUser') class CompanyUser(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) user_id = models.ForeignKey(User, on_delete=models.CASCADE) company_id = models.ForeignKey(CompanyAccount, on_delete=models.CASCADE) is_company_admin = models.BooleanField(default=False, null=True) Now my goal would be to get the company serialized and returned along with any user. Here are my serializer, but sadly the company is not returned. class CompanyAccountSerializer(serializers.ModelSerializer): address_id = AddressSerializer(many=False) class Meta: model = CompanyAccount fields = '__all__' class UserSerializer(serializers.ModelSerializer): company_id = CompanyAccountSerializer(many=False, read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'first_name', 'last_name', 'company_id'] Any help is welcome :-) -
Django aggregate query with filters
i have two tables.Template and Tracker tables. with one to many relationship. i need to show all the uploaded templates for a particular user. also i need to order by with the download count. i tried the following query. but it's not getting the all downloaded count. Template.objects.filter(tracker__type='upload', user_id=300).annotate( download_count=Count( 'tracker', filter=Q(tracker__type='download') ) ).order_by("-download_count") Template Table id title description 1 AAA AAA 2 AAA AAA 3 AAA AAA Tracker Table id type user_id template_id 1 download 100 1 2 download 200 1 3 upload 300 1 -
How do you avoid SQL Injection attacks in your Django Rest APIs if using native ORM?
They say that by using Django ORM you are already protected against most SQL Injection attacks. However, I wanted to know if there are any additional measures that should or can be used to process user input? Any libraries like bleach? -
Heroku 20-stack django deployment issue (djongo not found)
-----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/app/.heroku/python/lib/python3.6/site-packages/djongo/base.py", line 11, in from . import database as Database File "/app/.heroku/python/lib/python3.6/site-packages/djongo/database.py", line 2, in from pymongo import MongoClient File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/init.py", line 77, in from pymongo.collection import ReturnDocument File "/app/.heroku/python/lib/python3.6/site-packages/pymongo/collection.py", line 20, in from bson.code import Code File "/app/.heroku/python/lib/python3.6/site-packages/bson/code.py", line 18, in from bson.py3compat import abc, string_type, PY3, text_type ImportError: cannot import name 'abc' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 357, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", … -
How do I pass a context name into a url call in my template html django
This is the urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('blog/', views.blog, name='blog') ] This is the views.py file def index(request): # Home home = Home.objects.latest('updated') # About about = About.objects.latest('updated') profiles = Profile.objects.filter(about=about) # Skills categories = Category.objects.all() # Portfolio portfolios = Portfolio.objects.all() context = { 'home': home, 'about': about, 'profiles': profiles, 'categories': categories, 'portfolios': portfolios } if request.method == "POST": form_inst = FormFill(name = request.POST['name'], email = request.POST['email'], text = request.POST['text']) form_inst.save() return redirect('/') return render(request, 'index.html', context=context) This is the html file where I am trying to pass each context name to the the navlink <div class="nav__menu" id="nav-menu"> <ul class="nav__list"> <li class="nav__item"><a href="{% url 'blog' %}" class="nav__link active" target="_blank">Blog</a></li> <li class="nav__item"><a href="{% url 'index' {{home}} %}" class="nav__link">Home</a></li> <li class="nav__item"><a href="{% url 'index' {{sbout}} %}" class="nav__link">About</a></li> <li class="nav__item"><a href="{% url 'index' {{profiles}} %}" class="nav__link">Skills</a></li> <li class="nav__item"><a href="{% url 'index' {{categories}} %}" class="nav__link">Portfolio</a></li> <li class="nav__item"><a href="{% url 'index' {{portfolios}} %}" class="nav__link">Contact</a></li> </ul> </div> I would like to pass the context dictionary keys in the url of each nav link in the html file -
Dash app in django-plotly-dash breaking migrate, how to stop it executing in a migrate?
I am using django-plotly-dash so have a Django template that hosts a Dash app. (The Dash app is using raw SQL queries over psycopg2) When I do a django migrate, this dash raw SQL fails because the tables have not yet been created. Thus halting the migrate. aka Catch22. Anyone know if there's a way to stop the Dash apps being executed during a migrate ? -
django-ninja endpoint for post
I am a beginner in programming, I use Django + Django ninja in my project. Now stuck on the moment of creating endpoints I'm trying to make a filter to add tags to an article and check if the tag exists. Here is the piece of code I'm currently working on: @router.post('/article', response={200: schema.ArticleOut, 500: schema.Error}) def create_article(request, tags_id: List[int], payload: schema.ArticleIn): try: for tag in tags_id: if tag > 0: qs = models.Article.objects.create(**payload.dict()) qs.save() current_article = get_object_or_404(models.Article, pk=qs.id) e = models.Tag.objects.get(pk=tag) current_article.tags.add(e) return 200, qs else: return 500, {'msg': 'No Tags'} except: return 500, {'msg': 'Not'} Tell me, does it make sense to do this in the request, if so, how best to implement it? Maybe there are other approaches? -
Dockerize exists Django Postgres project:on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432?
I have a django project using postgresql run in local host without any problem. And then I started to dockerize it: original settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'myuser', 'PASSWORD': 'mypass', 'HOST': 'localhost', 'PORT': ' ', } } Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 Then I run: docker-compose build Image build successfully. Then I run : docker-compose up Error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Cannot assign requested address web_1 | Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432? I know it is because container not able to connect with my local Postgresql db.What should I do,any friend can help? -
GitHub Actions with encrypted SECRET_KEY as environmental variable do not work
I don't have much experience in coding. I am currently writing a small Django application. Following all the rules, I do not want to place the SECRET_KEY in the repository, so I created the SECRET_KEY environment variable in the .bashrс file. And in the settings.py file I wrote: SECRET_KEY = os.environ.get ('SECRET_KEY') When I execute pylint --load-plugins pylint_django my_application in the terminal on my computer everything works. I get a response Your code has been rated at 9.88 / 10 Also I have workflow pylint.yaml to accomplish pylint-django tests on push trigger, when I send my files to my GitHub repo: name: Pylint on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Analysing the code with pylint run: | pylint --load-plugins pylint_django rm When I am pushing my files to GitHub, I reseive this: Run pylint --load-plugins pylint_django rm Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/pylint_django/checkers/foreign_key_strings.py", line 90, in open django.setup() File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/django/conf/__init__.py", line 63, … -
Could't Import Django: Are you sure it's installed and activated in your PYTHONPATH
I am trying to run django in python 3.6.8. When using pip freeze in my activated venv i get this list: asgiref==3.2.3 backports.entry-points-selectable==1.1.1 distlib==0.3.3 Django==3.0.8 django-bootstrap-datepicker-plus==3.0.5 django-crispy-forms==1.9.1 filelock==3.3.2 importlib-metadata==4.8.2 importlib-resources==5.4.0 mysqlclient @ file:///D:/Downloads/mysqlclient-1.4.6-cp36-cp36m-win32.whl Pillow==7.2.0 platformdirs==2.4.0 pytz==2020.1 six==1.16.0 sqlparse==0.3.1 typing-extensions==3.10.0.2 virtualenv==20.10.0 zipp==3.6.0 When i try to run my migrate.py file the following error: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\management\__init__.py", line 14, in <module> from django.core.management.base import ( File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\management\base.py", line 11, in <module> from django.core import checks File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\checks\__init__.py", line 8, in <module> import django.core.checks.caches # NOQA isort:skip File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\checks\caches.py", line 2, in <module> from django.core.cache import DEFAULT_CACHE_ALIAS File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\cache\__init__.py", line 15, in <module> from asgiref.local import Local ModuleNotFoundError: No module named 'asgiref' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The virtual environment is activated. I tried setting up the PYTHONPATH in my environment variables with no success. I am using … -
Getting MultiValueDictKeyError on Django while trying to receiving a stripe hook
I am getting a django.utils.datastructures.MultiValueDictKeyError while trying to receive a stripe signal when a subscription's charge fails, Here is the traceback Traceback (most recent call last): File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback return callback(request, *args, **kwargs) File "/usr/lib/python3.7/contextlib.py", line 74, in inner return func(*args, **kwds) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/zebra/views.py", line 38, in webhooks request_data = json.loads(request.POST["request_data"]) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/utils/datastructures.py", line 80, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'request_data' [13/Nov/2021 09:36:29] "POST /zebra/webhooks/ HTTP/1.1" 500 121292 I am using django 2.2 Python 3.7.12 Thanks in advance for any solutions and suggestions. -
How to send user IP address from ListView to template?
i'm working on a blog project using django.I need to send User IP address from my class PostListView (which inheritance ListView class) to template, how can i do this ????? This is my signals.py from django.contrib.auth.signals import user_logged_in from django.contrib.auth.models import User from django.dispatch import receiver @receiver(user_logged_in,sender=User) def login_success(sender,request,user,**kwargs): print("____________________________") print("log in") ip = request.META.get('REMOTE_ADDR') print(" ip: ",ip) request.session['ip'] = ip I think i need to change in views.py, so what i need to add/change.... views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self,request, **kwargs): ip = request.session.get('ip',0) context = super().get_context_data(**kwargs) context['ip'] = ip return context Template <p>ip{{ip}}</p> I got a error from views.py -
How to get the param PK in django restframework permission?
I have this permission in Django that look like this: class PermissionName(BasePermission): def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True #I want to extract the pk or id params in here. return False Can anybody help me get the params of request I tried using self.kwargs["pk"], request.POST['pk'] but they all return saying object has no attribute. -
ImproperlyConfigured: The included URLconf
I am trying to have all access all courses in my courses.urls but when i trying running my server, i am getting this error message. ImproperlyConfigured: The included URLconf '<module 'courses.urls' from 'C:\Users\USER\Desktop\jtalk_project\jtalks_institute\courses\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Here is my code def course_list(request, category_slug=None): category = None categories = Category.objects.all() courses = Courses.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) courses = Courses.filter(category=category) return render(request,'courses/content/list.html', {'category': category, 'categories': categories, 'courses': courses}) def course_detail(request, id, slug): course = get_object_or_404(Courses, id=id, slug=slug, available=True) return render(request, 'courses/content/detail.html', {'course': course}) here is the code for my url project directory urlpatterns = [ path('admin/', admin.site.urls), path('', include('jtalks.urls')), path('signup/', user_signup, name='signup'), path('blog/', include('blog.urls', namespace='blog')), path('course/', include('courses.urls', namespace='course')), ] What could be the problem ? -
sessions in django not updating
i'm a beginner webdeveloper, and i have an issue. i'm building an e-commerce website following this tutorial on youtube. everthing was going fine until i was trying to access the session data through the session key onthe django shell. it was returning an empty dictionary even tho it's meant to return the product id and the price. the codes are down below the view from django.shortcuts import render from django.http import JsonResponse from django.shortcuts import get_object_or_404 from store.models import Product from .cart import Cart # Create your views here. def cart_summary(request): return render(request, 'store/cart/summary.html') def cart_add(request): cart = Cart(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) cart.add(product=product, qty=product_qty) response = JsonResponse({'test':'data'}) return response the cart.py class Cart(): def __init__(self, request): self.session = request.session cart = self.session.get('skey') if 'skey' not in request.session: cart = self.session['skey']= {} self.cart = cart def add(self, product, qty): product_id = product.id if product_id not in self.cart: self.cart[product_id]= {'price': str(product.price), 'qty':int(qty)} self.session.modified = True the script <script> $(document).on('click', '#add-button', function(e){ e.preventDefault(); console.log($('#select option:selected').text()) $.ajax({ type:'POST', url:'{% url "cart:cart_add" %}', data:{ productid: $('#add-button').val(), csrfmiddlewaretoken:"{% csrf_token %}", action: 'post' }, success: function (json){ }, error: function (xhr, errmsg, err){} }) }) </script> -
Using prefetch_related and aggregations to avoid n+1 issue with Django database queries for model with time series data
I am trying to avoid an obscene amount of database queries in a Django app. In the app I am monotoring a number of suggestions (model: Suggestion) that can be voted for (model: Vote). The Vote model does not store each individual vote. Instead the total number of votes for a suggestion are stored at regular intervals. A suggestion of "Better ice cream" could have "10 votes at 8:10", "12 votes at 8:20", "25 votes at 8:30", etc. I have created a very ineffecient loop with some major n+1 issues to calculate the number of new votes per day per suggestion. I am looking for a more efficient (probably single) queryset than the current ones for the same functionality. I know that I should probably create some kind of annotation by dates of votes on "suggestions" in views.py and then annotate that by my aggregate function that calculates the number of votes on each day, but I cannot figure out how to actually chain this together. Here's my current working but very inefficient code: models.py: class Suggestion(models.Model): unique_id = models.CharField(max_length=10, unique=True) title = models.CharField(max_length=500) suggested_date = models.DateField() class Vote(models.Model): suggestion = models.ForeignKey('Suggestion', on_delete=models.CASCADE) timestamp = models.DateTimeField() votes = models.IntegerField() … -
Not getting Django paypal IPN handshake
I am trying to implement Django- PayPal in my project , now it has been 3 days , I am still stuck on this , I don't understand how we perform IPN handshake, I am receiving a signal from PayPal after payment but what is the next step after this , really frustrated there are no clear docs about this process help needed , thanks in advance def show_me_the_money(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: verify_url = settings.VERIFY_URL_TEST print ('content-type: text/plain') print () print('SIgnal form paypal') param_str = sys.stdin.readline().strip() print(param_str) params = urllib.parse.parse_qsl(param_str) params.append(('cmd', '_notify-validate')) print(params) headers = {'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'Python-IPN-Verification-Script'} r = requests.post(verify_url, params=params, headers=headers, verify=True) r.raise_for_status() print(r) # WARNING ! # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != settings.PAYPAL_RECEIVER_EMAIL: # Not a valid payment print('reciever mail is diff') print(ipn_obj.receiver_email) # ALSO: for the same reason, you need to check the amount # received, `custom` etc. are all what you expect or what # is allowed. # Undertake some action depending upon `ipn_obj`. if ipn_obj.custom == "premium_plan": … -
phone verification in django session or cookie for security purpose
i am trying to validate a user phone number in my website using twilio and django. but for some reason i am really concern about security risk.So my question is: What is the best to use cookie or session ?(i want to code validation to expire after 5 minutes) Will my code below will need some improvement for security reason ? views.py @login_required def show_phone_verification(request): form = NumberForm() if request.method == 'POST': form = NumberForm(request.POST) if form.is_valid(): request.session['number'] = form.cleaned_data.get('telephone') request.session['code'] = generate_code() return redirect('send_verify_code') return render(request,request.session['is_mobile']+'profile/phone_show.html',{'form':form}) @login_required def send_verify_code(request): form = CodeForm(request.POST or None) code = request.session.get('code',None) number_verify = request.session.get('number',None) if number_verify and code: if not request.POST: send_sms(number_verify,code) if form.is_valid(): del request.session['code'] del request.session['number'] number = form.cleaned_data.get('number') if number == code: obj, created = Phone.objects.update_or_create( user=request.user,is_verified=True, defaults={'phone': number_verify},) messages.success(request,'Your Number Has been verified.') return redirect('news') else: messages.success(request,'Your Number Has not been verified.Tried again.') return redirect('show_phone_verification') return render(request,request.session['is_mobile']+'profile/verify_code.html',{'form':form}) else: messages.success(request,'Access Refused') return redirect('news') Thanks.