Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named ' '
I am attempting to run python manage.py runserver and I am getting a ModuleNotFoundError: No module named ' ' The entirety of the output can be seen here: (venv) danieljohnson@MACHPXNV2CL2Y project % python manage.py runserver /Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/tzwhere/tzwhere.py:62: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray. self.timezoneNamesToPolygons[tzname] = WRAP(polys) Traceback (most recent call last): File "src/gevent/greenlet.py", line 906, in gevent._gevent_cgreenlet.Greenlet.run File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 51, in inner_run http_consumer=self.get_consumer(*args, **options), File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 157, in get_consumer return StaticFilesConsumer() File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/handler.py", line 347, in __init__ self.handler = self.handler_class() File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/staticfiles.py", line 18, in __init__ super(StaticFilesHandler, self).__init__() File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/handler.py", line 194, in __init__ self.load_middleware() File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 56, in load_middleware mw_class = import_string(middleware_path) File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/opt/homebrew/Cellar/python@3.9/3.9.12/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 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", … -
Unexpected keyword argument incoming allow when trying to create Twilio Audio ChatRoom
Following this tutorial to build a drop-in-audio chat application using Django, React and Twilio Programmable Voice. When I carry out GET request using fetch to create a chatroom, I get the error: Response {type: 'cors', url: 'http://127.0.0.1:8000/voice_chat/token/Emmanuel', redirected: false, status: 500, ok: false, …} and in my server: TypeError: __init__() got an unexpected keyword argument 'incoming_allow' This is the fetch function in my frontend: const handleSubmit = e => { e.preventDefault(); const nickname = state.nickname; setupTwilio(nickname); history.push('/rooms'); } const setupTwilio = (nickname) => { console.log('inside setupTwilio function', nickname) fetch(`http://127.0.0.1:8000/voice_chat/token/${nickname}`) .then(response => { console.log('resp', response) }) the API end-point I am interacting with: path('voice_chat/', include('voice_chat.urls')) urls.py containing voice_chat.urls: urlpatterns = [ path("rooms", RoomView.as_view(), name="room_list"), path("token/<username>", TokenView.as_view(), name="rooms"), ] Here is my TokenView: class TokenView(View): def get(self, request, username, *args, **kwargs): voice_grant = grants.VoiceGrant( outgoing_application_sid=settings.TWIML_APPLICATION_SID, incoming_allow=True, ) access_token = AccessToken( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY, settings.TWILIO_API_SECRET, identity=username ) access_token.add_grant(voice_grant) jwt_token = access_token.to_jwt() return JsonResponse({"token": jwt_token.decode("utf-8")}) -
Limitar 4 dados no return da função [closed]
Can I limit view for return 4 objects? @login_required(login_url='/login/') def lista_colaboradores(request): usuario = request.user colaborador = Colaborador.objects.filter(local_adm=usuario) dados = {'colaboradores':colaborador} return render(request, 'colaboradores.html', dados) -
Overriding TinyMCE Styling after using dangerouslySetInnerHTML
I have a dynamic page with a lot of text in RTL format. TinyMCE cannot display the RTL text properly. It shows up something like this: While I want it to be displayed like this: Searching for a solution, I found out that dangerouslySetInnerHtml will help me get the text clean, however, I cannot get my desired formatting for the dynamic text. The code is as follows: const getWelcomeText = () => { return( <div> {texts.map((data, index) => ( <div className='backgroundnawishta'> <p className='title'> {data.title} </p> <p className='para' dangerouslySetInnerHTML={{__html: data.body}} /> </div> ))} </div> ) } and the css styling. .para{ font-size: clamp('1.5rem, 2vw, 5rem !important') ; line-height: clamp('2rem, 4vw, 5rem !important') ; font-family: titr !important; text-align: center !important; direction: rtl !important; color: #112D4E; padding: 0 !important; margin: 0 !important; text-shadow: 2px 2px #ffffff !important; } Is there a way for me to get clean text without using dangerouslySetInnerHTML or Can I override TinyMCE styling? -
Django, website with changed prefix, how to fix urls globally
I recently deployed my app locally with the help of Apache. I use server name and sufix to get to the content as http://my-server/app. The Problem is every button ignores what the root of my app is. So from my main view at my-server/app I try to redirect to /second_page and it sends me to server/second_page instead of server/app/second_page. Do I have to change every form by hand or is there any way to configure it through settings.py or urls.py? -
Django: how to update django models every couple of minutes
I am building an app, where I need to fetch some data from a website likes a news website or articles website, add it to my django models and update all the models with that data every few minutes, let's say every 15 minutes. What would be a clean and clear way to accomplish something like this? How do i requests data from external sources, let's say bbc.com How do i add these to my models automatically How would i update the models every 5 minutes I need a guide on how to accomplish this task? -
Django media image file is not displaying in template
I have a problem with media files in Django 4.0.4, here are the code and some screenshots to understand the problem : Settings.py STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('sites_events.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py photo = models.FileField() # I'm not able to use ImageField, I have troubles setting up Pillow. index.html {% load static %} <h1>{{ object.title }}</h1> <p>{{ object.description }}</p> <p>link: {{ object.link }}</p> <p>Category: {{ object.category }}</p> <p>Date: {{ object.date_time|date }} at {{ object.date_time|time }}</p> {% for photo in photo_list %} {{photo.photo.url}} <img scr="{{ photo.photo.url }}" width="250" height="250"> {% endfor %} If I copy the img src url, For example (http://127.0.0.1:8000/media/canvas_gb9uMM8.png), the image is well displayed. Thank you for your help. -
Standalone application in Django
I'm studying in Coursera. I like Django models and instruments and want to use it in my standalone Python application. How I can do in Django project? So my application must be leading and work not as request handler as all apps in Django, but in "pooling" mode. -
Why new pulled code from git not applied when Gunicorn running on ubuntu server?
I have a django project on ubuntu server that works with Nginx and Gunicorn correctrly. I change some django code and push on git server and then pull from git server on ubuntu server. It seems new changes not implemented on server. How to fix it? I restart and reload Gunicorn and Nginx but not happend. -
DRF create serializer for nested OneToOnefield
I have some Models that have OnetoOnefield in it. Question how can I update them to create serializer method, and create all fields in ModelB and ModelC thought OnetoOnefield Models: class ModelA(models.Model): name = models.TextField() class ModelB(models.Model): description = models.TextField() record = models.OneToOneField(ModelA) class ModelC(models.Model): name = models.TextField() link = models.OneToOneField(ModelB) Serializers: class RecordSerializer(ModelSerializer): link = LinkSerializer() class Meta: model = ModelB fields = '__all__' class TestSerializer(ModelSerializer): record = RecordSerializer() class Meta: model = ModelA fields = '__all__' def create(self, validated_data): record_data = validated_data.pop('record') record = RecordSerializer.create(RecordSerializer(), validated_data=record_data) modelA, created = ModelA.objects.create(record=record) return modelA View class TestViewSet(ListModelMixin, RetrieveModelMixin, CreateModelMixin, GenericViewSet): permission_classes = [IsAuthenticated] serializer_class = TestSerializer queryset = ModelA.objects.all() -
Django Channels. How to create a variable (or a object) that can live only during the WebSocket?
I have a websocket and i want to create a global variable that lives during all the life time of the websocket itself. The main issue is that the variable is actually shared between all the client that connect to the websocket while i need it to be specific to the single client. Do you know any possible solution? -
How to set tls version in Django database settings
I have an application deployed on azure, with the new releases I want to increase minimum tls version to 1.2 Python version 3.8 production MySQL version is 8.0.15 When we increase it from the mysql server app crashes and gives us the following error exception when mysql server increases the minimum tls version Here is my database connection settings DATABASES[database_name] = { 'ENGINE': 'django.db.backends.mysql', 'NAME': database_name, 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'OPTIONS': { 'ssl': {'ssl-ca': 'configs/public-azure-mysql-certificate.pem'} } I tried adding an additional field like this under the 'ssl' option field like this import ssl later in the code DATABASES[database_name] = { 'ENGINE': 'django.db.backends.mysql', 'NAME': database_name, 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'OPTIONS': { 'ssl': {'ssl-ca': 'configs/public-azure-mysql-certificate.pem', 'ssl-version': ssl.PROTOCOL_TLSv1_2} } it gives the same error as well, How can I set the TLS version to 1.2 so that I can set mysql server to accept minimum TLSv1.2 ? Thanks! -
Django Rest CORS Permissions Default
I am in the process of building a React App to talk to Django as the backend via the Django Rest Framework. I have installed the relevant packages and am trying to configure my default behavour when accessing the views to block access and have the following in my settings.py file REST_FRAMEWORK = { 'DEFAULT_PREMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ] } My view access the data is: from django.shortcuts import render from django.http import JsonResponse from .models import Articles from .serializers import ArticleSerializer # Create your views here. def articles_list(request): articles = Articles.objects.all() serializer = ArticleSerializer(articles, many=True) return JsonResponse(serializer.data, safe=False) def get_article(request, articlename): article = Articles.objects.get(name=articlename) serializer = ArticleSerializer(article, many=False) return JsonResponse(serializer.data, safe=False) Am I missing something completely simple as I can still access this when when not currently authenticated to the Django backend. Thanks -
Django: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account
I want to use django-helpdesk (which uses account) with django-allauth (which uses allauth.account). Obviously these conflict. I already have a forked version of django-allauth and I don't want to change any code as I am using the forked package in other projects. Is there any way I can change the app label of django-allauth without modifying source code? -
How to have a 'Folder' ForeignKey sorted by folders and subfolders
I have models for scripts and folders, with the scripts inside the folders. When registering a new script (or modifying an existing one) in the Django Admin page, the folders are not represented as folders and subfolders, but rather all at the same time under the form of a list, without anything to distinguish which one is a parent or a child of another one in the list. What I want is to have them clearly ordered, with subfolders underneath their parent (Or atleast display the path from the root folder instead of just the name of the folder to be able to tell where they are if what I want is not possible). I hope I'm clear, but to try explaining differently, have like a ChoiceField with the following choices : FOLDER_CHOICE= [ ('Folder1', ( ('folder1-1', 'Folder1-1'), ('folder1-2', 'Folder1-2'), ) ), ('Folder2', ( ('folder2-1', 'Folder2-1'), ('folder2-2', 'Folder2-2'), ) ) ,... ] The code of the models.py class : import importlib.util import os import shutil import types from django.db import models from django.urls import reverse from django.utils.html import format_html class Folder(models.Model): folder_name = models.CharField(max_length=200, unique=True) parent_folder = models.FilePathField(path=r'media/', allow_files=False, allow_folders=True, recursive=True) def __init__(self, *args, **kwargs): super(Folder, self).__init__(*args, **kwargs) self.initial_folder_name = … -
Delete folder or directory using API (django)
I have written down a Python script to delete or remove a folder from file directory. The code is below: import os import sys import shutil base_dir = os.path.dirname(os.path.realpath(__file__)) path = 'media/user110' try: path = os.path.join(base_dir, path) shutil.rmtree(path) print("Deleted: " + path) except OSError as e: print("Error: %s - %s." % (e.filename, e.strerror)) This worked. But it's not working in API using Django. If I print path it shows '/home/Desktop/my_project/media/user110/ But when I want to do this in API using Django, using same code, and print path I got /media/user110/ and it throw an Exception saying this directory doesn't exist Now I want to delete or remove file directory using API. I want the solution. BTW, I am using Linux, and my project will deploy in Linux server. -
Django Custom Vlaidation For Boolean Field not working
the validation is not working for the boolean field in django, models.py product_filed = models.BooleanField(default=False) def clean(self): if (self.product_field is not None) < 1: raise ValidationError( { "product_field": _(" Product field can be select once") } ) -
How can I extract timestamps from this formats?
I have certain strings like Bert interview starts (4:00) 4:32 Understanding VC fund metrics Magic of being a fan (1:20:50) How can I get timestamps from this? -
Mocking a method_decorator in django pytest?
I need a bit of guidance on the correct way to mock a method_decorator for a dispatch function. I have a method_decorator that appends log to a log file. I want to mock the method_decorator(log_request) for the dispatch function in my view. Tried to patch it but it doesn't seem to work. What could I be doing wrong ? class DummyView(APIView): serializer_class = DummySerializer @method_decorator(log_request) def dispatch(self, *args, **kwargs): return super(DummyView, self).dispatch(*args, **kwargs) class TestCustomersView: @patch("dummy.api.create_dummy") @patch("dummy.api.log_request") def test_dummy_view(self, mock_log_request,mock_create_dummy): post_data = dict(first_name="Test") mock_log_request.return_value = "Ok" mock_create_dummy.return_value = {"id": "12345", "First_Name": "Test"} req = RequestFactory().post("/api/dummies/", data=post_data) response = DummyView.as_view()(req) -
drf_yasg only renders filterset parameters on list view
I have defined a filterset for a DRF ViewSet. drf_yasg correctly renders all the filterset fields as parameters in Swagger for the list endpoint, but not for any other endpoints. Any idea why? views.py: from rest_framework import mixins, viewsets from django_filters import rest_framework as filters from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from my_app.models import MyModel from my_app.serializers import MySerializer class MyFilterSet(filters.FilterSet): class Meta: model = MyModel fields = { "status", } class MyViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet, ): filter_backends = (filters.DjangoFilterBackend, ) filterset_class = MyFilterSet queryset = MyModel.objects.all() serializer_class = MySerializer -
Django authentication to Cloud SQL postgresql through GCP IAM
I am setting up a Django project on GCP and I just created a Cloud SQL instance with IAM authentication. I have CloudSQL proxy set up to allow me to connect from my local machine. Unfortunately, when it comes to setting up the Django backend connection, there's only third-party packages for AWS IAM. Has anyone here managed to connect to a CloudSQL instance with GCP IAM? -
Error: [@formatjs/intl Error MISSING_TRANSLATION] Missing message: "currentStage." for locale "he", using id as fallback
so im trying to get data from DB, but i get this error and i dont know how to fix it. this is where im fetching the data - this is where im trying to print it - this is my he.json file constants - everything is printed but with error - -
How to Auto Approve After Some particular time in Django
class LeaveTable(models.Model): emp_name = models.CharField(max_length=50,null=True) emp_id = models.CharField(max_length=50, null=True) leave_type = models.CharField(max_length=50,null=True) applied_date = models.DateTimeField(null=True,blank=True) start_date = models.DateField() end_date = models.DateField() no_days = models.IntegerField() agent_reason = models.TextField(null=True) tl_approval = models.BooleanField(default=False) manager_approval = models.BooleanField(default=False) final_status = models.BooleanField(default=False) I want to make tl_approval, manager_approval and final_status as True automatically after 48 Hours from applied_date if it is False. I can Write the function in views.py to do same but how will it be triggered that function automatically after 48 Hours? -
How can I export a function return in Django
I have a function called on_loading_booking_deal return a dic and I am interested to use the amount key and I want to export it to use it in another file @receiver(loading_deal, sender=Booking) def on_loading_booking_deal(deal_id: str, load_company: bool = False, **kwargs): deal = get_deal(deal_id) if not deal: return None formatted_deal = { 'id': deal_id, 'amount': get_entity_property(deal, 'amount'), 'occupational_use': get_entity_property(deal, 'occupational_use') } contact = None if len(deal['associations']['associatedVids']) > 0: contact = get_contact(deal['associations']['associatedVids'][0]) if not contact: logger.warning("Unable to load hubspot contact") if contact: formatted_deal['contact'] = { 'first_name': get_entity_property(contact, 'firstname'), 'last_name': get_entity_property(contact, 'lastname'), 'email': get_entity_property(contact, 'email'), 'type_of_business_model': get_entity_property(contact, 'type_of_business_model') } if load_company: company = None if len(deal['associations']['associatedCompanyIds']) > 0: company = get_company(deal['associations']['associatedCompanyIds'][0]) if not company: logger.warning("Unable to load hubspot company") if company: formatted_deal['company'] = { 'name': get_entity_property(company, 'name') } print(f"Loaded deal {formatted_deal['amount']}") return formatted_deal ## I want to export this return into another folder/file -
why django-split-json-widget can't use in my model.form
i have tried many times, but it seems like the widget didn't work. There's nothing in my page. I use jsonfield to save the data with json, now , i want to tranform these json data into html input form, and i have found the django-split-json-widget. I've tried to use but i don't know what's the problem views.py class Message(models.Model): myQOS = ( ('0','0'), ('1','1'), ('2','2'), ) name = models.CharField(max_length=200, null=True) description = models.CharField(max_length=300, null=True) topic = models.CharField(max_length=300) qos = models.CharField(max_length=200, choices=myQOS, null=True) retain = models.BooleanField(null=True) payload =jsonfield.JSONField(null=True) def __str__(self): return self.name forms.py class MessageForm(ModelForm): def render(self, name, value, attrs=None): attrs = {'class': 'special', 'size': '25'} data = forms.CharField(widget=SplitJSONWidget(attrs=attrs, debug=True)) class Meta: model = Message fields = ('name','description', 'topic', 'qos', 'retain') views.py def Update_Message(request, pk): messages = Message.objects.get(pk=pk) json = messages.payload messageform = MessageForm(request.POST or None, instance=messages, initial={'data': json}) print(messageform.data) context = {'messageform' : messageform} if request.method == 'POST': if messageform.is_valid(): Mesform = messageform,save(commit=False) Mesform.payload = messageform.cleaned_data['payload'] Mesform.save() return redirect('/Update_Message/{}'.format(messages.id)) return render(request, 'apps/Update_Message.html',context) html <a href="{% url 'MessageList' %}">back to list</a> <form method="POST"> {% csrf_token %} {{ messageform.payload }} <input type="submit" value='Update' class="buttonupdate"> </form>