Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to manipulate Django Admin
I created this class: class Orcamento(models.Model): id = models.IntegerField(primary_key=True) Cliente = models.CharField(max_length=40, default=0) Cod_Cliente= models.CharField(max_length=40, default=0) N_Orcamento = models.CharField(max_length=40, default=0) Endereço = models.CharField(max_length=50, default=0) Email = models.CharField(max_length=40, default=0) Telefone = models.CharField(max_length=40, default=0) Departamento = models.CharField(max_length=40, default=0) Data = models.CharField(max_length=40, default=0) Revisao = models.IntegerField(default=0) #Serviços = models.CharField(max_length=100, default=0) Serviços = ArrayField(models.CharField(max_length=50),default=list, size=20) #função para usar o nome do objeto e não a instância def __str__(self) -> str: return self.Cliente But in the Admin page "Serviços" has just 1 field and not a array, how can I manipulate it? I want to enter with some date in more than 10 fields Image bellow: Djando Admin page -
Django get sum of value from list of objects in jsonfield
I have a model with the following implementation class MyModel(models.Model): data = models.JSONField(null=True, blank=True) The I have json in this format: { "name": "Name", "irrelevant_list": [], "items": [ { "name": "Name 1", "quantity": 1, "other_list_of_objects": [] }, { "name": "Name 2", "quantity": 2, "other_list_of_objects": [] } ] } I want to annotate db rows with the sum of quantity (i.e. quantity = 3 for this db row), I have tried multiple approaches, still not getting the right query. -
Sending emails with django and Celery - how to return error message if sending failed?
I'm using django with celery to send emails with verification code. I use third-party service (SendGrid) to send emails. If there is any error on the email server side (say, I exceeded a daily email limit) I want to tell users about that, but since celery is async and does not return the actual response from the server, how could I accomplish that? -
django.db.migrations.exceptions.NodeNotFoundError: Migration app.0172_auto_20220603_1746 dependencie _auto_20220601_2313')
I deleted some migration files that were giving me the error. Then when I write "python3 manage.py showmigrations" I get the following error: root@chat-manager:/var/www/jinabot# python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 419, in exe utility.execute() File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 413, in exe self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 354, in run_fro self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/makemigrations.py", l loader = MigrationLoader(None, ignore_no_migrations=True) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 259, in build_g self.graph.validate_consistency() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/graph.py", line 195, in validate [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/graph.py", line 195, in <listcom [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/graph.py", line 58, in raise_err raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration app.0172_auto_20220603_1746 dependencie _auto_20220601_2313') How to fix it? -
RelatedObjectDoesNotExist at /authentication/update-user-bio.html User has no user_bio
i have a userBio model class UserBio(models.Model): user=models.OneToOneField(User, verbose_name=("User's Bio"), on_delete=models.CASCADE,related_name='user_bio') user_profile_bio=models.TextField(max_length=200,null=True,default='This user has no Bio yet') def __str__(self): return self.user.username +"s' bio" When someone wants to update their bio; i want to create a userbio object and show it to them or pass to through the form. here's views.py def Userbio(request): form=form=UserBioForm(instance=request.user.user_bio) if not request.user.user_bio: txt='User Bio' a=UserBio.objects.create(user=request.user,user_profile_bio=txt) a.save() form=UserBioForm(instance=request.user.user_bio) if request.method == 'POST': form = UserBioForm(request.POST, instance=request.user.user_bio) if form.is_valid(): form.save() messages.success(request,'Change Saved succesfully!') return HttpResponseRedirect(reverse('profile')) return render(request, 'authentication/User_bio.html', context={'form':form}) but it says RelatedObjectDoesNotExist at /authentication/update-user-bio.html User has no user_bio. what's the problem here? Or you can help me in another way. How can i create an userbio object when someone signs up?if i can auto create an usebio object for everyone who signs up it would be better than this. -
Google oauth + django - cant authenticate from saved data
Okay, so i got the flow working, but it only works on the current session, if i try to load the data in, even with just a refresh the credentials dont hold up. So this works which is where oauth redirects to after user accepts prompts: def oauth_redir(request): u=Employee.objects.filter(dashboard_user=request.user) if not u: u=Employee.objects.create(dashboard_user=request.user) else: u=u[0] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES, state=request.GET.get("state")) flow.redirect_uri = REDIRECT_URL flow.fetch_token(authorization_response=request.build_absolute_uri().replace("http:","https:")) #saving credentials for future use credentials = flow.credentials if not Emp_google_creds.objects.filter(employee=u): Emp_google_creds.objects.create( token= credentials.token, refresh_token= credentials.refresh_token, token_uri = credentials.token_uri, client_id = credentials.client_id, client_secret= credentials.client_secret, scopes = " ".join(credentials.scopes), employee = u ) else: creds=Emp_google_creds.objects.get(employee=u) creds.token = credentials.token, creds.refresh_token = credentials.refresh_token, creds.token_uri = credentials.token_uri, creds.client_id = credentials.client_id, creds.client_secret = credentials.client_secret, creds.scopes = " ".join(credentials.scopes), creds.save() if not credentials or not credentials.valid: print(credentials, credentials.valid, credentials.expiry) # credentials.refresh(Request()) # return redirect("/calendar/cal_auth/") try: service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials) # Call the Calendar API now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: print('No upcoming events found.') return # Prints the start and name of the next 10 events for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) except … -
Problem when deploying Django with apache when running the server
I'm currently working on deploying a Django app with apache (on Debian server). I configured apache with mod_wsgi. I added my server IP in allowed_hosts in settings.py. Migrations done correctly. When I run the server : python manage.py runserver 0.0.0.0:8000 I get an infinite loop with the following message : "GET / HTTP/1.0" 302 0 I can't find a solution, any idea plz ? enter image description here -
what Django request.META is
I read a lot of articles about request.META but I didn't understand anything about it and what it does. Can anyone explain it? -
Problem when sending dictionary with ajax ( POST ) to python ( django views ) -> always empty
So i call this in the head of the html : <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> then with a button i call a function : <div> <button class= "button" type="ajax-call" onclick="getValue();">Envoyer</button> </div> And the function is : <script type="text/javascript"> function getValue(){ .... $.ajax({ url: "{% url 'sondage' %}", type : 'POST', dataType: "json", data: {heure_reponse: heure, jour_reponse: jour,habitude_reponse: habit, faim_reponse : faim, soif_reponse: soif, estomac_reponse:estomac, miam_reponse: miam, quantite_reponse: quantite, but_reponse: but, adresse_reponse: adresse, identifiant_reponse:identifiant } }) } </script> The problem is : When i write in the views.py of my django site ( python ) with from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from csv import writer from csv import QUOTE_MINIMAL @csrf_exempt @login_required def sondage(request): #Récupération des données par ajax reponses = request.POST.items() reponses = list(reponses) if len(reponses) == 0: print(" AJAX PROBLEME ") reponses.append(request.user.get_filename().split('/')[1].split('.')[0]) name = request.user.get_filename().split('/')[1].split('.')[0] #Ecriture dans le csv write_csv(reponses,name) #Appel de la page que l'on est en train de traiter return render(request, 'sondage.html',{'data':reponses}) def write_csv(data,name): #Ouverture en mode APPEND with open('uploads/questionnaire/sondage.csv', 'a', newline='', encoding="utf-8") as csvfile: csv_writer = writer(csvfile, delimiter=',') csv_writer.writerow(data) csvfile.close() I always have "AJAX PROBLEME" ! Why ? And how do we fix this ? -
How to create a registration form in Django that will recognise when password and confirm password don't match
I am trying to build a registration form for a user on a webpage using python and the Django framework. The form works fine and registers a user if all the fields are valid and Django has built in error messages if fields are left blank etc which work fine. However, I am trying to add my own error for if the 'password' and 'confirm password' fields don't match. If they don't match I get an error stating: 'The view main.views.register didn't return an HttpResponse object. It returned None instead.' My question is how would I successfully return the registration page with the error displayed to the user? Here is my views.py code: def register(request): if request.method == "GET": register_form = RegisterForm() return render(request, "main/register.html", { 'form': register_form }) else: register_form = RegisterForm(request.POST) if register_form.is_valid(): register_form.save() return render(request, "main/login.html") Here is my form.py code: class RegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] def clean(self): cleaned_data = super(RegisterForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: self.add_error("confirm_password", "Password does not match") -
Django + Twilio 500 Error (Session issue?)
I forked this Tutorial https://github.com/TwilioDevEd/automated-survey-django and am trying to get it to run locally. The current behavior is that, I send a text to the Twilio number and then it correctly texts me the first question of the survey. However, then when I text back, I don't get a response (should be the 2nd question of the survey) and I see a 500 error in Django. I can see that the second text message is being received by Django and, from the following function, it prints HELLO. However, it doesn't make it to YEP, so it appears to be erroring on answering_question = request.session.get('answering_question_id'), which seems like it is a problem with the session. I can see that there is a new session in the Django_session table created from my first text. I'm stuck on what is going wrong. request.session['answering_question_id'] is being set elsewhere in the code, but, my understanding, is if wasn't set, then answering_question would just be false, not an error. I'm stuck - any thoughts? def redirects_twilio_request_to_proper_endpoint(request): print("HELLO") answering_question = request.session.get('answering_question_id') print("YEP") if not answering_question: print('1') first_survey = Survey.objects.first() redirect_url = reverse('survey', kwargs={'survey_id': first_survey.id}) else: print('2') question = Question.objects.get(id=answering_question) redirect_url = reverse('save_response', kwargs={'survey_id': question.survey.id, 'question_id': question.id}) return … -
Signature Error with xmlsec on Windows with django_saml2_auth
I am following this tutorial to set up a SSO Login on Django. I have installed the xmlsec library from this link and everything seems correct but when testing the endpoint with Azure it throws this error: check_sig: ['C:\\Users\\user\\code\\project-backend\\env\\Scripts\\xmlsec.exe', '--verify', '--enabled-reference-uris', 'empty,same-doc', '--enabled-key-data', 'raw-x509-cert', '--pubkey-cert-pem', 'C:\\Users\\user\\AppData\\Local\\Temp\\tmpg9oixidy.pem', '--id-attr:ID', 'urn:oasis:names:tc:SAML:2.0:assertion:Assertion', '--node-id', 'xxxxxxx', '--output', 'C:\\Users\\user\\AppData\\Local\\Temp\\tmp4q_a_mb0.xml', 'C:\\Users\\user\\AppData\\Local\\Temp\\tmpybj2a3vf.xml'] correctly_signed_response: Failed to verify signature Signature Error: Failed to verify signature XML parse error: Failed to verify signature Internal Server Error: /sso/acs/ Internal Server Error: /sso/acs/ I've tried it on a Unix system and It works fine. -
Django, more type of user with other permission - I need advice
I need advice. I want make 3 types of user: member (only nickname/password/email) company (nickname/password/email/company/regon + permision for edit model) admin My question is aobut how make model for this users: make big model for member and company together but field which are only for comapny make empty for member. Next to by admin panel i can make group and add "comapny" ppl make 2 type of user (here i will need advice like what i should use on it) and seperate website register for member and company and login should be the same form Thank you for answer -
Can I use more than one name attribute in HTML tag?
I am doing a django project. But I wanted to have radio buttons grouped as well as name of the buttons to work with django. Is it okay to use two name attributes in one HTML tag? Will I be facing any errors if I do so? Below is my code I am stuck in. <input type="radio" name="group1" name="removePunc"> Remove Punctuations <br> -
List of child ID in django template
Here is my models.py: #child class Country(models.Model): name = models.CharField(max_length=255) wine_rg = models.ManyToManyField(WineRegion, blank=True) #parent class WorldRegion(models.Model): name = models.CharField(max_length=255) country = models.ManyToManyField(Country, blank=True) def __str__(self): return self.name views.py: world_region_filters = WorldRegion.objects.all() templates/test.html: {% for world_region in world_region_filters %} {{ world_region.name }} - {{ return list of country ID }} {% endfor %} How to return all country ID (child) on django template? I know I can do this: {% for country in world_region.country.all %} {{ country.id }} {% endfor %} But is there any way to make it shorter? I've tried this: {{ world_region.country.all.id }} But it doesn't work. Any suggestions? -
djano - can not display an uploaded image from mySQL database
I configured everything as it should and yet I can't display the images from my database. settings.py : STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) models.py class Etudiants(models.Model): numeroetudiant = models.BigIntegerField(db_column='numeroEtudiant', blank=True, null=True) # Field name made lowercase. nom = models.CharField(max_length=255, blank=True, null=True) prenom = models.CharField(max_length=255, blank=True, null=True) groupe = models.BigIntegerField(blank=True, null=True) photo = models.ImageField(blank=False, null=False, upload_to='images/') email = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'etudiants' def __str__(self): return self.nom + " " + self.prenom views.py : def ajoutetudiant(request): submitted = False if request.method == "POST": form = EtudiantsForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect("../ajoutetudiant/") else: form = EtudiantsForm() if 'submitted' in request.GET: submitted = True return render(request, 'ajoutetudiant.html', {'form': form}) urls.py (of my project) : from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('notes.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) .html : <img src="{{etudiant.photo.url}}"/> The pictures are saved in my database as you can see here. But cannot display it. My field in mySQL database is "blob". If it shouldn't be blob what should i put ? -
Django modal form not showing with HTMX
I have tried to replicate the example of this Github repository but the modal form won't display using HTMX. I'm really new to HTMX and I cannot figure out why. Here are my files: I use a Class Based View instead of a FBV in views.py: class UserAddReportView(LoginRequiredMixin, RequestFormMixin, CreateView): """ View to create a report. """ model = Report template_name = 'tool/add-report.html' form_class = ReportForm success_url = reverse_lazy('tool:home') def form_valid(self, form): self.object = form.save() self.request.session['report_id'] = self.object.pk if not self.object.slug: self.object.slug = slugify(str(self.object.company) + "-" + get_random_string(length=32)) date_f = self.request.session['date_f'] self.object.title = self.object.company.name + " " + date_f return super().form_valid(form) In models.py: class Report(models.Model): """ Class designed to create a report and assign it to a company. """ title = models.CharField(max_length=200, null=True, blank=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=255, blank=True) def __str__(self): return str(self.slug) In forms.py: class ReportForm(forms.ModelForm): """ Form to create a report. """ date = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) class Meta: model = Report fields = ['company', ] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request user = self.request.user self.initial['company'] = user.company def clean(self): super().clean() filtered_date = self.cleaned_data.get('date') month = filtered_date.month month = calendar.month_name[month] year = filtered_date.year date_f … -
How to correctly send data to the server from the table?
I apologize for possible grammatical errors, this text was translated through Google translate. I'm not very good at programming yet, I'm learning right away in practice. Now I'm making a Django web application for warehouse management. I have a select with a list of products that is loaded via api, and when the select is selected, a row with the product is added to the table success: function (res) { let invoiceRow = document.querySelector(".invoice-add-table table tbody tr.add-elements").insertAdjacentHTML('beforebegin', '<tr class="invoice-row">' + '<td align="right" class="fixed">'+ res.articul +'</td>' + '<td class="name" align="left"><span title="'+ res.name +'" style="text-decoration: underline; cursor: pointer;">'+ res.name +'</span></td>' + '<td align="right" class="fixed"><input name="quantity" value="1" class="ta-right fixed" type="text"></td>' + '<td align="right" class="fixed"><input name="last_buy_price" value="'+ res.last_buy_price +'" class="ta-right fixed" type="text"></td>' + '<td align="right" class="fixed"><input name="summ" value="" class="ta-right fixed" type="text"></td>' + '<td align="right" class="fixed"><input name="sell_price" value="'+ res.sell_price +'" class="ta-right fixed" type="text"></td>' + '<td align="right"><div style="display: flex;" class="edit-tool-table"><span class="iconify" data-icon="bx:trash" style="color: white;" data-width="20"></span></div></td>'+ '</tr>'); $(".add-items-select")[0].selectize.clear() Question: How do I identify each row to send it to the server, as well as the data in the inputs that are responsible for the quantity and price? There can be as many lines as you want, I don't understand how to get them on the server And … -
Multiple filters in django
I want to filter movies, that fit only to selected genres, for example: def get_queryset(self): queryset = Movie.objects.all() if 'genres' in self.request.GET: queryset = queryset.filter(genre__in=self.request.GET.getlist('genres')) return queryset This filter shows movies that fit into at least one to filter, but I want to show movies that are fit all of the selected genress like 'comedy, horror, fantasy' and all of the selected genres must be in the movie genres How cat I do this? -
How to roll up multiple rows filtered by a column value into a single row in Django?
I have a model for Notification: class VerbChoices(models.TextChoices): COMMENTED = 'commented' LIKE = 'like' id = models.CharField(primary_key=True, default=generate_id, max_length=255) actor = models.ForeignKey(Users, on_delete=models.DO_NOTHING, related_name='notify_actions', null=True) recipient = models.ForeignKey(Users, on_delete=models.DO_NOTHING, related_name='notifications') verb = models.CharField(max_length=255, choices=VerbChoices.choices) read = models.BooleanField(default=False) target_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) target_object_id = models.CharField(max_length=255) target = GenericForeignKey('target_content_type', 'target_object_id') created_at = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) I am trying to write a query which will return the count of rows with verb = LIKE, grouped by target_object_id. All the other rows should be without group by. Any help in this regard would be much appreciated. -
How to overrider Logger class with method to select log level and output line of the log
I need to record logs in many places of my Django application and I want to have it in a standardized way so that when people contribute they don't have to worry to much about it. So instead of calling: logger.info(<standardized message here>) I would like to write a function or probably a class that inherits Logger and selects the correct .info, .warning, .error and so on and outputs the message the way we want. So in the code I would only call log(request, 200, "info", "Success message") And the function I wrote looks like this: logger = logging.getLogger(__name__) def log(request=None, status_code=None, level=None, message=None): """ Create a log stream in a standardized format <request_path> <request_method> <status_code>: user <user_id> <message> """ method = request.method path = request.path user_id = None if not request.user.is_anonymous: user_id = request.user.id log = f"{path} {method} {status_code}: user {user_id} {message}" if level == 'info': logger_type = logger.info elif level == 'warning': logger_type = logger.warning elif level == 'error': logger_type = logger.error elif level == 'debug': logger_type = logger.debug return logger_type(log) The problem is that our log formatter also records the line in the code where the log happened, and because the log is called in the log … -
Axios post request to create a Django REST model with ForeignKey field
I am working on a NextJS + Django REST Framework project where I have two models; Document, MySource models.py class Document(models.Model): id = HashidAutoField(primary_key=True) title = models.CharField(max_length=100, default="Untitled") template = models.CharField(max_length=100, default="") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class MySource(models.Model): id = models.AutoField(primary_key=True) document = models.ForeignKey( Document, related_name="mysource", on_delete=models.CASCADE, null=True, blank=True, ) url = models.CharField(max_length=500, default="") title = models.CharField(max_length=500, default="", blank=True) publisher = models.CharField(max_length=500, default="", blank=True) desc = models.CharField(max_length=500, default="", blank=True) summary = models.CharField(max_length=500, default="", blank=True) I want to make an axios.post request that creates a MySource object that is linked to a document of a provided documented. Something like this: { "url": "aaaa", "title": "bbbb", "publisher": "bbbb", "desc": "bbbb", "summary": "bbbb", "document": "J9DY2pE" } Currently, making a POST request with the fields above will create the object but with document set to null. I can however select the document model manually from the admin panel below. [![admin panel][1]][1] Only after then, I get the desired axios.GET(documents) result like the following. "id": "J9DY2pE", "mysource": [ { "id": 16, "url": "google.com", etc. . . }, ], "title": "renamed title", "template": "commonapp", "updated": "2022-05-19T02:16:00+0000", "created": "2022-04-21T06:59:05+0000" Here's the rest of my code serializers.py from django.forms.models import model_to_dict class … -
How to order a related table using list of ids in Django
here is example of what I am trying to perform; class GroupA(models.Model): name=models.CharField(max_length=250) class GroupB(models.Model): category = models.CharField(max_length=250) group_a = models.ForeignKey(GroupA) I have list of ids; [1, 2, 3]. How do I perform an order of GroupA through GroupB using the list of ids. Currently, an example of data I am returning is; [ { "id": 3, "category": "Category 1", "group_a": [ { "id": 2, "name": "John" }, { "id": 1, "name": "Doe" }, { "id": 3, "name": "Jane" } ] } ] What I am trying to archive is order the data of group_a using list of ids; [1, 2, 3]. So it would return something like this; [ { "id": 3, "category": "Category 1", "group_a": [ { "id": 1, "name": "Doe" }, { "id": 2, "name": "John" }, { "id": 3, "name": "Jane" } ] } ] -
How to redirect user to vue app from django without forcing him to login second time?
Let's suppose I have a django app based on templates, but i want to make a button that redirects user to admin app made in Vue.js, what is the best way to redirect user to that vue service and not force him to login second time on that vue page? -
Is there a way to print only the data with the json key in python?
im trying to print a json in python "rules":[ { "table":"Forest", "format":"List", "header":{"en":"Forest","fr":"Forêt"}, "fields":[ { "name":"Name", "displayName":{"en":"Forest","fr":"Forêt"} }, { "name":"ForestMode", "displayName":{"en":"Forest Mode","fr":"Mode forêt"}, "ok":"re.search('Windows(2019|2016)Forest',x) != None", "warn":"re.search('Windows(2012R2|2012)Forest',x) != None", "nok":"re.search('Windows(2008R2|2008|2003|2003Interim|2000)Forest',x) != None", "comment":{"en":"Increase the functional level of the forest","fr":"Augmenter le niveau fonctionnel de la forêt"} }, { "name":"RootDomain", "displayName":{"en":"Root Domain","fr":"Domaine racine"} }, { "name":"Domains", "displayName":{"en":"Domains","fr":"Domaines"} }, { "name":"Sites", "displayName":{"en":"Sites","fr":"Sites"} }, { but i've run into an issue some of the json data doent have the key while some do i have written this thus far with open('./rules-adds.json', 'r') as ad_file: ad_data = json.load(ad_file) # print(ad_data) data = ad_data["rules"] # print(data) # print(json.dumps(ad_data, indent=4)) for x in data: print(x['table'], x['fields']) for y in x['fields']: print(y['name']) But i get an error since the first element of the json file doesn't have the "ok" key print(y['ok']) KeyError: 'ok'