Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django translation files not generated inside locale directory in a specific app
I have no issue with running django-admin makemessages --all from the base directory and the .po files are being generated inside the locale directory in my main app but I have an issue with generating the same files in my specific apps. my project looks like this ├── about_page ((but this one is not filled) ___ en ___ de ___ es ___ fr ├── accessories ├── callibrators ├── careers ├── contact_page ├── db.sqlite3 ├── dimensional_measurement ├── leak_testing ├── locale ___ en (these files are filled with .po files) ___ de ___ fr ___ es ├── manage.py ├── mysite ├── newsnevents_page ├── polls ├── products_page └── services my settings.py has from django.utils.translation import gettext_lazy as _ LANGUAGES = [ ('en', _('English')), ('de', _('German')), ('fr', _('French')), ('es', _('Spanish')), ] LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), os.path.join(BASE_DIR, 'about_page', 'locale'), ] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'about_page.apps.AboutPageConfig', 'contact_page.apps.ContactConfig', 'products_page.apps.ProductsPageConfig', 'careers.apps.CareersConfig', 'newsnevents_page.apps.NewsneventsPageConfig', 'dimensional_measurement.apps.DimensionalMeasurementConfig', 'leak_testing.apps.LeakTestingConfig', 'callibrators.apps.CallibratorsConfig', 'services.apps.ServicesConfig', 'accessories.apps.AccessoriesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_recaptcha', 'rosetta', #NEW ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' when I execute this from the project's base directory django-admin makemessages --all the locale in base directory is filled but the about_page's … -
http://127.0.0.1:8000/ This site can’t be reached127.0.0.1 refused to connect
I created my program in pycharm. It is a series of questions for the user that adds their inputs and get a result from it, pretty basic stuff. I want to share the program with my colleagues, but they are not interested in the coding part, they want to see how it works. So I thought did a little research and decided to test Django. I installed django 4.2.10 and followed chatgtp's steps. Now I have the following folders and files: HYSPI_project/ |-- HYSPI_app/ # Your Django app |-- HYSPI_project/ # Your Django project folder | |-- __init__.py | |-- asgi.py | |-- settings.py | |-- urls.py | |-- wsgi.py |-- db.sqlite3 |-- manage.py |-- python Everything looks good, but when I run python manage.py runserver, the only thing that happens is that my program starts, in bash (mamba). If I try to open http://127.0.0.1:8000 in the browser it says the site cannot be reached. I have verified everything, connection, firewall, and all suggestions from chatgpt. Maybe the problem is in one of my files, manage.py, urls.py, settings.py, but when I ask chatgpt it always says that everything looks ok, and asks me for more information on the error when … -
How to import and use a file in django project folder
Project structure I'm trying to import the file "am_model.py" in backend/api/views.py. The "am_model.py" uses files from the easy_ViTPose folder (it is a github directory). Relative import does not work as it gives me: ImportError: attempted relative import beyond top-level package. Any ideas how can I import this in views.py? Thank you. -
How to show all questions and answer inputs in Django?
I made this models, urls, etc, but it doesn't show all questions/pertanyaan that I made. It also didn't save the answers/jawaban through database. Idk which one is having error. Here's my code, though : views.py from django.shortcuts import render, redirect from .models import Pertanyaan from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from .forms import JawabanForm from django.contrib import messages @login_required def get_pertanyaans(request): if request.method == 'POST': jawab_form = JawabanForm(instance=request.user, data=request.POST) if jawab_form.is_valid(): jawab_form.save() messages.success(request, 'Anda berhasil menjawab kuisioner') else: messages.error(request, 'Anda gagal menjawab kuisioner') else: jawab_form = JawabanForm(instance=request.user) return render(request, 'survey/kuisioner.html', {'jawab_form':jawab_form}) models.py from django.db import models from django.contrib.auth.models import User class Kuisioner(models.Model): judul = models.CharField(max_length=255) alias = models.SlugField(max_length=255, unique=True) class Meta: ordering = ['judul'] def __str__(self): return self.judul class Pertanyaan(models.Model): kuisioner = models.ForeignKey(Kuisioner, related_name='pertanyaans', on_delete=models.CASCADE) pertanyaan = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.pertanyaan class Jawaban(models.Model): pertanyaan = models.ForeignKey(Pertanyaan, related_name='jawabans', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) jawab = models.PositiveIntegerField() urls.py inside survey app from django.urls import path, include from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('kuisioner/', views.get_pertanyaans, name='get_pertanyaans') ] urls.py in my project urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('account.urls')), path('survey/', include('survey.urls')), ] forms.py from django … -
many attributes in manyTomanyField does not have a attribute called .all() |Help needed Beginner|
I have created a model named Flight which is connected to another model named Passengers flights = models.ManyToManyField(Flight, blank=True, related_name="passengers") i tried to use Passengers = Flight.Passengers.all() it throws an error saying that Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' need help with it! i want only the realted fields from flight and passengers into my html but it throw an error whenever i try to access using Flight.Passengers.all() and Flight.Passengers.get() it can be bypass using Passengers.objects.all() but i don't need that otherwise there will be no relation between my databases! -
Django SessionWizardView weird behaviour
I'm trying to build a SessionWizardView used to create an instance of my model Servizio, with 3 different steps/ModelForms. class ServizioWizard(SessionWizardView): template_name = 'core/wizard_form.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'wizard_storage')) form_list = [ServizioModelForm1, ServizioModelForm2, ServizioModelForm3] def get(self, *args, **kwargs): print(f"{self.get_form().fields=}") return super().get(*args, **kwargs) def post(self, *args, **kwargs): print("step before super().post():", self.steps.current) print("POST data:", self.request.POST) response = super().post(*args, **kwargs) print("step after super().post():", self.steps.current) return response def render_revalidation_failure(self, step, form, **kwargs): print(f"{form.errors=}") print(f"{step=}") return super().render_revalidation_failure(step, form, **kwargs) def done(self, form_list, **kwargs): print("done?") print(f"{self.request.POST=}") s = process_widard_forms_data(form_list) s.hub = self.request.user.referente.hub s.save() return redirect('core:home') def get_context_data(self, form, **kwargs): ctx = super(ServizioWizard, self).get_context_data(form=form, **kwargs) print(f"{self.request.session.keys()=}") print(f"{self.request.session['wizard_servizio_wizard']=}") r = self.request.user.referente ctx['referente'] = r ctx['hub'] = r.hub return ctx The issue I'm meeting is that whenever I load the first of those steps, I get the following output in my console: self.get_form().fields={'nome': <django.forms.fields.CharField object at 0x706f84fe6800>, 'tipo': <django.forms.fields.TypedChoiceField object at 0x706f84fe6650>, 'categoria': <django.forms.models.ModelChoiceField object at 0x706f84fe6a40>, 'descrizione': <django.forms.fields.CharField object at 0x706f850289a0>, 'informazioni': <django.forms.fields.CharField object at 0x706f85028b20>} self.request.session.keys()=dict_keys(['_auth_user_id', '_auth_user_backend', '_auth_user_hash', 'wizard_servizio_wizard']) self.request.session['wizard_servizio_wizard']={'step': '0', 'step_data': {}, 'step_files': {}, 'extra_data': {}} [09/Feb/2024 11:16:05] "GET /crea-servizio/ HTTP/1.1" 200 131264 self.get_form().fields={'nome': <django.forms.fields.CharField object at 0x706f850295a0>, 'tipo': <django.forms.fields.TypedChoiceField object at 0x706f85029120>, 'categoria': <django.forms.models.ModelChoiceField object at 0x706f85028ca0>, 'descrizione': <django.forms.fields.CharField object at 0x706f850293c0>, 'informazioni': <django.forms.fields.CharField object at … -
I am using Django Admin action but I want to use it in modal form
I am new to django and I am using Django admin actions which gives us action admin action dropdown. I am using django-admin-actions 0.1.1 I created view # views.py from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML, CSS from .models import StudentEnrollment # Django actions def generate_enrollment_form_pdf(request): # Query Student Enrollment data enrollments = StudentEnrollment.objects.all() # Render HTML template with data html_string = render_to_string('enrollment_form.html', {'enrollments': enrollments}) # Create PDF from HTML with A5 size pdf_file = HTML(string=html_string).write_pdf(stylesheets=[CSS(string='@page { size: A6; }')]) # Return PDF response response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="enrollment_form.pdf"' return response # Django actions over and setup urls.py # urls.py from django.urls import path from .views import * urlpatterns = [ path('generate-enrollment-pdf/', generate_enrollment_form_pdf, name='generate_enrollment_pdf'), ] In admin.py I create a function for my plan execution xD # Function for Prep Enrollment Print def print_enrollment_form_pdf(modeladmin, request, queryset): # Query Student Enrollment data enrollments = queryset # Render HTML template with data html_string = render_to_string('enrollment_form.html', {'enrollments': enrollments}) # Create PDF from HTML pdf_file = HTML(string=html_string).write_pdf() # Return PDF response response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="enrollment_form.pdf"' return response print_enrollment_form_pdf.short_description = "Print Enrollment Form PDF" and then i call that action in my modalAdmin @admin.register(StudentEnrollment) class … -
Django THOUSAND_SEPARATOR issue
I want to display my numbers in the template (Frontend) in the following format: 1.000.000 # for one million 0,5 # for 1/2 This is my current setting: LANGUAGE_CODE = "es-cl" USE_I18N = True USE_L10N = True NUMBER_GROUPING = 3 USE_THOUSAND_SEPARATOR = True THOUSAND_SEPARATOR = "." DECIMAL_SEPARATOR = "," The thousands separator is not used.. Why? My browser language is Spanish and I am currently in Germany. Maybe that has an effect? but the LANGUAGE_CODE should have precedence or not? But currently this is the output: 1 000 000 # for one million 0,5 # for 1/2 I am using django 4.2.9 with python 3.8 -
django migrate with clickhouse
I have a project with two databases: PostgreSQL and Clickhouse. To interact with Clickhouse, I use the django-clickhouse-backend lib. For a long time, I did not use the created migrations for this database, but created tables using raw SQL. Now it's time to apply all the previous migrations, but I ran into a problem. To avoid all conflicts, I had to significantly edit the existing migration files, after that I locally modeled and checked the application of these migrations in the existing database and everything was OK. But when I tried to apply these migrations on the production server, I got the following error: # python manage.py migrate --database clickhouse --fake-initial Operations to perform: Apply all migrations: admin, auth, authtoken, celery_app, contenttypes, django_dramatiq, edl, sessions, users Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/dbapi/cursor.py", line 111, in execute response = execute( ^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_backend/driver/client.py", line 53, in execute rv = self.process_ordinary_query( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/client.py", line 571, in process_ordinary_query return self.receive_result(with_column_types=with_column_types, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/client.py", line 204, in receive_result return result.get_result() ^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/result.py", line 50, in get_result for packet in self.packet_generator: File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/client.py", line 220, in packet_generator packet = self.receive_packet() ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/clickhouse_driver/client.py", line 237, in receive_packet raise packet.exception … -
Upload issue in Django
Please can someone help with an issue i'm having in Django? I've created a recipe app for a course project and want the user to upload images. I've set the model up and when I upload an image from the django admin page it works perfectly, however when I try and upload an image from the user interface, it doesn't work and it should be using the same model. The other CharField, TextField and IntergerField all work but not the ImageField and I don't know why. There is also a default no_picture.jpg however it doesn't use that either. when the Img works the url shows as and when it doesn't the /recipes/ is missing from the URL However I don't think there is an issue with my urlpatterns as the other data works its just the image. Here is the models.py class Recipe(models.Model): name = models.CharField(max_length = 120) cooking_time = models.IntegerField(help_text = 'in mintues', default = 0 ) ingredients = models.CharField(max_length = 300) description = models.TextField() pictures = models.ImageField(upload_to = 'recipes', default = 'no_picture.jpg') forms.py class CreateRecipeForm(forms.Form): name = forms.CharField(max_length=50, required=False) cooking_time = forms.IntegerField(help_text='in minutes', required=False) ingredients = forms.CharField(max_length=300, required=False) description = forms.CharField(max_length=500, required=False) pictures = forms.ImageField(required=False) views.py @login_required def … -
ValueError at (url) seek of closed file in Django app
I am trying to add an image processing library inside a webodm django app that takes input image path, output directory path. I do not want to save the input image inside the database so I was implementing the image processing on the fly. I end up getting: ValueError at /plugins/diagnostic/ seek of closed file here is part of my view that handles the image processing: def vegetative_indices_view(request): print(cv2.__version__) if request.method == 'POST': form = VegetativeIndicesForm(request.POST, request.FILES) if form.is_valid(): uploaded_image = form.cleaned_data['input_image'] # Read the uploaded image into memory uploaded_image.seek(0) image_data = uploaded_image.read() uploaded_image.close() # Create an in-memory file-like object for the image in_memory_file = BytesIO(image_data) in_memory_file.name = uploaded_image.name # Normalize the uploaded image normalized_image = normalize(Image.open(in_memory_file)) # Call the vegetative indices calculation logic indexes = calculate_vegetative_indices(normalized_image) return render(request, self.template_path('vegetative_indices_results.html'), {'indexes': indexes}) else: form = VegetativeIndicesForm() return render(request, self.template_path("vegetative_indices.html"), {'form': form}) and in the terminal the error is printed like so: webapp | return func(*args, **kwargs) webapp | ValueError: seek of closed file What could be the issue here where the image file is prematurely closed? -
Can not access the values of dictionary using jinja
Here is my views.py def following(request): currentUser = User.objects.get(pk=request.user.id) currentUser_followings = Following_System.objects.get(user=currentUser).following allPosts = Post.objects.all().order_by("-timestamp").reverse() followingPosts = [] for user in currentUser_followings.all(): for post in allPosts: if post.author == user: followingPosts.append(post) **post_likers_ids = {post.id: list(post.likers.values_list('id', flat=True)) for post in followingPosts}** # Show 10 posts per page. paginator = Paginator(followingPosts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/following.html",{ "page_obj": page_obj, "post_likers_ids" : post_likers_ids }) I debug, and the post_likers_ids return: ({4: [2], 2: [1,3,5]}) And now in my following html why the if condition is always false (Although it should be true for some, cause I know the expected input output): {% for post in page_obj %} <div class="list-group-item"> {% with post_id=post.id %} {% if user.id in post_likers_ids.post_id %} <p>The user liked this </p> {% else %} <p>The user have not liked this </p> {% endif %} {% endwith %} </div> {% endfor %} Here is my model if that helps: class Post(models.Model): content = models.TextField(blank=False) author = models.ForeignKey("User", on_delete=models.CASCADE, related_name="author") timestamp = models.DateTimeField(auto_now_add=True) likers = models.ManyToManyField("User", related_name="liked_posts", blank=True) def serialize(self): likes_count = self.likers.count() # likers = [user.id for user in self.likers.all()] return { "id": self.id, "content": self.content, "author": self.author.username, "author_id": self.author.id, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "likes": … -
Django Fulltext search is very slow how to make it fast?
I possess an extensive database of products and aim to implement full-text search functionality to enable users to easily search for products. I've employed SearchVector with Postgres for this purpose; however, the performance is quite sluggish. Despite attempting to enhance speed through indexing, it hasn't yielded the desired results. Below is a snippet of the code I've been working with. models.py class Product(models.Model): brand = models.ForeignKey(BrandName,related_name="brand_products", on_delete=models.CASCADE,db_index = True) item_name_title = models.CharField(max_length=10000, db_index = True,) product_description = models.TextField(db_index = True,) class Meta: indexes = [ GinIndex(fields=['search_vector']), ] Views.py search = request.GET.get('search') search_vector = SearchVector( 'product__mob_sku', 'product__item_name_title', 'product__product_description', 'product__brand__brand_name', ) query = SearchQuery(search) vendor_products = VendorProducts.objects.annotate( rank = (SearchRank(search_vector , query)) ).filter(rank__gte=0.001).select_related( 'vendor', 'product').prefetch_related( 'product__product_images', 'product__brand').exclude( vendor__vendor_name = "ALL_123").order_by('-rank') -
Django: Handling Expired API Keys Without Signals
Title: Django: Handling Expired API Keys Without Signals Question: How can I implement a logic in Django to automatically delete expired API keys from the OutstandingKey model and update the corresponding BlacklistedKey entry when the expiry date has passed, without using signals? I have two Django models: OutstandingKey and BlacklistedKey. The OutstandingKey model represents API keys generated by users, including an expiry date field. The BlacklistedKey model stores blacklisted API keys, referencing the OutstandingKey through a one-to-one relationship. I want to create a system where expired API keys are automatically removed from the OutstandingKey model and added to the BlacklistedKey model when their expiry date has passed. However, I prefer not to use signals for this implementation due to this Django Anti-Pattern. Could someone provide a blueprint or example of how to achieve this logic within Django?. Below is my Models from django.db import models from django.conf import settings from django.utils import timezone class OutstandingKey(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, default=None, verbose_name="User", ) name = models.CharField(max_length=1000, default="", blank=True, null=True) api_key = models.CharField( max_length=1000, unique=True, verbose_name="API Key", default="", blank=True, null=True, editable=False, ) expiry_date = models.DateTimeField( default=None, verbose_name="Expiry Date", blank=True, null=True ) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class … -
How to make the price of the product to be dynamically changed in Django?
I'm using Django framework. I've addded product variants like size, color and glass. Now, I need the price to be dynamically changed with selecting product options. The price doesn't change when I'm choosing different options of the product, it remains the same. Here is my ajax part: $('#size, #color, #glass').on('change', function () { const productId = $('#product-id').val(); const sizeId = $('#size').val(); const colorId = $('#color').val(); const glassId = $('#glass').val(); console.log("Selected values:", productId, sizeId, colorId, glassId); // Log captured values if (productId && sizeId && colorId && glassId) { calculateUpdatedPrice(productId, sizeId, colorId, glassId); } }); function calculateUpdatedPrice(productId, sizeId, colorId, glassId) { const url = `/get_variant/?product_id=${productId}&size=${sizeId}&color=${colorId}&glass=${glassId}`; console.log("Fetching price from URL:", url); // Log request URL fetch(url) .then(response => response.json()) .then(data => { console.log("Response data:", data); // Log server response const priceElement = document.getElementById('price'); const sellPriceElement = document.getElementById('sell-price'); priceElement.textContent = data.price; sellPriceElement.textContent = data.price; }) .catch(error => console.error('Error:', error)); } And product detail : {% for variant in product.variants.all %} <p>Size: {{ variant.size.name }}</p> <p>Color: {{ variant.color.name }}</p> <p>Glass: {{ variant.glass.name }}</p> <p>Price: <span id="price">{{ variant.price }}</span></p> {% endfor %} <div class="mb-3"> <strong><label for="size" class="form-label">Ölçü:</label></strong> <div class="dropdown-wrapper" style="width: 120px;"> <select class="form-select" id="size"> {% for size in sizes %} <option value="{{ size.id }}">{{ size.name … -
Create another object when I create an object in django model
When i create an object like: bus_stop_1 = 4(Foreign Key) bus_stop_2 = 7 then it should automatically create other object with bus_stop_1 = 7 bus_stop_2 = 4 ** time and distance would be the same ** BusStop is an model My model class ConnectedRoute(models.Model): bus_stop_1 = models.ForeignKey( BusStop, on_delete=models.CASCADE, related_name='stop1') bus_stop_2 = models.ForeignKey( BusStop, on_delete=models.CASCADE, related_name='stop2') distance = models.FloatField(blank=True, null=True) time = models.TimeField(blank=True, null=True) I have tried this my using save method and saving the ConnectedRoute but it been called recursively again and again. def save(self, *args, **kwargs): # Check if the object is being created for the first time if not self.pk: # Create a new ConnectedRoute object with reversed bus stops reverse_connected_route = ConnectedRoute( bus_stop_1=self.bus_stop_2, bus_stop_2=self.bus_stop_1, distance=self.distance, time=self.time ) reverse_connected_route.save() # Save the reversed object super().save(*args, **kwargs) -
Django Channels - Sending message to multiple channels
I created a room dict which which stores channels of consumers which belong to a specific group, now when any consumers sends a message i want all the channels to get that message ... but I only know self.send function to send message how do i send message to all channels. Channels are stored in the following way : from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class MyWebsocketConsumer(WebsocketConsumer): room = {} def connect(self): print("Connected...",self.channel_name) self.group_name = self.scope['url_route']['kwargs']['group_name'] print('Group Name...',self.group_name) try: if self.room[self.group_name]: self.room[self.group_name].append(self.channel_name) except: self.room[self.group_name]= [self.channel_name] self.accept() print(self.room) def receive(self, text_data=None, bytes_data=None): # Help with logic here pass def disconnect(self, close_code): self.room[self.group_name].remove(self.channel_name) -
django using drf-spectacular, I cannot customize schema with @extend_schema decorator
I have the following view: class ReferralCodeList(generics.ListCreateAPIView): queryset = ReferralCode.objects.all() serializer_class = ReferralCodeSerializer def get_queryset(self): queryset = super().get_queryset() queryset = queryset.filter(user=self.request.user) return queryset @extend_schema( description='More descriptive text', ) def create(self, request, *args, **kwargs): request.data['user'] = request.user.id serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) if 'send_mail' in request.data.keys() and \ request.data['send_mail'] == True: send_mail( "Your referral code", serializer.data['code_str'], project_settings.EMAIL_HOST_USER, [request.user.email], fail_silently=False, ) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I execute ./manage.py spectacular --color --file schema.yml But I don't see any changes to the view's description. When I change the serializer, I see the respective changes in swagger page. What am I doing wrong? Thanks -
Heroku logging for django management commands
I would like to log statements when running a Django management command on Heroku. So, for example, when I login to Heroku and run the command: heroku run bash python manage.py my_management_command I should see all of the logging.info statements included. But instead they don't appear in the Heroku logs. All logging.info statements from the normal django appear fine, just not when I run a management command. My logger setup in settings.py is as follows: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'mylogger': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, 'formatters': { 'verbose': { 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s' }, }, } Can anyone tell me how to get log statements from inside my django management command to appear in the heroku logs? -
django using APIView can't override default djangorestframework permission classes
I'm trying to add swagger to my app, like stated here: https://django-rest-swagger.readthedocs.io/en/latest/schema/#advanced-usage So I've added this: class SwaggerSchemaView(APIView): permission_classes = [AllowAny] renderer_classes = [ renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer ] def get(self, request): generator = SchemaGenerator() schema = generator.get_schema(request=request) return Response(schema) I have the following lines in my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } When I go to swagger url, I get this: HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "Authentication credentials were not provided." } But I am expecting permission_classes to override the default ones. What am I doing wrong? Thank you -
How can I resolve ModuleNotFound Error in Django?
I have been working on a Django project for some time now. However, I am unable to resolve this error when I start the development server: Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/chanakgautam/PycharmProjects/djangoProject/venv/lib/python3.8/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'scraper_app' Based off previous posts I've read, I suspected the issue could lie in my file structuring. But my structure (below) appears to be alright. djangoProject [**scraper**] ├── djangoProject │ ├── __init__.py │ ├── asgi.py │ ├── scraper_app │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── templates │ ├── results.html │ └── search.html └── … -
How to Embed google review in Django website?
I was going through the Google Cloud Platform Console to find out how I could embed a Google review on my Django website. I found the Google Places API to be the most relevant (not quite sure), but then I got lost with all the details, pricing, and different tiers. My case is actually quite simple. I just want to display the total number of stars a specific place has. Is there a free way to get that, which I didn't understand? -
Portable windows app built with electron-builder takes too long to start up
I have used electron-builder to package my React + Django application into a single executable file. When I build the app, the resulting dist folder contains: -- dist (folder generated after building the app with electron) | |- MyApp0.0.1.exe (portable exe file) | |- win-unpacked | | | |-MyApp.exe | |-multiple_folders (dependencies of the MyApp.exe) | |-multiple_files (dependencies of the MyApp.exe) The problem is the following: When runnning the MyApp.exe inside the win-unpacked folder, and as long as the dependency files/folders are at the same level, the app works perfectly fine and takes less than a second to startup and display. It even asks for admin password, as in the package.json config it is specified to build it with "requestedExecutionLevel": "highestAvailable". When running the MyApp0.0.1.exe which is supposed to be the portable, standalone .exe file for the application, although it does run perfectly fine, it takes up to 6 minutes to start-up and display the app. I have tried skimming down the project as much as possible in terms of the node_modules that I need, removing large data files not needed, ... I am clueless as to why this is happening. I am not a web-dev expert in any way … -
Custom Admin Site in Django
I have problem to change title_header, site_header, index_title in custom admin site. My admin.py: from reviews.models import Movie, MovieCasts, Review, Actor class CritiflixAdminSite(AdminSite): title_header = 'Aplikacja administracyjna Critiflix' site_header = 'Aplikacja administracyjna Critiflix' index_title = 'Administracja witryną Critiflix' movie_admin_site = CritiflixAdminSite(name='critiflix') movie_admin_site.register(Movie) movie_admin_site.register(MovieCasts) movie_admin_site.register(Review) movie_admin_site.register(Actor) My urls.py: from django.urls import include, path from . import views urlpatterns = [ path('admin/', movie_admin_site.urls), path('movies/', views.movie_list, name = 'movie_list'), path('movies/<int:pk>', views.movie_detail, name = 'movie_detail'), path('', views.base, name = 'base') ] When i run manage.py nothing is change and models aren't on panel. -
Sending and receiving custom signals in Django and ensuring it is atomic
I want to create a custom signal and send the signal after some database operations. The receiver also performs database operations. I want to make sure all the database operations before sending the signal and in the signal, receiver is atomic meaning either all fail, or all succeed. Consider the following code: def send_my_signal(): # Database operation 1 # Database Operation 2 my_signal.send(sender=MyModel) The receiver: @receiver(my_signal) def my_receiver(sender, **kwargs): # Database operation 3 # Database operation 4 I want either all database operations 1 to 4 succeed or fail together. By asking from generative AI models, one proposed solution is to wrap the body of the function that performs database operations and sends the signal inside the transaction.atomic() context manager. So, the code would look like this: def send_my_signal(): with transaction.atomic(): # Database operation 1 # Database Operation 2 my_signal.send(sender=MyModel) But I could not find any resource or anything in Django documentation confirming this. It's not like I am calling the receiver of the signal inside the transaction.atomic() context manager, I am just sending the signal there.