Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reference newrelic keys via settings.py
I am just using NewRelic for the first time. I have the new relic.ini file, which includes the license_key and app_name hard coded, in my Django Python repository and have updated my manage.py script to be as so: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import newrelic.agent newrelic.agent.initialize('newrelic.ini') import os import sys def main(): ..... if __name__ == '__main__': main() When I run my api locally via ./manage.py runserver I can see the logs being tracked in NewRelic which is good. However, I'm wanting to remove the hardcoded license_key and app_name from the newrelic.ini file so that I can reference environment variables. I have read this documentation https://docs.newrelic.com/docs/apm/agents/python-agent/configuration/python-agent-configuration/#server-side-configuration which outlines the environment and config variables. I added this to my settings.py file so that I can override the env variables on deployment: NEW_RELIC_APP_NAME = "My API" NEW_RELIC_LICENSE_KEY="XXXXXXXXXXXXXXXX" I have tried removing license_key and app_name entirely from newrelic.ini keeping the variables but setting them equal to "" keeping the variables but setting license_key = NEW_RELIC_LICENSE_KEY but I can't seem to get it tracking without it being hardcoded in the newrelic.ini file So my question - how can I use environment variables with the newrelic.ini file? thanks in advance -
Using Python to Pull Data from XLSX file stored online
I'm building an app using Django that needs to be able to pull data from sheets stored in an XLSX file. For testing I've used files stored locally, but now that I need to put it online I need to be able to work with files stored online. I've tried working with files stored on SharePoint but haven't been able to work with the raw file. Is there a place these files could be stored where I can access them with Python or a way to make them accessible if stored somewhere like SharePoint? I also have to work with CSV files stored online but was able to do so by adding them to GitHub and accessing the raw file as shown in the image below. Is this possible anywhere for non CSV excel files? -
Django - limit_choices_to users within a group model
I have a group models with members and one admin which looks like this: class Group(models.Model): name = models.CharField(unique=True, max_length=255) members = models.ManyToManyField(User, related_name='members') is_admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, limit_choices_to={'members': True}) I want to show only members which are part of the group to the is_admin field. I tried the limit_choices_to method and referred the members but it is not working when I try to display the users in a form like this: form = EditGroupForm(instance=group). How can I do so? -
DJANGO: Error ninja.errors.ConfigError: Router@'/xxxxxxxx/' has already been attached to API NinjaAPI:1.0.0
I am running a Django application in Docker when I spinup the docker container I get the error Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/utils/deprecation.py", line 94, in __call__ response = response or self.get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception callback, param_dict = resolver.resolve_error_handler(500) File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 597, in resolve_error_handler callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) File "/usr/local/lib/python3.9/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/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 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/repo/repo/repo/urls.py", line 28, in <module> api.add_router("/xxxxx/", xxxxx_router) File "/usr/local/lib/python3.9/site-packages/ninja/main.py", line 367, in add_router self._routers.extend(router.build_routers(prefix)) File "/usr/local/lib/python3.9/site-packages/ninja/router.py", line 366, in build_routers raise ConfigError( ninja.errors.ConfigError: Router@'/xxxxx/' has already been attached to API NinjaAPI:1.0.0 The start script start.sh using gunicorn echo Starting Gunicorn. export … -
Traefik2 as reverse_proxy for Nginx in django production docker-compose
I have managed to build a small Django app some basic things. Localy works all fine and I'd like to start this WebApp on a production server I already have running. On this server are already some docker-compose configurations running were a traefik2 works as a revers_proxy with letsencrypt certifikates. So far so good. As I designed my django project with nginx as static file delivery I'd like to use it and let traefik2 work as revers_proxy in front of nginx. docer-compose.pro.yml version: "3.9" # docker-compose for production # It is important that the .env.prod is used. # For this, docker-compose must always be executed # with the command docker-compose -f docker-compose.pro.yml --env-file .env.prod. services: web: build: context: . dockerfile: ./compose/Dockerfile restart: always command: gunicorn project.wsgi:application --bind 0.0.0.0:8000 env_file: - ./.env.prod expose: - 8000 volumes: - static_volume:/code/staticfiles - media_volume:/code/mediafiles depends_on: - redis - db networks: - pjnet db: image: postgres:15 restart: always volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=${DB_USERNAME} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} networks: - pjnet redis: image: redis:7 networks: - pjnet celery: build: context: . dockerfile: ./compose/Dockerfile restart: always command: celery -A project worker -l info volumes: - .:/code env_file: - ./.env.prod depends_on: - db - redis - web networks: … -
Django can not send mail but smtplib can
I was trying to use django's accounts system and configured some templates. When i tried to do password reset it said "SMTPRecipientsRefused at /accounts/password_reset/". But it works when i send an email with smtplib. In django settings: # EMAIL EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "mail.X.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "X@mydomain" EMAIL_PASSWORD = "password" And the error: Exception Type: SMTPRecipientsRefused at /accounts/password_reset/ Exception Value: {'X@gmail.com': (450, b'4.7.1 We do not relay gmail.com')} But i knew i used the same mail before with smtplib and tried again, and it worked. >>> import smtplib >>> from email.message import EmailMessage >>> mail_server = "mail.X.com" >>> mail_username = "X@mydomain" >>> mail_password = "password" >>> mail_port = 587 >>> msg = EmailMessage() >>> msg["Subject"] = "subject test" >>> msg["From"] = mail_username >>> msg["To"] = "X@gmail.com" >>> server = smtplib.SMTP(mail_server, mail_port) >>> server.login(mail_username, mail_password) (235, b'2.7.0 Ok') >>> server.send_message(msg) {} >>> server.quit() (221, b'2.0.0 Bye') I tried adding DEFAULT_FROM_EMAIL = "X@mydomain" to the settings.py but it didn't make any difference. I tried adding EMAIL_USE_TLS=True but it said: SSLCertVerificationError at /accounts/password_reset/ [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'mail.X.com'. (_ssl.c:1131) -
How to run both react and django on https
I had a react+django app. The react app was on http://my.domain.com, and it called the django app that is on http://my.domain.com:8000. Now, I have installed an SSL certificate and changed the react app to run on https://my.domain.com. However, whenever it tries to call the django app on http://my.domain.com:8000, I get an error Blocked loading mixed active content “http://my.domain.com:8000/auth/”. This makes sense, because I really have mixed content: an https page (the react app) tries to call http (the django app). On the other hand, if I change the API call to “https://my.domain.com:8000/auth/”, it does not work at all (it hangs). How can I let django accept calls through SSL, so that I do not get these mixed content errors? -
KeyError: 'room_name' in Django channels
I'm stuck on this KeyError issue. Can anyone advise what's the problem? First I'll show you my code here. class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room await(self.channel_layer.group_add)(self.room_group_name, self.channel_name) await self.accept() routing.py websocket_urlpatterns = [ re_path(r'^ws/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()), ] urls.py path('chat/<str:room_name>/', views.ChatAPIView.as_view()) and The Error is - KeyError: 'room_name'. I referred to the Django docs, but the difference is I used ApiView in views.py. I'm using this project for an android project as a server. Need to be fixed the KeyError. -
Django relative_name issues on model Inheritance
I have an issus with inheritance on models and reverse relations. Here my models : class A(B): designation = CharField() class B (): owner = ForeignKey(A, null=True, blank=True, related_name='sites') name = CharField() street1 = CharField() class C(): name = CharField() relation_a = ForeignKey(A, related_name='all_elements', null=True, blank=True) relation_b = ForeignKey(B, related_name='elements', null=True, blank=True) Firstly my model A inherits from the model B for get all address informations.Model A can have several sites(B) I have an other model C with foreign key to model A and another to model B. For each element B I want get all elements. This work fine: for b in B.objects.all(): print(b.elements.all()) For get all elements link to A is work: print(A.all_elements.all()) But I can't get just the element C linked to A by the relation_b print(A.elements.all()) I got an empty list. If I want only this element I need to pass by B models B.objects.get(id=A.id).elements.all() This is the first issues. Secondly, my main problem is with serializer. My serializer : A_Serializer(B_Serializer): class Meta: model = A fields = [ 'designation', 'street1', 'site', 'all_elements', 'elements', ] expandable_fields = { 'sites': (B_Serializer, {'many'=True} 'all_elements': (C_Serializer,{'many':True}), 'elements': (C_Serializer,{'many':True}), } In DRF I can expend the all_elements in serializer A. … -
csv download is not including all the results in a django application
im trying to build a web app with python and django, in this application a user can enter a list of websites, the results will show the website status, the website title, the website summary, the email, the phone number, facebook and instagram links if present. At the end the user can download the results as csv, btw the csv is showing only 1 result, and even incomplete (the website, the phone, the email, fb and instagram are missing). What am i doing wrong? here is the main file # website_checker/checker/views.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.shortcuts import render, HttpResponse from django.urls import reverse import requests from bs4 import BeautifulSoup from .utils import get_business_summary, extract_emails, extract_phones, extract_social_media_links import spacy import re import csv import io # Function to get a business summary from the text def get_business_summary(text): nlp = spacy.load('en_core_web_sm') doc = nlp(text) sentences = [sent.text.strip() for sent in doc.sents] business_summary = '' for sent in sentences: # You can add more conditions to extract business-specific information from the text if 'business' in sent.lower() or 'company' in sent.lower(): business_summary = sent break return business_summary # Function to extract emails from the text def extract_emails(text): # Use … -
Error when trying to delete model instance in Django 4.2.2
I've been trying to delete an existent instance from the user table (mysql) but I keep getting error from the user.delete() this is the my viewpoint: @api_view(['GET', 'PUT', 'DELETE']) def user_api_id(request): try: id = request.GET.get('id') user = User.objects.get(pk=id) if request.method == 'GET': serializer = UserSerializer(user) return Response(serializer.data) elif request.method == 'PUT': serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': try: user.delete() return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as ve: return Response({"error": str(ve)}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) When I launch a DELETE request I get this: "error": "(1292, \"Truncated incorrect DOUBLE value: 'john'\")" (btw the user I want to delete has id='john') This is my User model: class User(models.Model): id = models.CharField(primary_key=True, max_length=50) password = models.CharField(max_length=50) name = models.CharField(max_length=25) lastname = models.CharField(max_length=25) age = models.IntegerField() gender = models.CharField(max_length=6) email = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=50, blank=True, null=True) address = models.CharField(max_length=50, blank=True, null=True) educationallevel = models.CharField(db_column='educationalLevel', max_length=50, blank=True, null=True) # Field name made lowercase. experience = models.CharField(max_length=20, blank=True, null=True) is_active = models.BooleanField(default=True) is_anonymous = models.BooleanField(default=False) is_authenticated = models.BooleanField(default=True) USERNAME_FIELD = 'id' REQUIRED_FIELDS = [] class Meta: managed = False db_table = 'user' And this is the … -
DRF Spectacular - @extend_schema subclass method for Serializers
Im using DRF_SPECTACTULAR to generate swagger DOC from my DRF Project. I have a GenericViewSet that implement CRUD methods. Over each ones, I have extend_schema decorator. Take this one as example: @extend_schema( # extra parameters added to the schema parameters=[ OpenApiParameter(name = "jwt_token", description="JSON Web Token", required=True, type=str), OpenApiParameter(name = "id", type = OpenApiTypes.STR, location=OpenApiParameter.PATH , description = "ID "), ], methods=["GET"], description = 'Return a serialized User', request = JWTRequestSerializer, responses = { 200: GenericResponseSerializer }, ) def retrieve(self, request, pk=None): I Have a lot of ViewSet for every Models that extends the Generic and override some methods to make it specific for the model. I need something like this for the Serializer in extend_schema. In the example, I have GenericResponseSerializer but I need every subclasses that extends this SuperClass, return its own specific Serializer. I've tried with a static method: @staticmethod def getRetrieveSerializer(): return GenericResponseSerializer() ... responses = { 200: getRetrieveSerializer }, ... It works well but it always return the SuperClasses method even if Im extending it. Unfortunally in decorator, I cant access self so I cant use a method that is overwritten at runtime. Is there a way to reach this goal? Maby with reflection? -
Django is not sending POST request
I am building a simple web app with Django and got into this weird situation. I want to delete an entry of a model but the html won't send any post request. delete.html {% extends 'main.html' %} {% block content %} <form method="POST" action=""> {% csrf_token %} <p> Are you sure to delete "{{obj}}" ?</p> <a href="{{request.META.HTTP_REFERER}}">GO BACK </a> <input type="submit" value="Confirm"> </form> {% endblock %} View for delete.html in views.py def delete_room(request, pk): room = Room.objects.get(id=pk) if request.method == 'POST': room.delete() return redirect('home') return render(request, 'base/delete.html', {'obj':room}) Model in models.py class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) # participants = created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering = ['-updated', '-created'] urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('room/<str:pk>', views.room, name='room'), path('create-room/', views.create_room, name='create-room'), path('update-room/<str:pk>', views.update_room, name='update-room'), path('delete-room/<str:pk>', views.delete_room, name='delete-room'), path('about/', views.about, name='about'), ] I've tried sending POST request from other templates and it woorks fine like adding new rooms and updating existing ones. When I click on Confirm, it shows nothing in terminal. -
Issue with swagger docs in django views
I have a view in my django project like this class SampleView(MixinPermissionsByAction, MixinSerializerByAction, generics.ListCreateAPIView): serializer_class = SampleCreateSerializer permission_classes = (IsAuthenticated) permissions_by_action = {"POST": (SomePermission,)} serializer_by_action = {"GET": SampleListSerializer} filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = ["status"] ordering_fields = ["-updated", "-created"] search_fields = [ "name", ] queryset = None throttle_classes = [SomeThrottling] def get_queryset(self): <get request logic here....> in my serializers.py class i have two serializers. one for get rquest and other for post request class SampleListSerializer(serializers.ModelSerializer): <some fields here> class Meta: model = MyModelName exclude = <fields to be excluded> class SampleCreateSerializer(serializers.ModelSerializer): <some fields here> class Meta: model = MyModelName fields = "__all__" def create(self, validated_data): <logic for post request> I want to add get and post methods in swagger docs and tried following added @method_decorator above SampleView but it did not worked added @swagger_auto_schema above get_queryset method in view class and create method in SampleCreateSerializer here is my swagger implementation schema_view = get_schema_view( openapi.Info( title="My API", default_version="v1", description="API documentation for MyAI", ), public=True, permission_classes=(permissions.IsAdminUser, ), authentication_classes=(SessionAuthentication, ), ) and in urlpatterns path('docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui') Need help here to implement swagger on my above views. I have tried different stuff that i mentioned above but it did not work. … -
Setting minimum-width in line [Django]
Consider class MyTable(tables.Table): name = tables.Column(attrs={'cell': {'min-width': '200px'}}) Is this the right syntax for setting the minimum width of the 'name' column to 200px? This doesn't work on my machine. The 'name' column doesn't respond to variations in the min-width. -
Why are `connection.wait psycopg` suddenly high?
I noticed that my django tests became slow so I profiled them using pyinstrument. I noticed that connection.wait psycopg/connection.py:949 were taking a lot more time than before. So I focused on profiling this chunk of code that just does 2 queries: def test_foo(self): from pyinstrument import Profiler profiler = Profiler() profiler.start() foos = Foo.objects.filter(status=True) nb_foos = foos .count() first_foo = foos.first() profiler.stop() profiler.print() And the results are: BEFORE: 0.005 foo.py:93 ├─ 0.004 BaseFooQuerySet.first django/db/models/query.py:1050 │ [27 frames hidden] django, inspect, psycopg │ 0.001 Connection.wait psycopg/connection.py:949 └─ 0.001 BaseFooQuerySet.count django/db/models/query.py:597 [6 frames hidden] django AFTER: 0.543 foo.py:62 ├─ 0.275 BaseFooQuerySet.count django/db/models/query.py:597 │ [9 frames hidden] django, psycopg │ 0.274 Connection.wait psycopg/connection.py:949 └─ 0.268 BaseFooQuerySet.first django/db/models/query.py:1050 [10 frames hidden] django, psycopg 0.266 Connection.wait psycopg/connection.py:949 It's 100x slower. It's running on the same python env (python version and requirements). Python 3.11.3 Django==4.2.4 psycopg==3.1.9 psycopg-c==3.1.9 psycopg-pool==3.1.7 The "before" version is using an old commit so obviously something changed in my code then but what could this be to have such an impact on the db connection? -
Django custom filter - to convert datetime
I am working on a Django app and need to show datetime on the UI. the datetime is UTC format and I need to convert it into local timezone of the user. for this I implemented this custom filter in my app from django import template import pytz register = template.Library() @register.filter def convert_to_localtime(value, user_tz): if not value: return value local_tz = pytz.timezone(user_tz) local_time = value.astimezone(local_tz) print("Conversion function",value, local_time) return local_time In the template I am using this custom filter like this {%load custom_filters%} <span class="text-center match-date-time">{{ match.start_time|convert_to_localtime:user_tz}}</span> I can see that the custom filter is executing and converting datetime properly into local timezone as I can see following output for the print statement Conversion function 2023-08-03 17:30:00+00:00 2023-08-03 23:00:00+05:30 But on the UI I still the UTC datetime rather than the converted time. What am I missing? -
Django Edited images not showing up after processing in views
The website allows user to upload an image and will be edited and shown to the user. (learning to use Pillow for image editing). It gives no error in the terminal, the images are getting saved, but not showing up after edit. Is there issue with how the image is generating? Or in the javascript? Terminal also looks fine, showing this: [03/Aug/2023 15:28:32] "GET / HTTP/1.1" 200 1445 [03/Aug/2023 15:28:37] "POST / HTTP/1.1" 200 1521 index.html: <!DOCTYPE html> <html> <head> <title>Image Editor</title> <style> img { max-width: 400px; max-height: 400px; } </style> </head> <body> <h1>Image Editor</h1> <form action="{% url 'edit_image' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="image_file" id="image_file" onchange="previewImage(event)"> <input type="submit" value="Upload and Edit"> </form> <div id="imagePreview"> <h2>Uploaded Image Preview:</h2> <img id="preview" src="" alt="Uploaded Image"> </div> {% if edited_image %} <h2>Edited Image:</h2> <img src="{{ edited_image.url }}" alt="Edited Image"> {% endif %} <script> function previewImage(event) { const fileInput = event.target; const imagePreview = document.getElementById("imagePreview"); const preview = document.getElementById("preview"); if (fileInput.files && fileInput.files[0]) { const reader = new FileReader(); reader.onload = function (e) { preview.src = e.target.result; }; reader.readAsDataURL(fileInput.files[0]); imagePreview.style.display = "block"; } else { preview.src = ""; imagePreview.style.display = "none"; } } </script> </body> </html> views.py: from django.shortcuts import render … -
Time Limit not Working for Django Celery 5.3.1
I am having a trouble with trying time_limit and soft_time_limit feature in celery and django app. import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') app = Celery('server') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.update( task_soft_time_limit=1, task_time_limit=1, ) # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True, ignore_result=True) def debug_task(self): print(f'Request: {self.request!r}') I have this celery configuration. I'm trying time limit config with for celery task in django and run this task. from celery import shared_task from celery.exceptions import SoftTimeLimitExceeded from celery.signals import task_success, task_failure, task_prerun import time from server.celery import app shared_task def scrape(domain: str, route: str = None): try: time.sleep(5) except SoftTimeLimitExceeded: print("Time Limit") @task_prerun.connect(sender=scrape) def scrape_prerun_notifier(task_id=None, task=None, *args, **kwargs): print("From task_prerun_notifier ==> Running just before add() executes") @task_success.connect(sender=scrape) def scrape_success_notifier(sender=None, result=None, **kwargs): print("Success") task_id = sender.request.id @task_failure.connect(sender=scrape) def scrape_failure_notifier(task_id=None, exception=None, *args, **kwargs): print("Failure") How ever, the scrape task always succeed without catching any exception. I've also tried modifying the decorator but it doesn't work either. @app.task(soft_time_limit=1, … -
Choices not being rendered in template
Working in Django. I've added choices and the necessary field in my model. The choices are well populated in the admin site, but not rendered in the template. I've double checked several times and everything seems right so I don't understand why the choices aren't rendered in the template. Could it be related to the CSS? I'm using materialize. I've added the .input-field class and initialized the select element as per the materialize documentation. Nothing changed. This is my code: model: class Grocery(models.Model): """ Model to create a grocery_list """ CATEGORIES = [("groceries", "Groceries"), ("school", "School"), ("hardware", "Hardware"), ("travel", "Travel"), ("gifts", "Gifts"), ("decoration", "Decoration"), ("lifestyle", "Lifestyle"), ("wishlist", "Wishlist")] name = models.CharField(max_length=500, default='My grocery list') category = models.CharField(max_length=20, choices=CATEGORIES, default='Shopping') form: class GroceryForm(forms.ModelForm): """ Form to create a grocery shopping list """ class Meta: model = Grocery fields = ['name', 'category', 'shop', 'item'] template: {% block title %}Create shopping list{% endblock %} {% block content %} <div class="container row"> <div class="col s10 m8 push-s1 push-m2"> <h1 class="center-align">Create a grocery shopping list</h1> <div class="divider"></div> <div class="input-field section"> <form method="POST"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button type="submit" class="waves-effect btn">Create list</button> </form> </div> </div> </div> {% endblock %} JS // … -
TinyMCE data setting issue
Actually i am trying setup data in tinyMCE editor. But, before the tinyMCE editor gets its initialization, function which set data in tinyMCE calls. So, when tinyMCE is loaded, it is with null data. Actually in one page i have around 10-12 editors. At first i started directly form data to load into tinyMCE from serverside in python django. But, it generates missing of data in some of the last editors. So, I decided to set data from client side through javascript. But I could not able to handle that my data setting function call, after the initialization of tinyMCE. So, please help to handle missing data in some of editors. -
celery running issue on raliway
inside the Procfile of my django app im using this worker: celery -A project.celery worker (using Redis as broker) and using railway platform for hosting my application but after deployment application is crashing : error is something like this : /opt/venv/lib/python3.9/site-packages/celery/platforms.py:800: RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended! Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format( suggest how to run the celery process efficiently on railway. -
ModuleNotFound error (Django), i am beginner in django
It was all working when i started the server first time without startapp. after i made an application and did some modifications in the application now the server is not starting. they only changes I made in views.py and urls.py Here is the log. PS E:\CS50\files\Django\demo> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Abdul Basit Khan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File … -
Formatting form's film with Boostrap and Django
I have a form which is generated by a model in Django made by text area, choice field, toggle field and so on like: class Test(models.Model): workerID = models.CharField(max_length=200, blank=True, null=True) dashboardURL = models.URLField(blank=True) centralinaVecchia = models.BooleanField(default=False) And I've styled the form with class StartWorker(ModelForm): class Meta: model = Test fields = ('testTitle', 'testDescription', 'centralinaVecchia') labels = { "testTitle": _("Titolo"), "testDescription": _("Descrizione"), "centralinaVecchia": _("Centralina Vecchia?"), } widgets = { 'testTitle': forms.TextInput(attrs={'class':'form-control'}), 'testDescription': forms.Textarea(attrs={'class':'form-control'}), 'centralinaVecchia': forms.CheckboxInput(attrs={'class':'form-check-input'}), The issue is that, if every single field is correctly formated one below the other, the check box is located in a weired way (see screenshot) I'm unabel to style it like the rest of the form. According to the documentation I need to add the checkbox inside a <div class="form-check"></div> but I do not know how to do it in Django -
Django - Gentella Theme
¿How can I create a new app on the django template called "Gentella"? I've tried searching and I' ve not found anything yet. Please help me!!. I know how to create a new app on django, but, the question is that when you create that app, you don' t see it on the panel in the UI of gentella. What I'm doing wrong?