Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting random object of a model with django-rest-framework after applying filters
So going based on this Stack Overflow question: Getting random object of a model with django-rest-framework I am trying to figure out how to do this, but after applying the filter backend. I have this class with these methods class DictionaryRandomView(generics.ListAPIView): def get_queryset(self): return Dictionary.objects.all() def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) And several filter backends (can include if desired). The problem is that I need to apply the filter backend before querying. Should I do this inside the list method, or the get_queryset method? For example, I have levels associated with a dictionary (for learning a language). I want to limit my query to ONLY words with say, level 6, but then get random values (a dynamic number that I can pass as a filter) inside that set. So pseudo-code for what I am trying to do would be something like this: get_random_value("SELECT * FROM dictionary WHERE level = 6") How can I do that in a DRF listAPIView? -
Filtering multiple M2M fields in a queryset - Django
I'm building a search bar for a crm software with DRF and NextJS. Here is a simplified version of my models. class Person(models.Model): name = models.CharField() contact_of = models.ForeignKey( Team, related_name='contacts' class Organization(models.Model): name = models.CharField() contact_of = models.ForeignKey( Team, related_name='org_contacts' class Team(models.Model): name = models.CharField() I want to get a search param and check if there are any organizations or people with that name and I'm struggling to create the appropriate queryset. This is what I tried(and failed) so far. class SearchView(generics.ListAPIView): def get_queryset(self): search = self.kwargs['search'] qs = Team.objects.filter( Q(contacts__name__icontains=search) | Q(org_contacts__name__icontains=search) ) ... A little help from my fellow Djangonauts would be appreciated. -
format='json' has no effect on APITestCase.client.get
I was testing my Django Rest Framework webserver using the APITestCase class. I have multiple tests with the same format and code. Even the backend for parsing the request is the same. But in the case below, it gives me a parse error. the test that gives me the error: def test_friends(self): data = {"type": "friends"} response = self.client.get(path=f"http://127.0.0.1:8000/api/friends", data=data, format='json') json_response = response.json() print(json_response) self.assertEqual(response.status_code, 200) The view for that test : class FriendsListView(APIView): authentication_classes = [authentication.TokenAuthentication, JWTAuthentication] permission_classes = (IsAuthenticated,) def get(self, request): print(request) data = JSONParser().parse(request) return JsonResponse({'the_type': data['type']}, status=200) Any helps that could help this? As I mentioned, I have multiple views with the same code. They work but this one does not work. Except this one is a get request with some JSON data. They are all put or post or delete. The error: {'detail': 'JSON parse error - Expecting value: line 1 column 1 (char 0)'} -
How to add image url field to an html form in django
I am creating a donation web application. Users are able to fill out a form and there donation is submitted into the database, I was wondering how I can have the user submit a url of an image and save it in the database, and then render it on another page. For example (the full form is down bellow), if the user fills out the form and submits a url like https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cmFuZG9tfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80, how would I save it to the database and render it out on another page? All help is appreciated. My code is down bellow. Html Form: <label class="label-input100" for="image">Image</label> <div class="wrap-input100"> <input id="phone" class="input100" type="text" name="image" placeholder="Please enter the url of your image" required> <span class="focus-input100"></span> </div> View: if request.method == "POST": image= request.POST['image'] return redirect('thankyou.html') Model: image = models.ImageField(null = True, blank = True) I am always on my computer so feel free to ask if you have any questions -
Django unable to add to ManyToMany field
I have Listings and Watch models. In Watch.listings is a ManyToManyField for Listings. When I try to add a listing to a watch instance it does not get added and I am getting no errors. in models.py: class Listings(models.Model): CATEGORY_CHOICES = [ ("None", "Optional"), ("Home", "Home"), ("Auto", "Auto"), ("Farm", "Farm"), ("Recreation", "Recreation"), ("Sporting Goods", "Sporting Goods"), ("Watercraft", "Watercraft"), ("Electronics", "Electronics") ] user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField(max_length=2000) photoURL = models.URLField(blank=True) category = models.CharField(max_length=15, choices=CATEGORY_CHOICES, blank=True) starting_bid = models.DecimalField(max_digits=12, decimal_places=2) highest_bid = models.DecimalField(max_digits=12, decimal_places=2, blank=True, default=0) date_created = models.DateField(auto_now_add=True) def __str__(self): return f"User: {self.user}, Listing: {self.title}." class Watch(models.Model): listings = models.ManyToManyField(Listings, related_name="watching", blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.user}, watching: {self.listings}" in views.py: def get_listing(listing_id): try: return Listings.objects.get(pk=listing_id) except: return None def get_watching(user): try: return Watch.objects.get(user=user) except Watch.DoesNotExist: return None def watch(request, listing_id): if request.method == "POST": if request.POST["watch"] == "watch": listing = get_listing(listing_id) if not listing: return HttpResponseBadRequest("Bad Request: listing does not exist.") watching = get_watching(request.user) if not watching: # save user to watch and add print("creating and saving to watch list") watch = Watch(user=request.user) watch.save() # saves no errors watch.listings.add(listing) # listing not added to watch print("watch = ", watch) # prints: watch … -
How to set SendGrid API key programmaticaly with Django Anymail
I'm writing multitenant application with Django Anymail and SendGrid. It works great when there is only one SendGrid API key, but every tenant have it's own API key. How can I set API key for every email message sent, so each tenant will use it's own key? I've tried this, but it won't work: msg = EmailMultiAlternatives(...) msg.connection = get_connection('anymail.backends.sendgrid.EmailBackend', api_key='THEACTUALTENANTAPIKEYHERE') msg.send() How can I set API key for every email message sent, so each tenant will use it's own key? -
Django Model From API Call
I would like to take advantage of an API that returns a JSON object. This object I would like to convert into a Django model so that I can interact with it just like a model, but instead of it storing it in the database, the API would act as the database. Is this possible? Does this require a custom "database" backend to accomplish it? The reason why I would like to map the data into a pseudo model is so that I can work with the data in class based views easier. -
Djongo ArrayReferenceField .add() strange behaviour
I have a model that has a Djongo ArrayReferenceField, and when I add elements with .add(), the elements goes to the start of the array and not to the end. For example: collection.elements.add(Element.objects.get(id=1)) collection.elements.add(Element.objects.get(id=2)) collection.elements.add(Element.objects.get(id=3)) And in mongo, the array will be in the order [3,2,1]. How can I avoid this behaviour? Thanks -
How to see posts using functions based view in django?
In my current django project I had to make a function to render the home page so that I could make a form in it, which form is in the base.html so that can be rendered in every page post of the website, the current code is this: def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, email, ['example@gmail.com'], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('home') return render(request, "index.html", {'form': form}) which works, but the view for every post is a class-based-view that display the form perfectly: class PostDetail(generic.DetailView): model = Post extra_context = {'form': ContactForm()} template_name = 'post_detail.html' The only problem is that the form in the homepage works because there is the code, the same code that I do not know how to call into a class (otherwise I would have used a class even for the home) for more detail the urls.py is: from django.urls import path from . import views urlpatterns = [ path('', views.contactView, name = 'home'), path('<slug:slug>/', views.PostDetail.as_view(), name = 'post_detail'), ] Basically, in the post form there is the slug that get added … -
Is it possible to generate hash from a queryset?
My idea is to create a hash of a queryset result. For example, product inventory. Each update of this stock would generate a hash. This use would be intended to only request this queryset in the API, when there is a change (example: a new product in invetory). Example for this use: no change, same hash - no request to get queryset there was change, different hash. Then a request will be made. This would be a feature designed for those who are consuming the data and not for the Django that is serving. Does this make any sense? I saw that in python there is a way to generate a hash from a tuple, in my case it would be to use the frozenset and generate the hash. I don't know if it's a good idea. -
Calculate Sum of aggregated fields in a Subquery
How can I calculate the sum of all aggregated fields in a subquery? For example, I have three models: A, B, C. B has FK to A. C has FK to B. I have a query: A.objects .annotate( total_revenue=Subquery( B.objects.filter(...) .revenue() .values("id") .annotate(b_renevue=Sum("revenue")) ) ) where B.revenue() is a method that sums up all related fields and then multiplies them by one of its fields. The problem is that revenue is aggregated and isn't calculated at the moment when I try to sum it. The original exception is : django.core.exceptions.FieldError: Cannot compute Sum('revenue'): 'revenue' is an aggregate -
How to link a field of a model to another models's field in django?
I want to link first_name and last_name field of my extended user model to the base User of Django so that changing the values of the fields in one model also affects the values in the other model. I have extended the Base User Model to store additional information about the user and I need to enable the users to edit all those values along with first_name and last_name with a single form. class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = "Linked to first_name of base User Model" last_name = "Linked to last_name of base User Model" other fields.... -
extends base html issue
i got main page at index.html , i want to transfer my template to base.html. I used {% extends 'base.html' %} at index.html , but he doesn't see this file with *Unresolved template reference ''base.html'' * folder of base.html: project/templates myproject/app/views.py from django.shortcuts import render def index(request): return render(request, 'mainsite/index.html') project/app/urls.py from django.urls import path from .views import * urlpatterns = [ path('', index, name='home'), ] project/setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainsite.apps.MainsiteConfig', ] project/url.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainsite.urls')), ] -
Wagtail Customising User Account Settings Form With One-to-One Model
I have a model in my app called "portal", in portal/models.py: from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from wagtail.snippets.models import register_snippet from wagtail.admin.edit_handlers import FieldPanel @register_snippet class StaffRoles(models.Model): role = models.CharField(max_length=154, unique=True, help_text="Create new staff roles here, these roles an be assigned to 'staff' users.") panels = [ FieldPanel('role'), ] def __str__(self): return self.role class Meta: verbose_name = "Staff Role" verbose_name_plural = "Staff Roles" @register_snippet class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=1024, blank=True) roles = models.ManyToManyField(StaffRoles, blank=True) def __str__(self): return str(self.user.first_name) + " " + str(self.user.last_name) class Meta: verbose_name = "Staff" verbose_name_plural = "Staff" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created and instance.is_superuser: Staff.objects.create(user=instance) Any new superuser is automatically given the Staff model. Any existing (non superuser) user can also be added as Staff. I want Staff members to be able to set a bio and a role. Roles can be added through the Snippets page in Wagtail admin. Right now, Staff is registered as a snippet, this means any Staff member can edit another Staff member's Staff attributes. I want to customise the Wagtail User Account Settings by adding a form to each user's respective … -
Understanding the purpose of an .env file with Django
Using Docker to deploy a Django + React application, and I've seen that best practice (or at least, one of the best practices) is to store certain pieces of information in an .env file, specifically database information. I am using this strategy now but I am still having trouble getting postgres to work. I am not sure if I still need to create the database locally on my system, or whether Docker handles it automatically. .env DB_NAME=animemusicsorter DB_PASSWORD=root DB_USER=waifuszn DB_HOST=postgres DB_PORT=5432 DEBUG=1 settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ.get("DB_NAME", "dbname"), "USER": os.environ.get("DB_USER", "dbuser"), "PASSWORD": os.environ.get("DB_PASSWORD", "dbpassword"), "HOST": os.environ.get("DB_HOST", "postgres"), "PORT": os.environ.get("DB_PORT", "5432"), } } Traceback postgres | 2021-07-12 17:21:19.630 UTC [34] FATAL: password authentication failed for user "waifuszn" postgres | 2021-07-12 17:21:19.630 UTC [34] DETAIL: Role "waifuszn" does not exist. -
Is there a build in login/logout endpoint in django rest?
I want to make a login functionality on my app for this i want a login end point does django rest have a built in end point or view to login (i will only be using it for BasicAuthentication). I found many ways online but they were for TokenAuth I just want BasicAuth -
Testing: TypeError: expected str, bytes or os.PathLike object, not NoneType
I'm testing user's creation but the test haven't reach the failed test because of the error given TypeError: expected str, bytes or os.PathLike object, not NoneType. I have the migrations using pass on using the AbstractUser giving the following on the migrations/0001initial.py file: # Generated by Django 3.1.4 on 2021-07-12 15:00 import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their … -
How to implement a fast temporary buffer for Django backend to make an online game?
I am making a "typing-race" online application with Django backend and ReactJS frontend. I wanna implement an online race-kinda logic where the users will be typing the given statements and their current progress will be shown to all other competitors. How should I implement this? Should I go with an AJAX implementation, where a user's progress is posted to the server periodically and other users' progress is fetched periodically? How can I store a current game's live state on the server? Should I use Django channels and WebSockets, but is that really necessary? -
Django 'context' for function-based and class-based views
Help me understand how to use Django's context--Is the issue related to the use of context in function-based vs class-based views: I have created two views (index and post_list) and respective templates (following the Assessment portion of the Mozilla Django Tutorial). The code for index works, but identical code for post_list doesn't. Why is that? view #1 def index(request): post_list = Post.objects.all() num_posts = Post.objects.all().count() num_comments = Comment.objects.all().count() num_authors = Author.objects.count() num_commenters = Commenter.objects.count() context = { 'num_posts': num_posts, 'num_comments': num_comments, 'num_authors': num_authors, 'num_commenters': num_commenters, 'post_list' : post_list, } return render(request, 'index.html', context=context) template #1 --Works: {% block content %} <h1>Index:</h1> This blog has a total of {{num_posts}} posts by {{ num_authors}} authors. {% endblock %} view #2 class PostListView(generic.ListView): model = Post post_list = Post.objects.all() num_posts = Post.objects.all().count() num_authors = Author.objects.count() template_name = 'blog/post_list.html' context = { 'num_posts': num_posts, #'num_authors': num_authors, # Removed b/c it doesn't work 'post_list' : post_list, } def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['num_authors'] = Author.objects.count() # But this works! template#2 - not totally working: {% block content %} <h1>All Posts:</h1> This blog has a total of {{num_posts}} posts by {{ num_authors}} authors. {% endblock %} -
Django __range function with date only returning first date
I want to return all Source objects within a date range, and the current query I have is sources = Source.objects.filter(datetime__range=(date(2013, 5, 15), date(2013, 5, 20))). However, the returned sources list only contains items from 2013-5-15. Any idea why this is happening? Sorry for the following code dump. views.py from django.shortcuts import render, redirect import os import json import pandas as pd import numpy as np import geopandas as gpd from .models import Source from datetime import date from .utils import df_to_geojson # Create your views here. def home(request): sources = Source.objects.filter(datetime__range=(date(2013, 5, 15), date(2013, 5, 20))) print('number of points: {}'.format(len(sources))) print(sources) sources_df = pd.DataFrame(list(sources.values())) source_gdf = gpd.GeoDataFrame(sources_df, geometry=gpd.points_from_xy(sources_df['lon'], sources_df['lat'])) points = df_to_geojson(sources_df, ['temp_BB', 'area'], 'lat', 'lon') print(sources_df.head()) defaultLon = -3.1883 defaultLat = 55.9533 return render(request, 'geoApp/home.html', { 'points': points, 'lon': defaultLon, 'lat': defaultLat, }) models.py from django.contrib.gis.db import models from django.contrib.gis.geos import Point from django.conf import settings import os import csv import pytz from decimal import Decimal # Create your models here. class Source(models.Model): id_key = models.CharField(blank=False, max_length=40, unique=True, null=True) lon = models.DecimalField(max_digits=14, decimal_places=6, default=999999) lat = models.DecimalField(max_digits=14, decimal_places=6, default=999999) temp_BB = models.IntegerField() area = models.DecimalField(max_digits=14, decimal_places=6, default=999999) datetime = models.DateTimeField(null=True) radiant_heat_intensity = models.DecimalField(max_digits=14, decimal_places=6, default=999999) radiant_heat = models.DecimalField(max_digits=14, … -
403 error when query param contains 2 byte character?
I am testing an API constucted via django views.py/urls.py format: where HttpResponse in views.py just returns filter_param, which is captured by some regex pattern defined in urls.py. I input some UTF-8 encoded char to test what is being captured by API, and receive an error in cases where the char requires more than one byte to encode. ex v1/.../filter/'%C2%A9'/ Returns: 403 Forbidden, expected copyright char But v1/.../filter/'%7E%7E'/ Returns: ~~ Therefore I know that this is not an issue of improperly formed regex. I am on python 2.x, and I read that python v2 only understands UTF-16. I tried this (%00%A9) query instead and received a not found error. Server is running Apache. I am new to django and unfamiliar with URI encoding standards, so any knowledge about the origin of this error would be helpful. -
Fetch API headers are not correctly received after GET request
I am using the Fetch API to download a file and the code to do that looks as follows: const response = fetch(`{% url 'export_xls' %}?${urlParams}`,{ method: 'GET', mode: 'cors', headers: { "X-CSRFToken": '{{ csrf_token }}', } }) .then(res => res.blob()) .then(blob => { let file = window.URL.createObjectURL(blob); window.location.assign(file); }) This does result in a downloaded file, however, the name of the file is randomized, instead of using the filename given in the Content-Disposition header. The headers, which I could see in the chrome dev tools are only the Content-Length and Content-Type, however, when I console log the headers of the response, the Content-Disposition header is there. The django view, which is being called with the fetch API sets the header, so I do not understand why the filename is not correct: response = FileResponse(buffer, as_attachment=True, filename="foo.xlsx") response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' response['Content-Disposition'] = 'attachment; filename="foo.xlsx' response['Access-Control-Expose-Headers'] = 'Content-Disposition' # I read it could be a CORS problem and this could solve it, however, no luck return response After some googling, I found multiple threads where people recommend using an a tag element and setting the download attribute, however, as the Content-Disposition header is set correctly, I would expect to have the … -
This is my html code can you help me how i convert my code into jquery
This is my html code: In this code i am displaying my blogs without ajax. In ajax, If i display my blogs without refresh page this code will mandatory in ajax calls so please help me how i write this code in jquery {% for blogs in blog %} <div class="card" id="card" style="width: 18rem;"> {% if ".jpg" in blogs.image.url or ".jpeg" in blogs.image.url or ".png" in blogs.image.url %} <img src="{{blogs.image.url}}" class="card-img-top" height="280" width="280" alt="..."> {% endif %} {% if '.mp3' in blogs.image.url %} <audio controls width="320" height="240"> <source src="{{blogs.image.url}}" type="audio/ogg"> </audio> {% endif %} {% if '.mp4' in blogs.image.url or '.mkv' in blogs.image.url or '.HDV*' in blogs.image.url %} <video width='400' controls> <source src="{{blogs.image.url}}" type='video/mp4'> Your browser does not support the video tag. </video> {% endif %} {% if '.3gp' in blogs.image.url or '.AVI*' in blogs.image.url %} <video width='400' controls> <source src="{{blogs.image.url}}" type='video/mp4'> Your browser does not support the video tag. </video> {% endif %} <div class="card-body"> <h5 class="card-title">{{blogs.title}} Written by {{blogs.author}} </h5> <h5 class="card-title">{{blogs.date}} | {{ blogs.time|time:"H:i" }}</h5> <p class="card-text">{{blogs.description}}</p> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group me-2" role="group" aria-label="First group"> <button type="button" data-sid="{{blogs.id}}" class="btn btn-success">Update</button> </div> <div class="btn-group me-2" role="group" aria-label="Second group"> <input type="button" data-sid="{{blogs.id}}" class="btn btn-danger" … -
Python recursion function to change the elements value
Example data = OrderedDict([('VaryasyonID', '22369'), ('StokKodu', '01277NUC'), ('Barkod', 'MG100009441'), ('StokAdedi', '1'), ('AlisFiyati', '272,00'), ('SatisFiyati', '272,00'), ('IndirimliFiyat', '126,00'), ('KDVDahil', 'true'), ('KdvOrani', '8'), ('ParaBirimi', 'TL'), ('ParaBirimiKodu', 'TRY'), ('Desi', '1'), ('EkSecenekOzellik', OrderedDict([('Ozellik', [OrderedDict([('@Tanim', 'Renk'), ('@Deger', 'Ten'), ('#text', 'Ten')]), OrderedDict([('@Tanim', 'Numara'), ('@Deger', '41'), ('#text', '41')])])]))]) It is an XML value if '#text' is inside the dict, it means the other tuples are attributes of the element. I have to insert data to db in this format. [{'@_value': 'Haki', '@_attributes': {'@Tanim': 'Renk', '@Deger': 'Haki'}}] I basically get the #text put in '@_value' key and other tuples inside the '@_attributes' dict. If dict doesn't contain '#text' then I save it as it is. Now if I do it with this function it works. def get_attrs_to_element(value): ## value type should be dict text_value = '' res = [] #check for attributes for key, val in value.items(): if '#text' in key: text_value = value['#text'] del value['#text'] attr_obj = { "@_value": text_value, "@_attributes": dict(value) } res.append(attr_obj) return res return value And I call this function where I am iterating over the whole XML as they are key value tuples. if isinstance(value, dict): whole_dict[key] = get_attrs_to_element(value) Now this works. But I also need this function to work when there is … -
How do i display the objects related to a foreign key in django
my models: class Company(models.Model): name = models.CharField(max_length=250) def __str__(self): return str(self.name) class Products(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="display") engine = models.CharField(max_length=250, blank=True) cyl = models.CharField(max_length=250, blank=True) bore = models.CharField(max_length=250, blank=True) def __str__(self): return str(self.engine) + " (ref:" + str(self.ref) + ")" my views.py: def Companies(request): context = { 'categories': Company.objects.all() } return render(request, 'product_list.html', context) HTML : {% for category in categories %} <h2>{{ category.name }}</h2> {% for item in category.item_set.all %} {{ item_engine }} {% endfor %} {% endfor %} how do i display every objects of Products(engine,cyl,bore) following its name