Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stop refresh after AJAX to Django form
I have a modal where a user can add a new Category. When the user adds a new Category and receives a response from the AJAX request I would like to use the response data to update some of the existing page data. Problem is that my form is not allowing e.preventDefault() but rather just refreshing the page after it receives a response: JQuery AJAX: function addCategory(e) { let post_url = '{% url "policies-categories-form" %}' $.ajax({ url: post_url, type:'POST', data: $('#addCategoryForm').serialize(), success: function(response){ console.log(response); // document.getElementById('editCategoriesContainer').innerHTML = data; }, error:function(){ console.log('Error'); }, }); }; Form (which is loaded using JQuery, only after a user clicks a button: {% load crispy_forms_tags %} <!--Add new category form--> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.title|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.parent|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.groups|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> <button class="btn btn-warning btn-block" id="addCategoryBtn" onclick="addCategory(this)" type="submit"> <span class="fas fa-plus"></span> Add Category </button> </div> </div> View: @login_required def policies_categories_form(request): if request.method == 'POST' and request.is_ajax(): form = PoliciesCategoryForm(request.POST, company=request.tenant) if form.is_valid(): form.save() categories = PoliciesAndProceduresCategory.objects.exclude(parent__isnull=False).values() return JsonResponse({'success': True, … -
In Django, can I do the All-In-One Front-end Integration ready (React, Vue) using Webpack like Laravel Does, creating a wrapper for compiling js?
In PHP Laravel for example I can do this without creating a directory for the Front-end stuff and the traditional and recommended way the RESTFul API or GraphQL method stuff for communication between different programming languages just taking advantage of the already included Axios(npm i = npm run dev = node_modules) in Laravel and its built-in API feature via a Route(api.php) for referencing the URI out of the box. The below code snippet is the example the webpack.mix.js(a modified configured Webpack wrapper support specifically for PHP Laravel). const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel applications. By default, we are compiling the CSS | file for the application as well as bundling up all the JS files. | */ //Additional Custom Configs implementing Typescript for React and its corresponding modules const webpack = require('webpack'); const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') // Try the environment variable, otherwise use root const ASSET_PATH = process.env.ASSET_PATH || `{{ asset('') }}` mix.webpackConfig({ entry: path.resolve(__dirname, '.', './resources/js/src/init.tsx'), resolve: { extensions: ['.css', '.tsx', '.ts', '.js'], }, module: { rules: [ { test: /\.(ts|js)x?$/, /* … -
how can i use path Django for locating and loading templates? Django 3.2
in django3.2 I was trying this to uses for locating and loading templates? but doesn't work with me TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ` [BASE_DIR / 'templates']`, } default setting was like : `from pathlib import Path` # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent Any clue of what might be the problem? -
elasticsearch.exceptions.AuthorizationException: AuthorizationException
elasticsearch error: _request self._raise_error(response.status_code, raw_data) File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/env/lib/python3.8/site-packages/elasticsearch/connection/base.py", line 315, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)( elasticsearch.exceptions.AuthorizationException: AuthorizationException(403, '{"message":"The security token included in the request is invalid."}') ERROR 2021-04-28 03:13:17,280 basehttp 2729 123145562267648 "POST /en/signup HTTP/1.1" 500 53 Django code: awsauth = AWS4Auth( os.environ.get("AWS_ES_ACCESS_KEY"), os.environ.get("AWS_ES_SECRET_KEY"), os.environ.get("AWS_ES_REGION"), os.environ.get("AWS_ES_SERVICE"), ) # Elasticsearch configuration ELASTICSEARCH_DSL = { "default": { "hosts": [ {"host": os.environ.get("AWS_ES_URL"), "port": 443}, ], "http_auth": awsauth, "use_ssl": True, "verify_certs": True, "connection_class": RequestsHttpConnection, "request_timeout": 60, } } Here is my code and error shared. My elasticsearch was working fine but, suddenly got this issues. Please let me know how to solve this. Do i need any token for this ? and how to get that -
How to filter queryset for all subcategories
I have a model: class Category(models.Model): title = models.CharField(max_length=127) # Lookups would be as follows: # cat = Category.objects.get(...) # for sub_cat in cat.sub_categories.all(): parent = models.ForeignKey( "self", on_delete=models.CASCADE, related_name="sub_categories") Obviously in templates I can filter for all the subcategories: {% for sub_cat in cat.sub_categories.all %} I would like to pass the queryset of subcategories to the form: self.fields['parent'].queryset = PoliciesAndProceduresCategory.subcategories.all() But this gives the error: AttributeError: type object 'PoliciesAndProceduresCategory' has no attribute 'subcategories' Is there an easy way to filter for this here or do I have to do something such as defining a Model Method? Thanks! -
Starting Django Project
I'm trying to create a django project with "django-admin.exe startproject mysite ." but I keep getting this error: Fatal error in launcher: Unable to create process using '"c:\users\denni\documents\ecommerce\myvenv\scripts\python.exe" "C:\Users\denni\Documents\Ecommerce_Site\myvenv\Scripts\django-admin.exe" startproject mysite .': The system cannot find the file specified. -
Stripe subscriptions checkout.session.completed resource missing error of invalid_request_error type
I am trying to understand why webhook for checkout.session.completed is crashing when testing it locally with the Stripe CLI. I am using djstripe. My webhook for customer.subscription.created is successful. With the CLI, I am getting the following error: Request failed, status=404, body={ "error": { "code": "resource_missing", "doc_url": "https://stripe.com/docs/error-codes/resource-missing", "message": "No such payment_page: 'ppage_1Il33eAyVjQjzOsRERzYQSbK'", "param": "payment_page", "type": "invalid_request_error" } Is the problem with the success url routing? views.py def create_checkout_session(request): """Create a checkout session for Stripe.""" data = json.loads(request.body) priceId = data.get("priceId") if not Price.objects.filter(id=priceId).exists(): messages.add_message(request, messages.ERROR, "That plan price is not available. Please contact support for help.", ) return HttpResponseRedirect(reverse("users:index")) request.account = OrgMembership.objects.filter(my_identity=request.user).first() sessionId = stripegateway.create_checkout_session(priceId, request) return JsonResponse({"sessionId": sessionId}) stripegateway.py class StripeGateway: """Gateway interacts with the APIs required by Stripe. Credit: Matt Layman""" def create_checkout_session(self, priceId, request): """Create a checkout session based on the subscription price.""" site = Site.objects.get_current() subscription_success = reverse("users:success") stripe_cancel = reverse("users:stripe_cancel") request.account = OrgMembership.objects.get(my_identity=request.user.id) request.org = request.account.my_org # session_parameters = { # "customer_email": request.org.billing_email, # "success_url": f"http://{site}{subscription_success}", # "cancel_url": f"https://{site}{stripe_cancel}", # "payment_method_types": ["card"], # "mode": "subscription", # "line_items": [{"price": priceId, "quantity": 1}], # "client_reference_id": str(request.account.id), # } # checkout_session = stripe.checkout.Session.create(**session_parameters) # return checkout_session["id"] checkout_session = stripe.checkout.Session.create( customer_email = request.org.billing_email, client_reference_id = str(request.account.id), payment_method_types=['card'], line_items=[{ … -
Django redirect URL based on the old URL
I have some urls that was originally in the form of uuid:pk when it is referred to specific post, more specifically path('<slug:slug>/post/<uuid:pk>/', views.post_detail, name='post_detail'), However, I've changed the path to include the post title so that it is more intuitive for the end reader path('<slug:slug>/post/<slug:post_slug>', views.post_detail, name='post_detail'), where post_slug is a contactnation of post.pk and post.title as I have override in the models def save(self, *args, **kwargs): if not self.post_slug: self.post_slug = slugify(str(self.title)+str(self.pk)) return super().save(*args, **kwargs) The issue is that i have send some links to some users that contain the old url format. I am wondering how do I redirect them automatically to the new url link. Thanks! -
how to extract a specific value from json format data for object filtering
{"field_summary": {"sex": "None -> Female", "age": "16-> 25", "status": "None -> active"}} The above json data is data stored in json format in sqlite. I would like to filter objects based on this by extracting the text output after the '->' arrow of status. ex) value.filter(summary='active').count() summary is field name. I succeeded in extracting the value with the sql statement. However, it seems to be a separate problem. For filtering -> How should I print the text after the arrow? SELECT substr(json_extract(summary, '$.field_summary.status'), instr(json_extract(summary, '$.field_summary.status'), '->')+3) AS summary FROM table name; -
I want to add username in Coment Viewsets response in DRF
#models.py class Comment(models.Model): listing = models.ForeignKey(Listing, default = 0, on_delete = models.CASCADE) user = models.ForeignKey(User, default = 0,on_delete=models.CASCADE) comment = models.TextField(max_length=100) class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ["listing", "user", 'comment' ] class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['listing'] def create(self, request): print(request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response( status=status.HTTP_201_CREATED) def perform_create(self, serializer): serializer.save(listing= Listing.objects.get(pk=self.request.data['listing']), user= User.objects.get(pk=self.request.data['user'])) ENDPOINT RESPONSE [ { "listing": 1, "user": 1, "comment": "ddd" }, { "listing": 1, "user": 2, "comment": "good" }, { "listing": 1, "user": 1, "comment": "fff" } ] -
Can't sign in admin in django admin site even though superuser does exist
I'm trying to sign in in the admin website with the credentials that I created as superuser. However, I get the error "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.". Now, I checked in the shell if the user exist and if it is a superuser and it is. Just in case, I changed its password through the shell again to no avail. I'm not sure why it's not working since the superuser does exist. I only have this in the admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) I've read the other questions about it but none have helped since my settings already have 'django.contrib.auth.backends.ModelBackend' and I've checked on the shell to see that everything's in order. So what's going on? -
how to manage multiple requests at once in django
I want to manage several event at once in django. for example if 10-people click like button of the post , owner of the post will receive one push-notification that say "10 people liked your post", not 10 push-notifications for each clicks. i can't get a any point to handling this. could somebody help this problem? -
Why does html disappar when trying to iterate using for loop in django
I am having an issue where I have categories for each product, so for my URLs, i have slugs referencing to each category. in the href on my frontpage (HTML pasted down below). I see that when I load the portion of the HTML that has the for loop applied makes it disappear. I have never run into this. Does anybody have any idea what's going on? I'll post the relevant div where this is occurring. I can post additional code if needed. Thanks In this case, the Get covered now button is missing {% extends 'base.html' %} {% block content %} {% load static %} <div id="signup"> {% for category in menu_categories %} <a class="btn btn-lg col-sm-12 slideanim" id="title" href="{% url 'category_detail' category.slug %}"> Get Covered Now! </a> {% endfor %} <a class="btn btn-lg col-sm-12 slideanim" id="title" href="#"> Learn More! </a> </div> -
How to properly end a background Celery worker in Django tests
I need to run a background Celery worker during some Django integration tests. I used the solution proposed here, and everything works fine. However, when running all my tests (which takes a while), I start getting the following error message: [2021-04-27 18:42:41,401: ERROR/MainProcess] Error in timer: AttributeError("'NoneType' object has no attribute 'heartbeat_tick'") Traceback (most recent call last): File "/home/user/.local/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 145, in fire_timers entry() File "/home/user/.local/lib/python3.7/site-packages/kombu/asynchronous/timer.py", line 68, in __call__ return self.fun(*self.args, **self.kwargs) File "/home/user/.local/lib/python3.7/site-packages/kombu/asynchronous/timer.py", line 130, in _reschedules return fun(*args, **kwargs) File "/home/user/.local/lib/python3.7/site-packages/kombu/connection.py", line 312, in heartbeat_check return self.transport.heartbeat_check(self.connection, rate=rate) File "/home/user/.local/lib/python3.7/site-packages/kombu/transport/pyamqp.py", line 149, in heartbeat_check return connection.heartbeat_tick(rate=rate) AttributeError: 'NoneType' object has no attribute 'heartbeat_tick' It seems that this is caused by trying to send a heartbeat from workers that have been ended. I have searched around and could not find how to end workers more cleanly. Here is a minimal failing example: import time import socket import selenium from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from django.contrib.staticfiles.testing import StaticLiveServerTestCase from celery.contrib.testing.worker import start_worker from celery.contrib.abortable import AbortableAsyncResult from myproject.celery import app from frontend import tasks docker = False # Same result with Docker class TestServer(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.host = socket.gethostbyname(socket.gethostname()) if … -
Django: Count related model where an annotation on the related has a specific value and store count in an annotation
I have two models Pick and GamePick. GamePick has a ForeignKey relation to Pick, which is accessible on Pick.game_picks. I have setup GamePick with a custom queryset and manger so that when ever I retrieve a GamePick with the manager objects is is annotated with a field is_correct based on the values of other fields. Now what I want to be able to do is count the how many correct GamePicks are pointing to a specific Pick. One simple way is doing this with a method in Python: class Pick(models.Model): ... def count_correct(self): return self.game_picks.filter(is_correct=True).count() So far so good. But now, I would like to annotate each Pick with that count, say as correct_count. This is so I can order the Pick with something like Pick.objects.all().order_by("correct_count"). Now how would I do this? This is where I am: correct_game_picks = GamePick.objects.filter( pick=models.OuterRef("pk") ).filter(is_correct=True) subquery = models.Subquery( correct_game_picks.values("is_correct"), output_field=models.BooleanField() ) picks = Pick.objects.annotate( correct_count=models.Count(subquery) ) This is what pick.query gives me: SELECT "picks_pick"."id", "picks_pick"."picker", "picks_pick"."pot_id", COUNT(( SELECT (U0."picked_team_id" = U1."winning_team_id") AS "is_correct" FROM "picks_gamepick" U0 INNER JOIN "games_game" U1 ON (U0."game_id" = U1."id") WHERE (U0."pick_id" = "picks_pick"."id" AND (U0."picked_team_id" = U1."winning_team_id")) )) AS "correct_count" FROM "picks_pick" GROUP BY "picks_pick"."id", "picks_pick"."picker", "picks_pick"."pot_id" I … -
Is it possible to create an updating newsfeed in Django
Here's the gist of my goals in my project. Collect data from Reddit, Twitter, etc. using their respective APIs. Embed those posts in a newsfeed format (newest post at the top, etc). Save previous posts in the bottom of the feed(user can scroll down and see past posts) (involves caching?) What I've done: So pretty much, I've been able to create a services script to fetch the data through the APIs, store each post in a list ordered by creation time, pass this list through the view as context to my template, and, in the template, check if the post is a twitter or reddit post by looping through the context. If either, access the respective template tag to post the embedded html to the page. Note: This is easily the most difficult project I've worked on as a self-taught developer, so some concepts that are necessary to understand to complete my final project may be out of my realm of knowledge. That's OK, but I'm not sure what concepts I need to understand. Alas, why I am here. Basically, is it possible to implement this newsfeed-esque design using Django, or does that reach the limit of the framework's functionality? … -
How to post data with null fields in django?
I am trying to have a source class that takes in either a project, profile, department, or team as an AutoOneToOne Field from django_annoying. Basically, I am trying to have access to the sourceID and source type (project, profile, department, or team) to then send to a different class: Posts. When I try to add a source with profile "s" and null for the other fields as shown here: I get the following error message: I've tried adding a default="", but that is counterintuitive, and doesn't work anyways. Here is my Source class: class Source(models.Model): profile = AutoOneToOneField('Profile', on_delete=models.CASCADE, null=True, blank=True) project= models.OneToOneField('Project', on_delete=models.CASCADE, null=True, blank=True) team = AutoOneToOneField('Team', on_delete=models.CASCADE, null=True, blank=True) department = AutoOneToOneField('Department', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.profile + self.project + self.team + self.department -
How can I change custom radio widget code to hide the text in Django?
This is the code I have for my custom radio widget {% with id=widget.attrs.id %}<div{% if id %} id="{{ id }}" {% endif %}{% if widget.attrs.class %} class="{{ widget.attrs.class }}" {% endif %}> {% for group, options, index in widget.optgroups %}{% if group %} <div style='display:inline-block'> {{ group }}<div style='display:inline-block' {% if id %} id="{{ id }}_{{ index }}" {% endif %}> {% endif %}{% for option in options %} <div style='display:inline-block'>{% include option.template_name with widget=option %}</div>{% endfor %}{% if group %} </div></div>{% endif %}{% endfor %} </div>{% endwith %} This is the actual HTML that is produced and I'm pretty sure I can't isolate "Strongly Disagree" text because it is not wrapped. The text is right next to the radio widget circle. I want to hide the text or at least make it opacity: 0 so I can eventually turn the form into this layout since it is 5 questions with the same agree/disagree options: -
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 .Django 3.0.2
Project name : CRMPROJECT App name: leads I'm working on a CRM project With Django and I keep getting this error while trying to map my urls to views django.core.exceptions.ImproperlyConfigured. The included URLconf does not appear to have any patterns in it Below is the project/urls.py file ''' from django.contrib import admin from django.urls import path,include from leads import views urlpatterns = [ path('admin/', admin.site.urls), path('leads/',include('leads.urls',namespace='leads')), ] ''' Below is leads/urls.py from django.urls import path from . import views app_name = 'leads' urlpatterns = [ path('',views.home,name='home'), ] And lastly my leads/views.py ''' from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request,'leads/base.html') ''' -
MINIO on localhost?
I want to set up MinIO as my Django app object storage, and I want to test the functionality of this module on my computer (localhost). I follow the instruction in django-minio-backend, but I got the below error. raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='127.0.0.1', port=9000): Max retries exceeded with url: /django-backend-dev-public?location= (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1091)'))) These are lines that I've added to my settings.py file. INSTALLED_APPS = [ ... 'rest_framework', 'django_minio_backend', ... ] MINIO_CONSISTENCY_CHECK_ON_START = True MINIO_ENDPOINT = '127.0.0.1:9000' MINIO_ACCESS_KEY = 'minioadmin ' MINIO_SECRET_KEY = 'minioadmin ' MINIO_USE_HTTPS = True MINIO_URL_EXPIRY_HOURS = timedelta(days=1) # Default is 7 days (longest) if not defined MINIO_CONSISTENCY_CHECK_ON_START = True MINIO_PRIVATE_BUCKETS = [ 'django-backend-dev-private', ] MINIO_PUBLIC_BUCKETS = [ 'django-backend-dev-public', ] MINIO_POLICY_HOOKS: List[Tuple[str, dict]] = [] here -
'User' object has no attribute 'is_verified'
Im having this error. All of a sudden it was working fine on my local. but when i tried to deploy the app i have this error, im using a package two_factor Otp, here is the traceback Traceback: File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/contrib/admin/sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner 212. if not self.has_permission(request): File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/two_factor/admin.py" in has_permission 28. return request.user.is_verified() File "/tmp/8d909c171bfae2c/antenv/lib/python3.7/site-packages/django/utils/functional.py" in inner 257. return func(self._wrapped, *args) Exception Type: AttributeError at / Exception Value: 'User' object has no attribute 'is_verified' any help would be appreciated. thank you -
Django - submit button value
I'm trying to send the value of a button when a form is submitted using the POST method. {% block content %} <div class="modal-dialog modal-lg" role="document"> <form action="" method="post" id="news-create" class="form">{% csrf_token %} <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title">Add News</h4> </div> <div class="modal-body"> {{ form }} </div> <div class="modal-footer"> <input class="btn btn-primary" type="submit" name="save" value="Save" /> <input class="btn btn-primary" type="submit" name="save_new" value="Save as new" /> </div> </div><!-- /.modal-content --> </form> </div><!-- /.modal-dialog --> <script> var form_options = { target: '#modal', success: function(response) {} }; $('#news-create').ajaxForm(form_options); </script> {% endblock content %} But when I print the QueryDict request.POST inside the file view.py the value of the button is not present. How can I get the value? I need to perform different action based on the button clicked. At the moment I'm using a bootstrap modal view to render a form (UpdateView) based on a model. Thanks for the support -
Django search submission from different urls not working
I'm trying to use a search form in a nav bar, but for whatever reason it is not being redirected to the correct URL. it should go to "http://localhost:8000/search?q=hj" but goes to "http://localhost:8000/?q=hj" or just appends on to the end of the url. Why is this? If i include the 'search' in the url manually, it works. in urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.Index.as_view(), name="index"), path("search", views.search, name="search"), ] in views.py: def search(request): if request.method == 'GET' and 'q' in request.GET: q = request.GET['q'] bugs = Bug.objects.filter(title__contains=q).order_by('priority', 'solved') projects = Project.objects.filter(title__contains=q) return render(request, 'myapp/searched.html', {'bug_list': bugs, 'project_list': projects}) and the template: <form action="{% url 'search' %}" method="GET"> <input type="text" class="form-control bg-light border-0 small" placeholder="Search bugs or projects..." aria-label="Search" name="q" aria-describedby="basic-addon2"> <div class="input-group-append"> <button class="btn btn-info" type="submit"> <i class="fas fa-search fa-sm"></i> </button> </div> </form> I've searched for similar answers but was unable to find any. I know I'm likely missing something really obvious and just can't see it. -
ModuleNotFoundError: No module named 'apps.product.context_processors'
I'm getting this error and I cannot find what is causing it. Here is the traceback: Traceback (most recent call last): File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/alex/projects/passtur/passtur/apps/core/views.py", line 9, in frontpage return render(request, 'core/frontpage.html', {'newest_products': newest_products}) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/base.py", line 168, in render with context.bind_template(self): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 117, in __enter__ return next(self.gen) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/context.py", line 240, in bind_template processors = (template.engine.template_context_processors + File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/engine.py", line 85, in template_context_processors return tuple(import_string(path) for path in context_processors) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/template/engine.py", line 85, in <genexpr> return tuple(import_string(path) for path in context_processors) File "/Users/alex/projects/passtur/venv/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'apps.product.context_processors' [27/Apr/2021 21:43:33] "GET / HTTP/1.1" 500 110467 My core/views.py is: from django.shortcuts import … -
How do I properly setup an producer - consumer scheme using redis as a message broker and store results in postgresql / sqlite?
I am really new with celery - redis scheme, but I am trying to implement a producer-consumer https://github.com/SkyBulk/celery scheme similar to where my task producer is my Django tasks , and then a broker (Redis) with celery beat for task scheduler where Redis can fit on this scheme to store my tasks, and celery worker executes task producer (django tasks) or any other outside djngo and save results of those tasks to sqlite or postgresql (not the logs of the scheduler) demo questions. why do I get nothing on Redis? INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "orders.apps.OrdersConfig", ] CELERY_BROKER_URL = "redis://redis:6379/0" CELERY_RESULT_BACKEND = "redis://redis:6379/0" CELERY_BEAT_SCHEDULE = { "sample_task": { "task": "orders.tasks.sample_task", 'schedule': timedelta(seconds=2), }, "send_email_report": { "task": "orders.tasks.send_email_report", "schedule": crontab(minute="*"), }, } logs celery_1 | [2021-04-27 21:42:01,910: INFO/MainProcess] Received task: orders.tasks.sample_task[a50a9653-c141-4922-816a-67b9423bb110] celery_1 | [2021-04-27 21:42:01,912: WARNING/ForkPoolWorker-3] each two seconds celery_1 | [2021-04-27 21:42:01,913: INFO/ForkPoolWorker-3] Task orders.tasks.sample_task[a50a9653-c141-4922-816a-67b9423bb110] succeeded in 0.0017081940000025497s: None celery_1 | [2021-04-27 21:42:03,910: INFO/MainProcess] Received task: orders.tasks.sample_task[567c8088-3de7-4876-a86f-ee418ff47ec5] celery_1 | [2021-04-27 21:42:03,912: WARNING/ForkPoolWorker-3] each two seconds celery_1 | [2021-04-27 21:42:03,913: INFO/ForkPoolWorker-3] Task orders.tasks.sample_task[567c8088-3de7-4876-a86f-ee418ff47ec5] succeeded in 0.0019250379999675715s: None celery_1 | [2021-04-27 21:42:05,908: INFO/MainProcess] Received task: orders.tasks.sample_task[407d41a7-8b09-4760-94d8-9311f0e9222e] celery_1 | [2021-04-27 21:42:05,909: WARNING/ForkPoolWorker-3] each two seconds celery_1 | [2021-04-27 21:42:05,910: …