Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overriding get_queryset(), get_context_data() method with get_object method and get_context_data() method in a Django DetailView
I have two models Employe and salaire, and my EmployeDetailView is based on the pk which is passed into the url : path('employe/<int:pk>', EmployeDetailView.as_view(), name='employe-detail'), My EmployeDetailView called by the above path : class EmployeDetailView(DetailView): model = Employe context_object_name = 'employe' today = datetime.now() def get_object(self): employe = get_object_or_404(Employe, matriculeemp__exact=self.kwargs['employe']) return self.model.objects.filter(employe=employe) def get_context_data(self, **kwargs): context = super(EmployeDetailView, self).get_context_data(**kwargs) employe = self.object context['salaire_list'] = Salaire.objects.filter(matriculeemp__matriculeemp=Employe.matriculeemp) return context My models Salaire and Employe : class Salaire(models.Model): date = models.DateField(db_column='Date') charge_patronale_mensuel = models.FloatField(db_column='Charge_Patronale_Mensuel', blank=True, null=False) charge_salariale_mensuel= models.FloatField(db_column='Charge_Salariale_Mensuel', blank=True, null=False) autre_charge_mensuel_fixe = models.FloatField(db_column='Autre_Charge_Mensuel_Fixe', blank=True, null=False) salaire_brut_mensuel = models.FloatField(db_column='Salaire_Brut_Mensuel', blank=True, null=False) matriculeemp = models.ForeignKey(Employe, models.DO_NOTHING, db_column='MatriculeEmp', blank=True, null=True) salaire_net_mensuel = models.FloatField(db_column='Salaire_Net_Mensuel', blank=True, null=False) charge_variable_mensuel = models.FloatField(db_column='Charge_Variable_Mensuel', blank=True, null=True) class Meta: db_table = 'salaire' ordering = ["date"] get_latest_by = 'date' class Employe(models.Model): matriculeemp = models.AutoField(db_column='MatriculeEmp', primary_key=True) nomemp = models.CharField(db_column='NomEmp', max_length=15, blank=True, null=True) prenomemp = models.CharField(db_column='PrenomEmp', max_length=15, blank=True, null=True) datenaissanceemp = models.DateField(db_column='DateNaissanceEmp', blank=True, null=True) dateembaucheemp = models.DateField(db_column='DateEmbaucheEmp', blank=True, null=True) genreemp = models.CharField(db_column='GenreEmp', max_length=10, blank=True, null=True) codefonc = models.ForeignKey('Fonction', models.DO_NOTHING, db_column='CodeFonc', blank=True, null=True) # Field name made lowercase. codecateg = models.ForeignKey(Categorie, models.DO_NOTHING, db_column='CodeCateg', blank=True, null=True) # Field name made lowercase. codeville = models.ForeignKey('VilleEmp', models.DO_NOTHING, db_column='CodeVille', blank=True, null=True) # Field name made lowercase. codedepartement = models.ForeignKey(DepartementEmp, models.DO_NOTHING, db_column='CodeDepartement', … -
Django error time out with multiple request
I am using runserver to run my Django app. Not too long ago I noticed that If there is a multiple request (lets say two user try to load the page in same time), the server freezes which means I get err_time_out error message in my browser. Is there any way to fix this problem? -
Django filter based on average of a field in reverse foreignkey
I have 2 classes, Product and Rating. class Product(models.Model): type = models.CharField(max_length=20) name = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) image = models.ImageField(upload_to = 'img/', default = 'img/no-img.png') slug = models.SlugField(unique=True, default = (randint(0,1000000))) def get_avg_rating(self): avg_rating = self.rate_set.all().aggregate(Avg('rating')) if avg_rating['rating__avg']: return round(avg_rating['rating__avg'],1) else: return 0 class Rate(models.Model): user = models.ForeignKey(User) product= models.ForeignKey(Product, blank=True, null=True) rating = models.DecimalField(max_digits=2, decimal_places=1, default=Decimal(0.0)) I'm trying to get the average ratings between two numbers, I have tried: Product.objects.filter(name__icontains=search, rate__rating__lte=rating[0], rate__rating__gte=rating[1]) The above didn't pick up any results from the database. The value of rating list is ['0', '6'], I have an object in the database with average rating of 2. The object isn't returned, and I get no errors. Is it possible to query the above at the database level, or should I do it in python? -
How to create client server streaming video?
I want to use WebRTC for min delay. I tried, but in my solution one connection use one port. How to do this? What to use? -
Django multiple databases tables not created
I've been working on separate apps and have now decided to regroup them in a single project. I've went through Django docs about multiple databases and various post on SO but I can't get this working. My problem is that tables are not created when I run manage.py migrate So far I've tried to drop the default database (containing migrations history) and empty every migrations folders. After that I ran makemigrations && migrate --fake && migrate as in this post. However though I get message success, tables are not created in PostgreSQL. Running migrations: Applying auth.0008_alter_user_username_max_length... FAKED Applying auth.0009_alter_user_last_name_max_length... FAKED Applying notifications.0001_initial... FAKED Applying sessions.0001_initial... FAKED Applying watson.0001_initial... FAKED (venv) C:\Users\USER\Documents\OutilsBU>python manage.py migrate Operations to perform: Apply all migrations: Chronos, Competences, Syc, admin, auth, contenttypes, notifications, sessions, watson Running migrations: No migrations to apply. If I re empty migrations folder and drop django DB and re ran makemigrations and migrate without fake step I just get this error (table not created). Operations to perform: Apply all migrations: Chronos, Competences, Syc, admin, auth, contenttypes, notifications, sessions, watson Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying Chronos.0001_initial... OK Applying Competences.0001_initial... OK Applying Syc.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying … -
how to do Group By between three or more tables in SQL or django
i have First Table called Header id | user_id -------------- 15 | 42 16 | 43 17 | 44 Second Table called Line line_id | ph_name | quantity ---------------------------- 15 | nokia | 3 16 | sumsung | 5 17 | nokia | 1 Third table called User_details id | name -------------- 42 | hi 43 | bye 44 | tata so how relate and group this to give out put like below based on the users count in SQL query or django aggregate { { "top":"nokia", "user":"2", "quantity":"4" }, { "top":"samsung", "user":"1", "quantity":"5" } } -
Trying to understand CBV's, but what is a good way to organize a single page with several models?
I know some about context data in views, but do you as a professional even use the built in CBV's, or how do you organize for example a profile app? In the profile view there can be one form for posting text, and one tag to display user details from a user model, and perhaps some other data from a profile model, and then maybe a list of the users friends and most popular posts and so on.. I find it really difficult to understand how to structure views for bigger projects. Are we not supposed to use ListView, CreateView, DetailView etc, in the same page, they are only for simple and fast usage for small websites? What is the standard way of doing this? Do you know of any github projects that are good examples that is not too big for a beginner to read? Thanks for your time and help. -
Displaying images in django template
I am querying images from the database and displaying them in HTML. My views.py is @login_required def viewall(request): context = RequestContext(request) images = Images.objects.all().order_by('-id') return render_to_response('cms/view-all.html',{'images':images,'media_url':settings.MEDIA_URL},context) My view-all.html is {% extends "cms/base.html" %} {% block title %} View-all {% endblock %} {% block main %} {% for image in images %} <img src="{{ media_url }}{{ image.file }}"> {% endfor %} {% endblock %} In settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media') My images are in the project directory file /media/images. But the images aren't getting displayed. I'm getting like this. What might be the problem here? -
I am working on two systems got error on one but working fine on another
same queryset i used on two systems: queryset=User.objects.filter(id__in=Setupuser.share_KB_with.through. objects.values_list("user_id").filter(setupuser_id=Setupuser. objects.values_list("id",flat=True).filter(email_id=current_user. email)[0])) Error list index out of range -
Send a javascript variable to django view
I am fetching the current url of the browser (which keeps changing) in a javascript variable (say var_url). I have a django model Url. I want to create its object using a view function create_url(). Earlier When I used a form, I used request.POST['field']. Now I don't have a form and I want to pass the value of var_url. How can that be done? -
django-comments-xtd not accessible with wagtail?
I have installed django-comments-xtd following the quick start guide in the documentation here. When I go to access the /comments URL, I only get a 404 error, and the message 'Raised by: wagtail.wagtailcore.views.serve'. I followed the documentation without issue, and have installed other apps that work fine such as django-machina. I am using django 1.11.13, python 2.7 and django-comments-xtd 2.1.0. Why would this particular URL not be accessible? Templates exist in the correct location. My files are setup exactly the same as in the documentation, happy to provide more info but not sure what to provide right now. -
Issue with adding Upload Handlers on the fly in Django
I am trying to add an upload handler on the fly following this documentation but receiving an error You cannot alter upload handlers after the upload has been processed. Here's my views.py # asset uploading view # @login_required(login_url='login/') @csrf_exempt def upload_asset_view(request): request.upload_handlers.insert(0, S3FileUploadHandler()) return _upload_asset_view(request) @csrf_protect def _upload_asset_view(request): # form has been uploaded POST if request.method == 'POST': form = UploadAssetForm(request.POST, request.FILES) if form.is_valid(): # store asset asset = store_asset(form, request) # print zip file details # zip_data = print_zip_file_details('https://3d-configurator.s3.amazonaws.com/' + asset.file.name) # textures = print_zip_file_details('http://roombuilder.s3.amazonaws.com/staging_bbby_google_ar/bbby_automation_backend/items/bbby-gltf-assets/133549_18660083_GLTF.zip') # add message to sqs # sqs_response = add_message_to_sqs(asset) pprint('done') # return render(request, 'dashboard/list_zip_data.html', { # 'textures': textures, # 'filename': asset.file.name # }) else: pprint('error') pprint(form.errors) # if GET, then get UploadAssetForm else: form = UploadAssetForm() return render(request, 'dashboard/form_upload_asset.html', { 'form': form }) and here's my template <form method="post" action="/" enctype="multipart/form-data">` <p class="lead">Please upload your zip file</p> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> I have used both csrf_exempt and csrf_protect decorators but still can't seem to find what the error could be. -
How to set detail & lookup_field in ViewSet in Django rest_framework?
I want to use two functions in one class. One function is detail=False, another one is detail=True. So i want to use two url pattern like these, /userinfo/users /userinfo/search/(search_key) but i get NoReverseMatch error like below, how can i solve this? error NoReverseMatch at /userinfo/users/ Reverse for 'userinfo-search' with no arguments not found. 1 pattern(s) tried: ['userinfo/(?P<search_key>[^/.]+)/search/$'] forms.py class ModelInfoForm(forms.Form): search_key = forms.CharField( required=True, widget=forms.TextInput( attrs={ 'placeholder': 'input keyword', 'class': 'form-control w-50 mr-sm-2', 'type': 'search', 'aria-label': 'search' } ) ) urls.py router = routers.SimpleRouter() router.register(r'userinfo', UserinfoViewSet, 'userinfo') view.py class UserinfoViewSet(viewsets.ModelViewSet): renderer_classes = [TemplateHTMLRenderer] template_name = 'user/userinfo.html' queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [AllowAny] lookup_field = 'search_key' @action(methods=['get'], detail=False) def users(self, request): form = ModelInfoForm(request.GET or None) serializer = UserSerializer(self.queryset, many=True) return Response({'users':serializer.data, 'form':form}) @action(methods=['post'], detail=True) def search(self, request): form = ModelInfoForm(request.POST or None) search_key = request.POST['search_key'] for user in self.queryset: if not search_key in user.username: self.queryset = self.queryset.exclude(username=user.username) serializer = UserSerializer(self.queryset, many=True) return Response({'users':serializer.data, 'form':form}) -
django is showing validation errors on its own error page
For form validation I need to send error messages, for that I am using validation error but instead of sending errors to template its showing validation error on its error page, you can see image. In my views def form_valid(self, form): user = get_current_user(self.request) review = self.request.POST.get('review') user_profile = get_object_or_404(UserProfileModel, display_username=self.kwargs['display_username']) ratings = get_object_or_404(Rating,user_profile_model=user_profile) try: usr_rating = UserRating.objects.get(rating=ratings, user = user) except UserRating.DoesNotExist: usr_rating = None if usr_rating: usr_rating.review = review usr_rating.save() else: raise forms.ValidationError('Please rate first') return super(UserProfileView,self).form_valid(form) In my template {% if not form.is_valid %} {% for error in form.errors %} error {% endfor %} {% endif %} I am unable to figure out the problem or I am confused to use form validation, please help me out. -
heroku run otree resetdb error
I am trying to run a app in Heroku and I get the next error, so I tried launching my database in postgresql but the error dont change, what can I do to fix this error? should I change my port in setting.py? Thanks Traceback (most recent call last): File "/app/.heroku/python/bin/otree", line 11, in <module> load_entry_point('otree==2.1.7', 'console_scripts', 'otree')() File "/app/.heroku/python/lib/python3.6/site-packages/otree_startup/__init__.py", line 147, in execute_from_command_line fetch_command(subcommand).run_from_argv(argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/otree/management/commands/resetdb.py", line 90, in handle tables = self._get_tables(db) File "/app/.heroku/python/lib/python3.6/site-packages/otree/management/commands/resetdb.py", line 58, in _get_tables call_command('inspectdb', database=db, no_color=True, stdout=out) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 130, in call_command return command.execute(*args, **defaults) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/inspectdb.py", line 32, in handle for line in self.handle_inspection(options): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/inspectdb.py", line 48, in handle_inspection with connection.cursor() as cursor: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, … -
How to install the package
Hey I'm studying Django tutorial Now I am in the Advanced tutorial process I packaged my app I wrote down what I did first I installed setuptools and pip and create a parent directory for polls, outside of your Django project. Call this directory django-polls Create a file django-polls/README.rst with the following contents mysite/django-polls/README.rst ===== Polls ===== Polls is a simpole Django app to conduct Web-based polls. For each question, visitors can choose between a fixed number of answers. Detailed documentation is in the "docs" directory. Quick start ----------- 1. Add "polls" to your INSTALLED_APPS setting like this:: INSTALLED_APPS = [ ... 'polls', ] 2. Include the polls URLconf in your project urls.p like this:: path('polls/', include('polls.urls')), 3. Run 'python manage.py migrate' to create the polls models. 4. Start the development server and visit http://127.0.0.1:8000/admin/ to create a poll (you'll need the Admin app enabled). 5. Visit http://127.0.0.1:8000/polls/ to participate in the poll. and create a django-polls/LICENSE file mysite/django-polls/LICENSE Copyright (c) Django Software Foundation and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above … -
monkey patch in django
I am trying monkey patch in django to assign rank to bloggers based on the sum of total blogs and total likes. I have tried the below method but not getting output. Can someone help.thanks. models.py class Blog(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blogs') slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1) likes = models.ManyToManyField(User, blank=True, related_name='blog_likes') title = models.CharField(max_length=100) def __str__(self): return self.title def count_blogs_of(user): return Blog.objects.filter(author=user).count() def total_likes_received(user): return user.blogs.aggregate(total_likes=Count('likes'))['total_likes'] or 0 views.py class BlogListView(ListView): model = Blog context_object_name = 'blog_list' def get_queryset(self): return (Blog.objects.filter(published_date__lte=timezone.now()) .order_by('-published_date') ) User.objects.annotate( nblogs=Count('blogs'), nrank=Func(F('nblogs') / 10, function='CEIL'), ).order_by('-nblogs') monkey_patching.py from django.contrib.auth import User RANK_TEXTS = ['zero', 'first', 'second', 'third'] def rank_text(self): nrank = getattr(self, 'nrank', None) if nrank is None: nrank = (Blog.objects(author=self).count() + 9) // 10 return RANK_TEXTS[nrank] User.rank_text = property(rank_text) -
Querying based on form input and string operations in django
This is a follow-up question for this question here. Django fields in form As question 4 in that describes, I need to get the form input and calculate design-id for each image uploaded. How do I query the database to get the abbreviation for category, fabric, manufacturer and manufacturer location and concatenate all these strings to generate and store the design id? Shall be thankful if someone gives the exact code. -
Build definition for Django app in VSTS
As the title said, I'm looking for a functional build definition for a Django 2.0.5 app in Visual Studio Team Services. What I'm trying to do is deploying my Django application to Azure App Services trough CI/CD, and the process is running well (I mean, the files is being traspased to production), but, for some reason, my app doesn't starts and I'm getting a lot of errors. I guess I'm traspassing the wrong files, but I really don't know it. ¿Can someone please tell me what did you do to build a Django app with CI/CD in VSTS? Thanks a lot in advance. Regards -
Geocode Form On Save
I'm trying to geocode the address on form save but, I'm having troubles. Here is my model: class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='dispensary') restaurant_name = models.CharField(max_length=500, blank=False) phone = models.CharField(max_length=500) logo = models.ImageField(upload_to= 'dispensary_logo/', blank=False) #Location street_address = models.CharField(default = '',max_length = 50, null = True) city = models.CharField(default='', max_length = 254,null=True,blank=True) state = models.CharField(default = '',max_length=25, null = True) zip_Code = models.IntegerField(null=False, default='') lat = models.DecimalField(max_digits=18, decimal_places=10, null=True) lng = models.DecimalField(max_digits=18, decimal_places=10, null=True) def __str__(self): return self.restaurant_name Here is the form: class RestaurantForm(forms.ModelForm): class Meta: model = Restauarant fields = ("restaurant_name", "phone", "logo", "street_address", "city", "state", "zip_Code") def save(self): if not self.lat or not self.lng: self.lat, self.lng = self.geocode(self.address) super(Restaurant, self).save() def geocode(self, address): address = urllib.parse.quote_plus(address) maps_api_url = "?".join([ "http://maps.googleapis.com/maps/api/geocode/json", urllib.parse.urlencode(street_address, city, state, zip_code) ]) response = urllib.urlopen(maps_api_url) data = json.loads(response.read().decode('utf8')) if data['status'] == 'OK': lat = data['results'][0]['geometry']['restaurant']['lat'] lng = data['results'][0]['geometry']['restaurant']['lng'] return Decimal(lat), Decimal(lng) # Creates instance of form. Once the form is created, we can go back and edit that form. def __init__(self, *args, **kwargs): super(RestaurantForm, self).__init__(*args, **kwargs) if kwargs.get('instance'): self.fields['logo'].required = False I keep getting the error that the "return Decimal(lat), Decimal(lng)" is out of the function but, I'm not sure why. Any advisement would … -
In django how to iterate and populate selected options value
Models.py from django.db import models class World(models.Model): country = models.CharField(max_length=200) Language = models.CharField(max_length=200) Populations = models.CharField(max_length=200) view.py from django.shortcuts import render from app_one.models import World def index(request): countries = World.objects.order_by('country') all_countries = {'list_countries':countries} return render(request,'app_one/index.html',context=all_suburbs) index.html {% if list_countries %} <select> {% for li in list_countries %} <option value="{{ li.country }}">{{ li.country }}</option> {% endfor %} </select> <p>"selected country's Language is "{{ li.language }}" </p> <p>"selected country's Population is "{{ li.populations }}" </p> {% else %} <p>No suburbs found</p> {% endif %} Once the country is selected by user I am not able to populate the language and population of the selected country. -
How can I perform ManyToOne without ForeignKey in db?
eb_config_object = models.ForeignKey(EbConfig, on_delete=models.CASCADE) I want to serialize an object, which includes another object. But the problem is in my design concept I can not allow ForeignKey(Hard foreign key) exist in my database(MySQL). Is there any method to perform that in Django2.x? -
Django: Is it possible/feasible to create a type2 table
So, I've used type 2 tables in other environments to capture record status at different points in time. Is it possible to create a type2 (Valid from, valid to) table in django? This is more theoretical than actual, but I'm considering doing this for a project. Suppose I have a model that has a status field (created, paid, shipped, completed, etc..) How can I make this/update this as as a type 2 table. ORDER_STATUS_CHOICES = ( ('blank', 'Blank'), ('created','Created'), ('paid', 'Paid'), ('shipped', 'Shipped'), ) Class Order(models.Model): status = models.CharField(max_length=120, default='created', choices=ORDER_STATUS_CHOICES) order_id = models.CharField(max_length=120, blank=True) valid_from_dt = models.DateField(default=timezone.now, blank=True, null=True) valid_to_dt = models.DateField(default=timezone.now, blank=True, null=True) Now that I'm thinking of it, I think the flow would be that whenever a status change is made to update the existing record's valid_to_dt and then create a new record using same order_id, other data, new status new valid_from_dt and '9999-12-31' valid_to_dt. It seems straight forward. Is there anything I'm missing like Django (sqlite3) is horrible at Type 2 tables? -
Slug field RecursionError
In my Django project, I want to create slug field from the title. For example: title = Arduino UNO slug = arduino-uno And if the slug field exists into my DB then I want to append a digit For example: arduino-uno2 Here is title to slug generator logic: def create_slug(title): qs = IndividualProduct.objects.filter(slug=title) if qs.exists(): title = title + str(qs.last().id) create_slug(title) else: return title def slug_generator_for_image_folder(sender, instance, *args, **kwargs): if instance.slug == None: title = slugify(instance.title) instance.slug = create_slug(title) instance.save() else: pass pre_save.connect(slug_generator_for_image_folder, sender=IndividualProduct) But this code is exceeding maximum recursion limit if I want to add a digit. If I make the change of the code from if qs.exists(): ..... else: return title to if qs.exists(): ..... return title Then it is working perfectly. I have tried both the code into python shell and it is working perfectly. I am not understanding why it is not working into my Django models. -
How to save and show on DetailView data associated with another data
I'd really appreciate any help. I have the following code: views.py: class Booklist(ListView): model = Book template_name='books/books.html' def get_context_data(self, **kwargs): context = super(BookList, self).get_context_data(**kwargs) context['form'] = CreatePost.PostForm return context def post(self, request, *args, **kwargs): form = CreatePost.PostForm(request.POST) if form.is_valid(): form.save() return render(request, self.template_name, {'form': form }) class CreatePost(CreateView): template_name_suffix='_create' class PostForm(ModelForm): class Meta: model = Post fields = ['post'] widgets = { 'post': forms.Textarea() } class Posts(DetailView): model = Book template_name='books/post_create.html' slug_field = 'id' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['posts'] = Post.objects.all() return context ... How can I save and show post data associated with each book? Right now the program shows the book list well enough and, after saving post through the form that's on each book item and clicking on the book item, shows the post list (on the DetailView of the book item). But no matter which book item is clicked, all the posts are showing. And the posts are saved only in association with the first book no matter where you save it. I would like to save the post to be associated with the specific book, on whom is the form that's used to create the post. And I'd like to show (on DetailView …