Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery second unregistered task
I have a doubt regarding the implementation of celery with rabbitMQ since only the first function (debug_task()) that I have defined in celery.py is executed. The problem is that send_user_mail(randomNumber, email) is not working. debug_task is working, so it's registered. This is the celery console [2022-10-08 22:28:48,081: ERROR/MainProcess] Received unregistered task of type 'callservices.celery.send_proveedor_mail_new_orden'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you are using relative imports? Why it's unregistered? celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from django.core.mail import EmailMultiAlternatives, send_mail os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'callservices.settings') app = Celery('tasks',broker='pyamqp://guest@localhost//') app.config_from_object('django.conf:settings') app.autodiscover_tasks(settings.INSTALLED_APPS) @app.task() def debug_task(): print("hi all") @app.task() def send_user_mail(randomNumber, email): subject = 'email validation - ServicesYA' cuerpo="Your number is: "+str(randomNumber) send_mail(subject, cuerpo ,'xxx.ssmtp@xxx.com', [email],fail_silently = False) return 1 This is init.py # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from celery import app as celery_app __all__ = ('celery_app',) and in settings.py I add this line: BROKER_URL = "amqp://guest:guest@localhost:5672//" -
How to view multiple images under separate posts in profile page
I am building a social media website. On the profile page and home page are different posts. Each can have multiple images. I created a different model for images and set ForeignKey to Post model. The form for uploading text and images works fine because the images attach to each post in the database. However, I am having issues writing the views code for the page they are to display. I am getting just text with no images. I am trying to add an Id to each post in the views but I have no idea how to do that since they are all in one page and therefore have no separate urls. I don't know if that is the right approach. Help me please. Thanks. -
Suddenly ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?
Suddenly my Django project showed me the following ImportError: "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?". It ran fine before. I work on Mac m1 using PyCharm Professional. My Django is installed. My venv is activated. So, I guess I have problem with PYTHONPATH . My interpreter is exactly I would like to use: Actually I have some versions of Python. which Python shows me: (venv) user_name@computer_name project_name % which python python: aliased to /usr/bin/python3 (venv) user_name@computer_name project_name % which python3 /Users/user_name/PyCharmProjects/TrainingProjects/project_name/venv/bin/python3 (venv) user_name@computer_name project_name % which python3.9 /opt/homebrew/bin/python3.9 python3 -c "import sys; print(sys.path)" shows me: /opt/homebrew/Cellar/python@3.10/3.10.7/Frameworks/Python.framework/Versions/3.10/lib/python310.zip /opt/homebrew/Cellar/python@3.10/3.10.7/Frameworks/Python.framework/Versions/3.10/lib/python3.10 /opt/homebrew/Cellar/python@3.10/3.10.7/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload /Users/user_name/PyCharmProjects/TrainingProjects/project_name/venv/lib/python3.10/site-packages If I understand this output correctly, it means that there is no python 3.9 in my PYTHONPATH for now. In my settings.py, there are: import os import sys #not active from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) which $PYTHONPATH brings me PYTHONPATH not found. echo $PYTHONPATH brings me nothing. The export: export PYTHONPATH=$PYTHONPATH:/Library/Frameworks/Python.framework/Versions/3.9/bin/python3 didn't help. Any help is highly appreciated. -
Django One-To-Two Relation
I want to implement a case where model A has exactly two B instances and model B has exactly one A instance. What is the best way to implement this? class A(Model): b1 = OneToOneField(B) b2 = OneToOneField(B) If I use this I have to provide two different related names to b1 and b2 fields. I want be able to simply say b.a_set.first() and get the object since I know B will have single A. And this is not really oneToTwo I think, b1 and b2 could point to the same B object although this is not critical at the moment. class B(Model): a = ForeignKey(A) If I use this then it is OneToMany, I want to be explicit about relation, and be able to use a.b1 and a.b2. Also I will be accessing model B from model A frequently so this is very inefficient. It doesn't make sense to search through table B when I know there are exactly two related B instances. I should be able to store the corresponding B ids in table A like in the previous case. What would be a good way to implement this? -
Django Autocomplete Light not working with Bootstrap 5 Modal
I am newbie to Python and Django. This is my first post. Sorry if I omit relevant information. I'm using DAL on a form inside a Bootstrap modal. Clicking the dropdown list appears behind the modal. The autocomplete function works correctly if I do it outside of the modal. I'm using: Django: 4.0.5 django-autocomplete-light: 3.9.4 Bootstrap 5.2.2 Python 3.10.4 To try to fix it, I have created a style.css file with the following code, as indicated in: bootstrap modal with select2 z-index .select2-container { z-index: 9999 !important; } Now the list appears in front of the modal, but it doesn't allow typing in the search box. I've tried doing the following, but it doesn't work: https://select2.org/troubleshooting/common-problems $(document).ready(function() { $("#codigo_emplazamiento").select2({ dropdownParent: $("#FormularioCrear") }); }); I've tried removing tabindex="-1" from the modal, but it doesn't work. It seems to be related to this, but I can't get it to work: https://lightrun.com/answers/yourlabs-django-autocomplete-light-search-input-not-receiving-focus I really appreciate your help. Thank you very much. This is my code: forms.py class FormularioTarea(forms.ModelForm): class Meta: model = Tarea fields = ['referencia_interna', 'codigo_emplazamiento', 'estado', 'fecha_fin', 'tipo_documento'] autocomplete.ModelSelect2(url='emplazamientoautocompletar')}) widgets = { 'codigo_emplazamiento': autocomplete.Select2( url='emplazamientoautocompletar', ) } models.py class Emplazamiento(models.Model): TIPO_ELECCION = (('URB', 'Urbano'), ('RUR', 'Rural')) codigo_emplazamiento = models.CharField(unique=True, max_length=10) direccion … -
Django on phones and other recommendations
I am trying to run django and run it's virtualenv on pycharm, is there a better python IDE to run django on phones or how I can do it on pycharm? -
KeyError: "Got KeyError when attempting to get a value for field `password` on serializer `LoginSerializer`
I have a login view that looks like this but I keep getting a KeyError whenever I access the API. I cannot seem to fix with the related answers. class LoginAPIView(GenericAPIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) The serializer looks like this: class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField() password = serializers.CharField(min_length=6) username = serializers.CharField(read_only=True) tokens = serializers.CharField(read_only=True) class Meta: model = User fields = ["email", "password", "username", "tokens"] def validate(self, attrs): email = attrs.get("email", "") password = attrs.get("password", "") user = auth.authenticate(email=email, password=password) if not user: raise AuthenticationFailed("Invalid credentials") if not user.is_active: raise AuthenticationFailed("Account is not active, please contact admin") return { "email": user.email, "username": user.username, "tokens": user.tokens(), } when I access this endpoint, I get this error: KeyError: "Got KeyError when attempting to get a value for field `password` on serializer `LoginSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'password'." full error below. [08/Oct/2022 23:29:57] "POST /auth/register/ HTTP/1.1" 201 54 Internal Server Error: /auth/login/ Traceback (most recent call last): File "/home/xorlali/.cache/pypoetry/virtualenvs/refive-backend-0hCIKWkR-py3.9/lib/python3.9/site-packages/rest_framework/fields.py", line 446, in get_attribute return get_attribute(instance, self.source_attrs) File "/home/xorlali/.cache/pypoetry/virtualenvs/refive-backend-0hCIKWkR-py3.9/lib/python3.9/site-packages/rest_framework/fields.py", line 94, in get_attribute instance = instance[attr] KeyError: 'password' During … -
I have installed MySQL for Python . Now I try to connect to the MySQL Community Server on my local machine, using this code:
DATABASES = { 'default': { 'NAME': "food", 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'USER': 'root', 'PASSWORD': 'groot', This code fails with this error: ... connection = Database.connect(**conn_params) File "C:\Users\mona\Downloads\food-ordering-system-master\food-ordering-system-master\food-ordering-system\env\lib\site-packages\MySQLdb_init_.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\mona\Downloads\food-ordering-system-master\food-ordering-system-master\food-ordering-system\env\lib\site-packages\MySQLdb\connections.py", line 179, in init super(Connection, self).init(*args, **kwargs2) django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'localhost' (10061)") -
Why Is Ajax Creating a New Comment When I'm Trying To Edit An Existing One?
I am trying to do a Django Blog in Class Based Views. They're proving very difficult to me anyway. I feel like I'm pretty close...I suspect it's creating a new one because I'm combining DetailView and trying to include an UpdateView in my page. I'm overriding POST on the DetailView...and perhaps that's why when I try to do my Update of the comment the overriden Post on DetailView is overriding that action? Here's my code.... HTML... <!DOCTYPE html> <form method='POST' class="comment-form"> {% csrf_token %} <div class="spacer284"> {{ form.comment }} </div> <button class="button7" type="submit">Submit</button> </form> <div class="spacer285"> {% include 'suggestion_comments.html' %} </div> </div> {% endblock %} Note that I'm doing an include so that I can loop through the comments more easily... Here's the include template... {% if suggestion_comments %} <h2>Comments</h2> {% for comment in object.suggestion_comments.all %} <div class="spacer291"> <p><a href="{% url 'Main:associate_directory_associate_detail' pk=comment.author.id %}">{{ comment.author }}</a> {{ comment.created_on }}</p> <p class="spacer290">{{ comment.comment }}</p> <div class="spacer289"> <div class="upvote-comment-count">{{ comment.total_comment_upvotes }}</div> <div class="hide-delete"> <button type="button" class="button6" data-href="{% url 'Suggestions:suggestion_comment_like' comment.id %}">Like</button> </div> <div class="hide-delete"> <button type="button" class="button2" data-href="">Reply</button> </div> {% if comment.author == request.user %} <button type="button" class="button4" id="{{ comment.id }}" pk="{{ object.pk }}" href="{% url 'Suggestions:suggestion_comment_edit' object.pk comment.id %}">Edit</button> <div class="spacer159" … -
Accessing TemporaryFilePath in form_valid Django
Currently my users are able to upload files, as I am deployed via Heroku I am using Django-storages to upload to AWS S3 buckets. I am using a CreateView/UpdateView as below, this works well however I now want to be able to run an operation on the file before uploading to AWS, my research insofar suggests that I can use temporary_file_path() to do this in the form_valid however I am getting an error, UpdateView/CreateView class project_update(LoginRequiredMixin, UpdateView): model = Project form_class = ProjectForm template_name = "home/update_project.html" context_object_name = 'project' success_url = reverse_lazy("project-list") def form_valid(self, form): handle_uploaded_boq(form['boq_file'].temporary_file_path(), form.cleaned_data['project_title']) return super(project_update, self).form_valid(form) However I am getting the following error: 'BoundField' object has no attribute 'temporary_file_path' So what is the best way to run the operation handle_uploaded_boq() before the file is uploaded to AWS? -
Search bar in the models.CharField containing choiches Django
I wanted to know if there is a way to insert a search bar in the Django choices, that is instead of manually searching the various choices if it is possible to use a filter bar to search for our choice in Django Admin - Models. -
How to check if a variable is alphanumeric if acertain condition has been met
I am trying to check if the length of the user's username is 7. If the condition is satisfied, then I want to check if it is alphanumeric. If it isn't, I want to return the error below. You have entered an invalid username Here is My code if len(username) == 7: if username.isalnum() is False: self.errors[''] = self.error_class(["You have entered an invalid username"]) else: pass else: self.errors[''] = self.error_class(["You have entered an invalid username"]) -
Multiprocessing In Django Function with ZIP
Is it possible to use multi processing in Django on a request. #so if I send a request to http://127.0.0.1:8000/wallet_verify def wallet_verify(request): walelts = botactive.objects.all() #here I check if the user want to be included in the process or not so if they set it to True then i'll include them else ignore. for active in walelts: check_active = active.active if check_active == True: user_is_active = active.user #for the ones that want to be included I then go to get their key data. I need to get both api and secret so then I loop through to get the data from active users. database = Bybitapidatas.objects.filter(user=user_is_active) for apikey in database: apikey = apikey.apikey for apisecret in database: apisecret = apisecret.apisecret #since I am making a request to an exchange endpoint I can only include one API and secret at a time . So for 1 person at a time this is why I want to run in parallel. for a, b in zip(list(Bybitapidatas.objects.filter(user=user_is_active).values("apikey")), list(Bybitapidatas.objects.filter(user=user_is_active).values("apisecret"))): session =spot.HTTP(endpoint='https://api-testnet.bybit.com/', api_key=a['apikey'], api_secret=b['apisecret']) #here I check to see if they have balance to open trades if they have selected to be included. GET_USDT_BALANCE = session.get_wallet_balance()['result']['balances'] for i in GET_USDT_BALANCE: if 'USDT' in i.values(): GET_USDT_BALANCE = … -
Method get_context_data is called twice. Template tags in django
the database is accessed twice, once per in views, second time in templatetags. I tried to make a mixin, it still calls twice. how to remove the second call to the database? VIEWS class MoneyHomeView(CacheQuerysetMixin, RelatedMixin, ListView): model = Money paginate_by = 10 template_name = 'money/money_list.html' context_object_name = 'money' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) if self._check_cached() == False: getQ = self._caching_queryset(self.getMoneyQuery()) else: getQ = self._get_cached_queryset() list_orders = getQ paginator = Paginator(list_orders, self.paginate_by) page = self.request.GET.get('page') return context def getMoneyQuery(self): return Money.objects.all() MIXIN class CacheQuerysetMixin: _cached_queryset: list = None def _caching_queryset(self, queryset): if not self._cached_queryset: self._cached_queryset = queryset return self._cached_queryset def _check_cached(self): if not self._cached_queryset: return False return True def _get_cached_queryset(self): if not self._cached_queryset: self._cached_queryset = queryset return self._cached_queryset templatetag @register.simple_tag(takes_context=True) def url_replace(context, **kwargs): query = context['request'].GET.copy() for kwarg in kwargs: try: query.pop(kwarg) except KeyError: pass query.update(kwargs) return mark_safe(query.urlencode()) How to solve this problem? i think i need to change templatetags -
How to customize an error message for django-rest-framework-simplejwt blacklist()
I am trying to create a logout serializer that blacklist's the refresh token. But I got this error message: AssertionError: ValidationError raised by `LogoutSerializer`, but error key `incorrect_token` does not exist in the `error_messages` dictionary. I have tried adding the default_error_message dictionary as shown but it doesn't work class LogoutSerializer(serializers.Serializer): """ Serializes for user logout data""" refresh_token = serializers.CharField() default_error_message = { 'incorrect_token': ('Token is expired or invalid') } def validate(self, attrs): self.token = attrs['refresh_token'] return attrs def save(self, **kwargs): try: RefreshToken(self.token).blacklist() except TokenError: self.fail('incorrect_token') What is the correct way of solving this? -
Print items from a list using index of a for loop in jinja code
{% for index in length %} {{index}} <img src={{image_url.index}} width="200" height="250"> {% endfor %} length contains number list from 0 to 38 i.e. [0,1,2,......38] The image_url contains the list of image urls that I want show in my webpage. The {{index}} code run properly and show the index number from 0 to 38. But when I try to display image using {{image_url.index}} no image is displayed. Is there an solution for this? -
Nested Query Based on The Select Related in Django Models
I have two models where the second has a dependency on the first. The Structure is as follows. class Crop(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(null=True, blank=True) the other is class Plotting(models.Model): crop = models.ForeignKey( Crop, on_delete=models.CASCADE, limit_choices_to={"is_active": True} ) sowing_date = models.DateField(null=True, blank=True) harvesting_date = models.DateField(null=True, blank=True) acre = models.DecimalField( max_digits=10, decimal_places=2, default=0, help_text="Area in Acres" ) I want to fetch the data in the following format. CROP NAME | JAN | FEB | MAR | APR | MAY crop 1 | 20 | 10 | 35 | 45 | 35 crop 2 | 20 | 10 | 35 | 45 | 35 crop 3 | 20 | 10 | 35 | 45 | 35 crop 4 | 20 | 10 | 35 | 45 | 35 CROP 1 JAN defines the sum of acres harvested in January based on the harvesting_date. I also want to filter with dates -
How to get data from url parameter and pass them into template from class-based view
Hello I can't figure out how to get data from URL parameter and pass them from class-based view. Can you help me please ? urls.py urlpatterns = ([ path("edit_pages/<gameid>", views.edit_pages, name='edit_pages'), re_path(r"^ckeditor/", include("ckeditor_uploader.urls")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ) views.py class edit_pages(generic.FormView): form_class = forms.CkEditorForm template_name = "homeSuperuser/edit_pages.html" @method_decorator(login_required(login_url='/signin')) @method_decorator(user_passes_test(lambda u: u.is_staff)) def get_success_url(self,request, **kwargs): gameid = kwargs['gameid'] stages = Stage.objects.filter(game_id=gameid) return render(request, "edit_pages",{'stages': stages}) -
Data Fetching from websites [closed]
A college website has declared the result,you can login and check your result through your roll number, I have the roll numbers and I want the data of all students all at once, how can I fetch it through programming? -
failed to solve: rpc error: code = Unknown desc = failed commit on ref
I have a django application and I'm trying to run it using docker. But when I run docker-compose build the following error shows up: > [ 1/15] FROM docker.io/library/python:3.9@sha256:d084f55e2bfeb86ae8e1f3fbac55aad813c7c343c7cbacc91ee11a2d07c32d25: ------ failed to solve: rpc error: code = Unknown desc = failed commit on ref "layer-sha256:bf48494000001a037b72870d2a6a2536f9da8bc5d1ceddd72d79f4a51fe7a60e": "layer-sha256:bf48494000001a037b72870d2a6a2536f9da8bc5d1ceddd72d79f4a51fe7a60e" failed size validation: 2623870 != 10876505: failed precondition here is my Dockerfile: FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN apt update && apt install -y lsb-release && apt clean all RUN pip install --upgrade pip RUN pip install -r requirements.txt RUN apt -y update && apt -y install gettext RUN wget -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc RUN sudo apt-key add ACCC4CF8.asc RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" | tee /etc/apt/sources.list.d/pgdg.list RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg-testing main 13" | tee /etc/apt/sources.list.d/pgdg-testing.list RUN apt -y update && apt -y install postgresql-client-13 COPY . /code/ RUN chmod +x /code/entrypoint.sh1 ENTRYPOINT ["sh", "/code/entrypoint.sh"] here is my docker-compose.yml: version: '3' services: db: image: postgres environment: - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_PORT=${POSTGRES_PORT} volumes: - postgres-data:/var/lib/postgresql/data web: build: . command: bash -c "python manage.py runserver 0.0.0.0:8000" volumes: - .:/code - ./static:/static - ./media:/media ports: - ${PORT}:8000 depends_on: - db volumes: postgres-data: I'm … -
Django/Gunicorn Request Takes Long Time To Begin Processing View
Looking into optimizing my application's request times and have done a lot of work to implement caching, reduce duplicate db calls, etc. However looking at our monitoring tools I see sometimes it looks like the request takes an exceptionally long time to even begin processing the view. Wondering if there is a way to explain this? Its making it hard to set a consistent SLO for API requests. My understanding of gunicorn workers and threads is admittedly limited but I don't believe we would be hitting any limits on our current setup. That is really the only place I can imagine the bottleneck on proccessing the request would be ex: no more threads or workers available to process. Django = 3.2.15 Django Rest Framework = 3.13.1 gunicorn = 20.0.4 Start Command "gunicorn", "--workers=4", "--threads=8", "--bind=0.0.0.0:8000", "--worker-class=uvicorn.workers.UvicornWorker", "webapp.asgi:application" This is running on ECS load balanced between 2 c6g.xlarge instances (4 vCPUs). -
Invalid CSRF or Missing Token in DJango
I have already checked this link on Stackoverflow but still facing same issue: CSRF verification failed. Request aborted. on django About the issue I am trying to submit ajax request to DJango. Html Form <form id="frmLogin" method="post"> {% csrf_token %} <input type="text" name="username" /> <input type="password" autocomplete="false" name="password" /> <input type="submit" value="Submit" /> </form> Ajax var data = { "username": $(form).find("input[name='username']").val(), "password": $(form).find("input[name='password']").val(), "csrfmiddlewaretoken": $(form).find("input[name='csrfmiddlewaretoken']").val() }; $.ajax({ method: "POST", url: "/authenticate/", cache: false, async: true, data: JSON.stringify(data), contentType: "application/json; charset=utf-8", success: function(response) { } }) View from django.shortcuts import render import json from django.http import JsonResponse def Authenticate(request): if request.method == "POST": #loginData = json.loads(request.body) #email = userData["email"] #password = userData["password"] print("ok") return JsonResponse({}, status = 200) else: print("not ok") Payload Info Error Message Am I missing anything? -
Update default port for Django server
I would like to make the website built on Django server (hosted on AWS EC2 instance) as public. As a first step, I would want to update the default port from 0.0.0.0:8000 to 0.0.0.0:80 or 0.0.0.0. Every time I change port and run server, it gives me the below error: System check identified no issues (0 silenced). October 08, 2022 - 15:55:12 Django version 3.2.12, using settings 'config.settings' Starting development server at http://0.0.0.0:80/ Quit the server with CONTROL-C. Error: You don't have permission to access that port. If I use sudo or access it as root user, it gives me the following error: (venv) [ec2-user@ip-172-31-19-84 config]$ sudo python3 manage.py runserver 0.0.0.0:80 Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 14, in main "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? And as root user: (venv) [root@ip-172-31-19-84 config]# python3 … -
Django Constructing Form With Multiple Dictionaries
I'm using FormWizard, which returns a list of forms once they have all been completed. I have split 1 model into multiple forms. I clean the data in the list of forms and store it in another list. Using: profile_data = [] profile_data += [form.cleaned_data for form in form_list] Which gives me data like: profile_data = [{'activity_level': 0}, {'date_of_birth': datetime.date(2022, 10, 1), 'gender': 'M', 'height_feet': 6, 'height_inches': 1}] I then want to use this data to construct the main Profile form: new_profile_form = ProfileForm(profile_data[0], profile_data[1]) This does not work, as it causes the form validation to fail. I am able to get it working by manually getting each item like: new_profile_form = ProfileForm({ 'activity_level': profile_data[0]['activity_level'], 'height_feet': profile_data[1]['height_feet'], 'height_inches': profile_data[1]['height_inches'], 'gender': profile_data[1]['gender'], 'date_of_birth': profile_data[1]['date_of_birth']}) Why am I unable to do it the first way mentioned? -
Serialise python object with other objects as properties
I have a custom written object to represent a computational graph. It has a two lists containg vertices and edges. I need to serialise this graph object in order to store it into a SQLite database. What's the best way to serialise this object? Do I need to make functions to return a dictionary in each child? The issue is that each vertex contains edges attached to itself. And each edge object contains their start and end vertex/node. Do I need to rethink my Graph class. My issue right know is I cant recursively serialise each object and it's child as would never meet a finished state/condition! Any help would be appreciated, or if you need more info let me know!