Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Replace form.as_p with custom template
need help to use html templates instead of using the deafult django form.as_p enter image description hereenter image description hereenter image description here it tried adding labels with id and i was exxpecting them to match -
Sort objects by hit_count.hits
Using django-hitcount to count views with no issues. Now, how do I sort a QS by hits? For example, have a bunch of different animals: class Dog(models.Models): name = models.CharField(max_length=40) age = models.IntField() class DogDetailView(HitCountDetailView): model = Dog count_hit = True Viewing individual animals works fine and view counts go up. Now on a main page, I need to list each animal type by most viewed. I can get the list of dogs, but how do I sort it by hit_count? class AllAnimalsView(TemplateView): ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["dogs"] = Dogs.objects.all().order_by("-hit_count.hits") .... return context This gives: django.db.utils.OperationalError: (1054, "Unknown column 'hit_count.hits' in 'order clause'") -
NoReverseMatch Error during template rendering
I have this url that causes the error <a href="{% url 'page-two' item_1 item_2 %}"> The url should be rendered as /pages/36/some-story urls.py urlpatterns = [ path('pages/<slug:slug>', views.PageOneView.as_view(), name='page-one'), path('pages/<slug:slug_1>/slug:slug_2>', views.PageTwoView.as_view(), name='page-two'), ] views.py class PageOneView(View): def get(self, request, slug): run = Pages.objects.get(id=slug) item_1 = 36 item_2 = 'some-story' context = { 'item_1': item_1, 'item_2': item_2, } return render(request, "pages/page_1.html", context) class PageTwoView(View): def get(self, request, slug_1, slug_2) context = {} return render(request, "pages/page_2.html", context) The trackback says: Reverse for 'page-two' with arguments '('36', 'some-story')' not found. It seems like the url get's rendered correctly because I see the values I expected. But I still can't figure out where this error is coming from. What have I done wrong? -
Optimizing Django queries - reducing database requests & proper queryset access
My Views def home(request): q = '' if request.GET.get('q'): q = request.GET.get('q') rooms = Room.objects.select_related('host', 'topic').prefetch_related('participants').filter( Q(topic__name__icontains=q) | Q(name__icontains=q) | Q(description__icontains=q) ) topics = Topic.objects.select_related('user') profile = Profile.objects.filter(user=request.user) r_messages = Message.objects.select_related('user', 'room').filter(Q(room__topic__name__icontains=q)) return render(request, 'base/home-page.html', context={ 'rooms': rooms, 'topics': topics, 'profile': profile, 'r_messages': r_messages, }) My Models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.FileField(default='default.jpg', upload_to='profile_image', null=True) name = models.CharField(max_length=100, null=True, blank=True) bio = models.TextField(max_length=5000, null=True, blank=True) email = models.EmailField() username = models.CharField(max_length=100) def __str__(self): return f'{self.user}' def get_absolute_url(self): return reverse('user-profile', args=[str(self.user)]) class Topic(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return f'{self.name}' class Room(models.Model): host = models.ForeignKey(Profile, 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 = models.ManyToManyField(Profile, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) # Save every time when we update created = models.DateTimeField(auto_now_add=True) # Only save when room was created class Meta: ordering = ['-updated', '-created'] def __str__(self): return f'{self.name}' class Message(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.body[:50]}' class Meta: ordering = ['-updated', '-created'] My Template {% for room in rooms %} <li> {{ room.topic.host }} <a href="{% url 'home' %}?q={{ room.topic.name}}">{{ room.topic.name}}<span>{{ room.topic.room_set.all.count}}</span></a> </li> … -
Published Google Play Store App not doing authentication but debug apk passes authentication
Assistance Am doing an app in ionic framework with JWT authentication coming from Django rest framework and encountering a very wierd problem, before I upload my app to Google play console it is able to login successfully but when I download the Open Test Version of Google play store am unable to login After some hours of research am thinking the problem is related to app signing and something to deal with API integrity What i have tried to do is upload my keystore file that i geneated using keytool to Google Play Console's App Signing Tab under App Integrity then also associated my app with the Digital Asset Links JSON but still encounter the same issue Anyone to help? What i have tried to do is upload my keystore file that i geneated using keytool to Google Play Console's App Signing Tab under App Integrity then also associated my app with the Digital Asset Links JSON but still encounter the same issue -
I'm using a standard Django login but I'm getting this error: Error exiting in Django 4.2.1
enter image description heremessage error when clicking link to logout message error when clicking link to logout urlpatterns content django.contrib.auth.urls in urls.py urlpatterns content django.contrib.auth.urls in urls.py Variable LOGOUT_REDIRECT_URL in settins.py Variable LOGOUT_REDIRECT_URL in settins.py file html index content button html logoutenter image description here I am creating logout, login works less logout -
How can I display all active sessions of logged in users using django-user-sessions?
Please I need someone to help me out on the django-user-sessions, I have tried the documentation but it is not showing me the full active sessions of the login user. Please I need help can someone show me the example views and template on how it should be. Thank you I have tried the django-user-sessions documentation, I have installed django-user-sessions and put user-sessions in my installed apps. -
How to create a web django system with a dynamic apps?
I need o create a django system with a dynamic apps. In another words: when the client buy the system, we will to enable whats apps they will use according to the contracted package and it needs to be intuitive because the sells time need to enable the apps without needing the dev. Can you guys already make something like this ?? I have no idea how start. -
How can I fix the '_TypeError' when adding a model to another model in Flutter with Django Rest API?
I'm really confused on how do I add director model to my show model. I'm writing Android application in Flutter, that uses local Django Rest API. This is Director Model in Django class Director(models.Model): name = models.CharField(max_length=20) surname = models.CharField(max_length=20) country = models.CharField(max_length=20) image = models.ImageField(null=True, blank=True, upload_to="images/") This is Shows Model in Django class Show(models.Model): name = models.CharField(max_length=50) annotation = models.TextField(max_length=1000) language = models.CharField(max_length=20, null=True) image = models.ImageField(null=True, blank=True, upload_to="images/") director = models.ForeignKey(Director, on_delete=models.CASCADE, null=True) This is Director Model in Flutter import 'package:flutter/widgets.dart'; class DirectorModel with ChangeNotifier { final int id; final String name; final String surname; final String image; DirectorModel({required this.id, required this.name, required this.surname, required this.image}); factory DirectorModel.fromJson(dynamic json) { return DirectorModel( id: json['id'], name: json['name'] as String, surname: json['surname'] as String, image: json['image'] as String, ); } static List<DirectorModel> directorFromSnapshot(List snapshot) { return snapshot.map((data) { return DirectorModel.fromJson(data); }).toList(); } } This is Shows model in Flutter import 'package:flutter/widgets.dart'; import 'package:kulises_app/models/directors.dart'; class ShowsModel with ChangeNotifier { int id; String name; String annotation; String language; DirectorModel director; String image; ShowsModel( {required this.id, required this.name, required this.annotation, required this.language, required this.director, required this.image}); factory ShowsModel.fromJson(dynamic json) { return ShowsModel( id: json['id'], director: DirectorModel.fromJson(json['director']), name: json['name'] as String, annotation: json['annotation'] … -
Python Django - process long running views in the background
What is the best approach to send a long running process to the background in Python when working within the Django framework. Summary: I'm using a Django web app alongside chatGPT to create a certain resource for my users. The problem is waiting on the response from openAI makes for a terrible user experience. For this reason I would like to offload this work. Ideally, I would like to send another http request to my server with the needed payload and run it in the background, then alert users when it's completed. Here's the synchronous code @login_required def createx(request): if request.method == "GET": return render(request, 'x/x_create.html', {}) else: request_body = json.loads(request.body) #get user profile my_user = request.user #make sure the user is premium if not my_user.is_premium_user(): #redirect to home page #set error message messages.error(request, 'You must be a premium user to create a x') return redirect('home') #get user profile my_user_profile = UserProfile.objects.get(user=my_user) user_prompt = createPrompt(my_user_profile, request_body.get('position'), request_body.get('company'), request_body.get('description')) system_prompt = "You are a helpful assistant." #create x using chatgpt url = "https://api.openai.com/v1/chat/completions" headers = { "Authorization": f"Bearer {settings.OPEN_AI_API_KEY}", "Content-Type": "application/json" } # Craft the request payload payload = { "model": "gpt-3.5-turbo", "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": … -
Unique_together doesn't work if a field is null. How to constrain it?
I have a model like this class ProductCode( models.Model): class Meta: unique_together=[('code','customer'), ] customer = models.ForeignKey( 'customers.Customer', models.CASCADE, null=True, blank=True, ) code = models.CharField( max_length = 20) product = models.ForeignKey( Product, models.CASCADE, ) ... The trouble is that if customer is None (DB null) then the constraint is not enforced. It lets me store rows/objects with, say, (code='foo', customer=None) multiple times. I have found this SO post which suggests that the problem is un-fixable for Postgres users. Is there any way to enforce this constraint with the (relatively) new Meta constraints? I am finding the documentation a bit hard to fathom. Or do I have to implement a placeholder customer to attach "default" product codes to? Or, another way would be to prepend a textual representation of customer to code and then just make it unique=True and use __startswith= and __contains lookups where necessary. -
How can I implement basic authentication between Next.JS and DRF using JWT?
I am trying to recode the website for my student club and would need some assistance regarding authentication. I do have a Django Backend setup with all the necessary data (e.g. Member infos, etc.) and would like to display them on the frontend (name + position) and on the Backend (email, phone number, etc.). Now to achieve that I would need basic authentication where I can give out login credentials to the members and they can login (no sign up from the website). Now I am wondering how to do that; coming from Django I would generate a credential pair and the authentication would go via JWT, but I cant find a suitable example (everything is very old). Right now my setup looks like this: Django Backend with JWT Next.JS frontend (typescript, tailwind css) with seperate login page I was looking at next-auth which seems promising but I am afraid that login via Socials is not my usecase. Can anyone provide more information how to setup Django with Next.JS with authentication? Cheers I already tried using Next-Auth with some examples provided on the internet but none of them worked/ were deprecated. -
Django: update data with ajax view (error on data format)
I want to update django data using ajax view but got an error "AttributeError: 'str' object has no attribute 'get'" dealing with format data passed in form in my view. I first serialized data of my form with Jquery and send data using ajax. In my view, I retrieve data (but str format) so when I passe it to my Form, an error is raised. I've tried many, JSON.parse in Jquery and Json.loads in my view and many other thing but nothing works // lock a form $("body").on("click", '.lock', function (event) { var model = $("form").data('model'); var csrfmiddlewaretoken = $("input[name='csrfmiddlewaretoken']").val(); // retrieve ide of form to lock/unlock var ide = $("form").data('ide').toString(); var url = "/ecrf/lock/".concat(ide); var data = $("form").serialize() console.log('serialize data', data) $.ajax({ type: "POST", url: url, data: { csrfmiddlewaretoken: csrfmiddlewaretoken, 'model': model, 'data': data }, dataType: 'json', success: function (response) { console.log('success'); }, }); }); def lock(request,pk): from urllib.parse import parse_qs model = apps.get_model('ecrf', request.POST.get('model')) data = request.POST.get('data') lock_unlock = None obj = get_object_or_404(model, ide = pk) form = SociodemographiqueForm(data=data or None, instance = obj) if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == "POST": if form.is_valid(): form.save() ... return JsonResponse({},status=200) -
django: suit.apps could not be resolved
I'm trying to use the Django Suit, I have downloaded the django v2-dev using pip and added the SuitConfig in the INSTALLED_APPS before django.contrib.admin. However, when I write "from suit.apps import DjangoSuitConfig" I get suit.apps could not be resolved apps.py file ] [settings,py][(https://i.stack.imgur.com/9ajKF.png)] -
How to fix "Permissions Denied" and "No such file or directory" Errors? Using Django and Docker Compose
Permissions Denied for makemigrations command in Django. I typed in the following: docker-compose -f production.yml run --rm django python manage.py makemigrations Then I got the following: PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.9/site-packages/allauth/socialaccount/providers/openid/migrations/0002_auto_20230524_1428.py' So I tried to give permissions by doing the following: sudo chown ec2-user /usr/local/lib/python3.9/site-packages/allauth/socialaccount/providers/openid/migrations/ But then I get the following: chown: cannot access ‘/usr/local/lib/python3.9/site-packages/allauth/socialaccount/providers/openid/migrations/’: No such file or directory So there's no directory to give permissions to? I checked what exists, and there's python3.7 but not python3.9 in the remote server. But I think Django uses Python3.9, I just don't know where it exists? I tried to give permissions to the directory but apparently the directory that contains the migrations doesn't exist. -
django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row')
Upon calling the get_tag_posts method of the Profile model, it is raising the following error: django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row') What about the query is causing this error and what correction should be made in order to resolve this it? authors/models.py class Profile(Model): user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE) def get_tag_posts(self, order_by=None): tags = Tag.objects.filter( question__profile=self ).distinct() questions_with_tag = self.questions.filter( tags__name=OuterRef("name")).only('id') records = tags.annotate( times_posted=Count(Subquery(questions_with_tag)), avg_question_score=Avg("question__score", output_field=IntegerField()) ) if not order_by or order_by not in ['name', 'score']: order_by = "name" if order_by == "name": records = records.order_by(order_by) else: records = records.order_by("-avg_question_score") return { 'records': records, 'title': f"{tags.count()} Tags" } posts/models.py class Tag(Model): name = CharField(unique=True, max_length=25) class Meta: managed = True db_table = "tag" def __str__(self): return f"{self.name}" def get_absolute_url(self): return f"/questions/posted/{self.name}" class Post(Model): body = TextField() date = DateTimeField(default=timezone.now) comment = ForeignKey('Comment', on_delete=CASCADE, null=True) profile = ForeignKey( 'authors.Profile', on_delete=SET_NULL, null=True, related_name='%(class)ss', related_query_name="%(class)s" ) vote = GenericRelation( 'Vote', related_query_name="%(class)s" ) score = IntegerField(default=0) class Meta: abstract = True managed = True class Question(Post): title = CharField( max_length=80, unique_for_date="date", help_text="Concisely state the problem you're having", error_messages={ "max_length": "The title of your question is too long" } ) tags = ManyToManyField( 'Tag', related_name="questions", related_query_name="question" ) views = IntegerField(default=0) visible = BooleanField(default=True) … -
How to return existing matching record for Django CreateView
I use a regular generic.edit.CreateView of Django to create an object according to user input. The MyModel has an UniqueConstrait so the creation would fail if the new object happens to match an existing one. However, instead of telling users that creation fails due to duplicate records, I would like to simply return the existing object since this is what users want. I tried to override def save(self, commit=True): return MyModel.get_or_create(value=self.cleaned_data['value'])[0] but this does not work because form._post_clean will call form.instance.full_clean with its default validate_constraints=True, so an error will return during form validation. Essentially I am looking for a GetOrCreateView but I am not sure what is a clean way to achieve this (other than maybe overriding form._full_clean). Note that I am not looking for a UpdateView because we do not know in advance which existing object will be returned. -
Django 4.1.9 requires_system_checks issue with manage.py - is this a bug or not
Django 4.1.9 requires_system_checks issue with manage.py - is this a bug or not we are upgrading our wagtail 4.2.2 app to from django 3.1.9 to django 4.1.9 getting the error TypeError: requires_system_checks must be a list or tuple. when running python manage.py runserver_plus 0.0.0.0:8020 --keep-meta-shutdown Is this a bug and / or can i be worked around Could I monkey patch BaseCommand.init() to set requires_system_checks = [] -
Received unregistered task of type in celery beat
I can't seem to find what's missing. In the ecommerce app I have a jobs folder with __init__.py and order.py files. Here's order.py from celery import shared_task @shared_task def test(): print("Test completed") These are from settings.py. CELERY_BEAT_SCHEDULE = { 'order_data_synchronization': { 'task': 'ecommerce.jobs.order.test', 'schedule': timedelta(seconds=5), }, } In 3 tabs I run python3 manage.py runserver, redis-server and celery -A my-project.celery worker --loglevel=info --beat Every 5 seconds the following message appears with large logs Received unregistered task of type 'ecommerce.jobs.order.test'. -
Docker Django static files found but not working on HTML + ASGI path not found
I am trying to deploy my app in django with docker but i am experiencing these 2 problems that are in the title. I will explain better what I did. Having problems starting ASGI with HTTP server I decided to split ASGI and WSGI into 2 different services, here is my docker-compose (WSGI I start with runserver to test): version: '3' services: web_asgi: environment: - DJANGO_SETTINGS_MODULE=KeyOne.settings - DJANGO_ALLOW_ASYNC_UNSAFE=true build: ./keyonecrm volumes: - ./keyonecrm:/code expose: - "8000" command: daphne -u /tmp/daphne.sock KeyOne.asgi:application depends_on: - db - redis web_wsgi: build: ./keyonecrm volumes: - ./KeyOneCRM:/code - ./KeyOneCRM/src:/code/src expose: - "8001" command: python ./manage.py runserver 0.0.0.0:8001 depends_on: - db - redis nginx: build: ./nginx volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./KeyOneCRM/src:/static ports: - "80:80" depends_on: - web_asgi - web_wsgi db: image: mongo:4.2.8 volumes: - ./data/db:/data/db ports: - "27017:27017" redis: image: redis:5.0.7 ports: - "6379:6379" Dockerfile for web and nginx: FROM python:3.10 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN pip install uvicorn COPY . /code/ RUN python manage.py collectstatic --noinput FROM nginx:1.21-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d nginx.conf: worker_processes auto; events { worker_connections 1024; } http { server … -
DRF. Filtering child's class objects linked to parrent with ForeignKey from a parent class api routing
I work on some kind of e-commercial shop (just for learning purpose). I have parent model Category and child model Product which has a field category which references to Category object with Many-To-One relations (ForeignKey). Idea is to make filtration from a parent class e.g. Category to retrieve all Product objects matches with given paramenter(s). For example: When I send a request to route "localhost/api/categories/" I get all categories and subcategories (just for wider vision: subcategory routing also works. If i send request to localhost/api/categories/smartphones/ it returns a response with subcategories which are children of smartphones and so on). Now I want to implement filtering in such way : when I send a request to route "localhost/api/categories/smartphones/brand?=apple" it has to return all Product objects with brand field equal to "apple". And this pattern has to work for any category so I don't have to hardcode apple as Category object for every single category that might contain Apple devices. My code right now (not all lines included but most important) : products/models.py class Product(models.Model): """Model representing a product.""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') brand = models.ForeignKey('Brand', on_delete=models.CASCADE, related_name='products') slug = models.SlugField(unique=True, blank=True, default=id) … -
How to do partial matching on searches with PostgreSQL in wagtail?
How to do partial matching on searches with PostgreSQL as search backend? I'm running wagtail 5.0 and I see the following statements in the documentation The partial_match option has been deprecated. To index a field for partial matching, use AutocompleteField instead. However in the autocomplete documentation it states This method should only be used for real-time autocomplete and actual search requests should always use the search() method. What is the issue with using the autocomplete method vs search? Functionally the autocomplete method gives me what i want. >>> UtvalgPostPage.objects.all().live().search("alt") <SearchResults [<UtvalgPostPage: Demo på alt vi har>]> >>> UtvalgPostPage.objects.all().live().search("al") <SearchResults []> >>> UtvalgPostPage.objects.all().live().autocomplete("al") <SearchResults [<UtvalgPostPage: Demo på alt vi har>]> -
Django: Displaying KMZ files
Hello am having trouble to display my kmz files in a website that am building I have this code written now {% extends 'main/base.html' %} {% block content %} <div id="map"></div> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: 0, lng: 0}, zoom: 10 }); {% for property in properties %} var kmlLayer{{ property.id }} = new google.maps.KmlLayer({ url: '{{ property.kmz_file.url }}', map: map }); {% endfor %} } function loadMap() { var script = document.createElement('script'); script.src = 'https://maps.googleapis.com/maps/api/js?key={{ GOOGLE_MAPS_API_KEY }}&libraries=places&callback=initMap'; script.async = true; script.defer = true; document.body.appendChild(script); } window.addEventListener('DOMContentLoaded', loadMap, { passive: true }); </script> {% endblock %} Also I created a folder named context_processors where i added a file named google_maps_api_key.py including the below code from django.conf import settings def google_maps_api_key(request): return {'GOOGLE_MAPS_API_KEY': settings.GOOGLE_MAPS_API_KEY} And in the setting.py i added the following lines TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [r'C:\xampp\htdocs\YF\mysite\main\templates\main'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ .... 'main.context_processors.google_maps_api_key.google_maps_api_key', ], }, }, ] But when am loading the website it shows nothing. Can someone help me? -
GraphQLTestCase does not return any data
I want to test my django graphql endpoints. So I just followed instructions and created a simple test case that should retrieve one data set. But instead I just get an empty object without any data. Meanwhile if I execute the query in graphql gui I can get the data. I'm also trying to use an existing database for testing by using --keepdb option: python manage.py test --keepdb category.category_test test: from graphene_django.utils.testing import GraphQLTestCase class QuestionModelTests(GraphQLTestCase): def test_get_all_categories(self): query = """ query{ categories{ id title } } """ response = self.query(query) print(response.content) self.assertResponseNoErrors(response) print line does not return any data as well. error: raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) My category schema: import graphene from django.db.models import Q from graphene_django import DjangoObjectType from app.permissions import permission, Admin, Seller, All from category.models import Category class CategoryType(DjangoObjectType): class Meta: model = Category class Query(graphene.ObjectType): categories = graphene.List(CategoryType, search=graphene.String(), searched_id=graphene.String(), ) @permission(roles=[All]) def resolve_categories(self, info, search=None, searched_id=None, **kwargs): if search: filter = ( Q(title__icontains=search) ) return Category.objects.filter(filter) if searched_id: Category.objects.get(id=searched_id) return Category.objects.all() -
Python step debugger breaking upon introducing asyncio and httpx
Python step debugger breaking upon introducing asyncio and httpx. Developing Django application using vscode using this debug configuration { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true } ] } Nothing changed other than introducing this asynchronous module. I can also fix the debugger by removing import of httpx and asyncio. A viable workaround for me would be any way to send a http request without awaiting the response, but using asyncio and httpx seems to be a common approach to do this.