Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Struggling with connection between Django and Postgres within Docker containers
I've been hitting the following error for awhile now and can't seem to fix it... django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? Multiple resources stated it was simply due to the HOST setting within my DATABASES, but the following is what I am working with and still can't get it to work: DATABASES = { 'default': { 'HOST': 'db', 'ENGINE': 'django_postgrespool2', 'NAME': os.environ.get('PROJECT_HEARSAY_DB_NAME'), 'USER': os.environ.get('PROJECT_HEARSAY_DB_USER'), 'PASSWORD': os.environ.get('PROJECT_HEARSAY_DB_PASSWORD'), 'PORT': os.environ.get('PROJECT_HEARSAY_DB_PORT'), } } Here is the Dockerfile for my Django app: FROM python:3 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip install --upgrade pip RUN pip install -r requirements.txt Here is the Dockerfile for my Postgresql DB: FROM postgres And here is the docker-compose.yml that I am working with: version: "3" services: postgresql: build: context: ./db container_name: db.postgresql ports: - 5432:5432 environment: POSTGRES_DB: "db_name" POSTGRES_USER: "username" POSTGRES_PASSWORD: "password" django: restart: always build: context: ./api command: bash -c "./manage.py migrate && ./manage.py runserver 0.0.0.0:8000" container_name: api.django ports: - 8000:8000 depends_on: - postgresql I'm curious if anyone here could shed some light on what I am doing wrong. Thank you. -
How to create multiple datetimepickers in django template (for loop) and jquery
I am having trouble getting django to display multiple datetimepickers in tabs on a html page. I can get them to work if I specify each element in the jquery outside of a loop, but when I put it in a loop, they don't show (only shows an empty input text box). As this has to be done on an array of varying sizes (min length of 1 and no max), I can't hard code each individual datetimepicker. The for loop on the django template html page works, and each tab and the sections where the datetimepickers go is made, but the jquery won't work. I have tried to make the 4 datetimepickers via a loop (4 per tab, can have 1+ tabs), and they don't create the datetimepicker object. Just creates a input text box. I have also tried putting them all into a class=datetimepicker, which does work, but then I can't add in default data from the array to fill in each datetimepicker, as the only function in jquery is a single one calling the class .datetimepicker. Tried $('#date1').datetimepicker({ defaultDate: array[counter][0] }) in an array to fill in each tab for the date1 datetimepicker, and that does not … -
MySql errors while executing queries on a Django project on AWS Lambda function
I have a Django project hosted on AWS Lambda function. This microservice uses pymysql to connect to AWS Aurora RDS database. This service executes one and only one query over and over again. 1 in 200 times the query fails with EOF packet error. In order to investigate this issue i have implemented a "repeater" which would repeat the same query if one fails (maximum 2 repeats with 0.25 seconds delay). Once again, in a rare ocasion, a query has failed and I expected to see a successful query after the first reattempt. However it failed in all 3 consecutive calls with all DIFFERENT error messages. Error messages (in order): AssertionError: Protocol error, expecting EOF django.db.utils.InternalError: Packet sequence number wrong - got 24 expected 1 django.db.utils.InterfaceError: (0, '') These are errors from 3 separate queries executed against MySql Aurora RDS database. (I just wanted to ephesize that indeed it is not a stack trace but rather different query errors). More useful info: The microservice uses Django ORM to create queries. The database is in Master-Slave configuration and those queries go against a Slave database. The parameters observed in Master and Slave databases (such as CPU usage, free RAM space, various … -
Submit a form, force download a pdf, after that redirect to another page, can we do this without using frontend/js?
I have a post form, I want to download a pdf receipt after submitting form, and then redirect to another page. form.submit >> force downlaod pdf >>> redirect. and I want to do this only at the server-side, is there any idea to do this without using js. -
Serialize related object before primary key is created
So I have a serializer which I have added a custom create method for, because I am using it to insert objects for a many-to-many relationship and am using nested serializers for this. As it stands, when I try to create and object using the DocumentSerializer, I get a "document":["This field is required."] error, because when the documentdomain_set variable is declared, the associated document has yet to be created, and therefore there is no id to be used in the relation. I obviously know how to capture this document_id after saving the new document object, but I am not sure what the best practice is to handle the variable initiation as it stands. Thanks! class DocumentDomainSerializer(serializers.ModelSerializer): domain = serializers.SerializerMethodField('get_domain_id') class Meta: model = DocumentDomain fields = ('document_id', 'domain_id') class DocumentSerializer(serializers.ModelSerializer): documentdomain_set = DocumentDomainSerializer(many=True, required=False) class Meta: model = Document fields = ( 'documentdomain_set', 'id', 'text', 'uploaded_at') extra_kwargs = { 'id': {'read_only': True}, 'uploaded_at': {'read_only': True} } def create(self, validated_data): documentdomain_set = documentdomain_set.pop('documentdomain_set', []) # create document first document = Document.objects.create(**validated_data) # serialize associated domains for documentdomain in documentdomain_set: # get ID of newly-created document, use for relation documentdomain['document_id'] = document DocumentDomain.objects.create(**documentdomain) return document -
Getting "Bad Request" on the post request to Django Rest-Api using serializers
I am trying to save data into a model using django-rest framework. I have already written the api, it works fine when i access it directly using the url to api. But I get a bad-request error when i try to post data using ajax. If it is working fine when data is inserted using the api interface, it should work fine when data is inserted using ajax....but instead i am getting a bad request. here is the AJAX request method(Jquery): $("form").submit(function(event){ event.preventDefault(); var this_ = $(this); var formData =this_.serialize(); $.ajax({ url: "/api/forum/posts/{{ post_question.thread_id.id }}/create", data: formData, method: "POST", success: function (data) { console.log("successfully returned"); console.log(data); displayPosts(); }, }) Serializers are as follow, in api/serializers.py : class ThreadModelSerializer(serializers.ModelSerializer): created_by = UserDisplaySerializer(read_only=True) class Meta: model = Thread fields = '__all__' class PostModelSerializer(serializers.ModelSerializer): posted_by = UserDisplaySerializer(read_only=True) class Meta: model = Post fields = '__all__' Models for the Post and Thread are as follow in models.py: class Thread(models.Model): thread_subject = models.CharField(max_length=250) posted_on = models.DateTimeField(auto_now=True) category = models.CharField(max_length=250) forum_id = models.ForeignKey(Forum, on_delete=models.CASCADE) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Post(models.Model): post_message = models.TextField() thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE) parent_id = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) posted_on = models.DateTimeField(auto_now=True) posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and finally the API view is … -
Python django TypeError at /cart/update/ 'NoneType' object is not iterable
enter image description here Hello I have the following error on my browser: TypeError at /cart/update/ 'NoneType' object is not iterable Exception Location: C:\Users\Gijs Machielsen\dev\ecommerce\src\carts\views.py in cart_update, line 19 ########## my views.py contains the following code: from django.shortcuts import render, redirect from products.models import Product from .models import Cart def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, "carts/home.html", {"cart": cart_obj}) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message, product is gone ") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) !!!! line 19 if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) return redirect("cart:home") ## models.py is the following: from decimal import Decimal from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated(): user_obj = user return self.model.objects.create(user=user_obj) Create your models here. class Cart(models.Model): user … -
Page not found after trying to add a new path to the urlpatterns of main urls.py file? (Mosh Python Tutorial)
I'm following Mosh's tutorial video on Python. He begins the django section (https://youtu.be/_uQrJ0TkZlc?t=18085) by installing django 2.1. I am able to open a development server the first time as he does: pip install django==2.1 django-admin startproject pyshop . python manage.py runserver #server works Here are the steps he goes through to add a "products" app/path: python manage.py startapp products Opens views.py from this new products folder and modifies code to this: from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') Creates urls.py inside the products app/folder and adds this code: from django.urls import path from . import views urlpatterns = [ path(' ', views.index) ] Opens the main urls.py in the pyshop folder and adds/modifies the end of the file like this: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) ] Mosh goes back to the server and adds /python to the url to get a page with "Hello World" (https://youtu.be/_uQrJ0TkZlc?t=19220) Upon trying to run the server again, I get Page not found error. Is there something I'm missing? I didn't figure it'd be a version issue since I made sure and installed the same 2.1 version. -
Adding a profile to user in django
Following this : https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone I am having some trouble with this call: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) In their example I am guessing this works as is on the signup of a new account because the Profile in their example has all fields that can be blank and null. In my case my profile I am trying to maintain here is called: class APOUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.InstitutionMember", on_delete=models.PROTECT) gender = models.ForeignKey("mainpage.GenderTable", on_delete=models.PROTECT) on_site_status = models.ForeignKey("mainpage.SiteStatus", on_delete=models.PROTECT) refer_to_as = models.TextField(max_length = 30, blank=True) #if the above is custom room_preference = models.ForeignKey("housing.Room", on_delete=models.PROTECT) Which has references to ultimately what will be drop downs to select form a form (populated by another table with defaults). So do I remove the @reciever and then just have the users fill out the profile separately somehow after they signup and confirm their account? I tried to mix my signup form with the profile form... but kept getting an anonmyous user object had no attribute object apouser in the views.py when I try to mix the signup forms and profile forms: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) profile_form = ProfileForm(request.POST, instance=request.user.apouser) if form.is_valid() and profile_form.is_valid(): … -
convert page to pdf and render on screen
I can convert a page to pdf perfectly, however, I need to render a graphic that is made with javascript, in this case I first need to render the page to be able to compile to pdf and render on screen, could someone help me? I am using lib django-weasyprint -
How to change default image in Django
I have a django app that allows users to fill out a form, and attach an image if they like. If they decide not to attach an image, I want a default image in it's place. The problem is that when the user tries to attach an image during the post creation, it doesn't save. It only saves when the post is edited. model field: image = models.ImageField(upload_to='images/', default = 'noImageAttached.png') This works as expected when a user creates a new post and does not add a new image. The default image 'noImageAttached.png' is used. However, when someone wants to attach an image in theCreateView it will not throw any errors, it just will simply not save the image. When this same post is edited with UpdateView, you can upload an image, and it works. Something in my CreateView is causing it to not work? Or maybe there is a different way of using default in models.py? views.py class assetCreateView(LoginRequiredMixin,CreateView): model = Assets form_class = Asset_Creation_Form template_name = 'addAsset.html' login_url = 'login' success_url = reverse_lazy('home') #these fields are hidden from user, and filled out automatically def form_valid(self, form): form.instance.createdBy = (self.request.user.first_name)+ " "+ (self.request.user.last_name) return super().form_valid(form) -
Postback, filters and sorting data in an App using Django and AJAX
I keep having this problem where I can't order some tables by date. I'm reading this code, I didn't write it so it will be useful if anyone can give me some tips. If I miss some information, just ask me, please. The ListView code: cursor = connections['default'].cursor() start = request.GET['start'] length = int(request.GET['length']) page = int(request.GET['draw']) poll = Poll.objects.get(id=poll_id) if not can_access_poll(request, poll): return JsonResponse({"error": "An error occurred"}) date_from = None period = None date_condition_shown = '' if request.GET.get("period"): period = request.GET['period'] if period and period != 'Total': date_condition, date_condition_shown, date_previous_condition, days_difference, date_from, date_to, filtering_by_date, date_from_previous, date_to_previous, date_from_string, date_from_previous_string = build_dates( period, None) if 'venue_id' in request.GET and request.GET['venue_id'] != '0' and request.GET['venue_id'] != 'undefined': filter_venue_id = request.GET['venue_id'] elif venue_id: filter_venue_id = venue_id else: filter_venue_id = None try: total = PollUser.objects.filter(poll=poll, completed=True).count() query = 'Select v.shown_on, v.source, u.first_name, u.last_name, p.id, v.id, ve.name ' \ 'From app_polluser v ' \ 'Inner join app_customuser u on u.id = v.user_id ' \ 'Inner join app_userprofile p on p.user_id = u.id ' query += 'Left join app_session s on v.session_id = s.id ' query += 'Left join app_router r on s.router_id = r.id ' query += 'Left join app_venue ve on r.venue_id = … -
How to access get request data in django rest framework
How to access GET request data in django rest framework. In the docs, they have mentioned "For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET" https://www.django-rest-framework.org/api-guide/requests/ But when I use request.query_params.get('some_vaue') it gives me none even though I pass the data in the request body. sample code example: class TestView(APIView): def get(self, request): test = request.query_params.get('test') print('data',test) ... ... ... When I pass some value in the body of the request in postman and print the value, it actually prints None. -
Django gives 404 Error from previous project
When I'm trying to start new Django project and to run server I have "SOURCE /lo-fi-radio HTTP/1.0" 404 1987 But it's fully new empty project with its own virtualenv. lo-fi-radio is the root directory of my previous project. There are another strange errors too. Full log: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 02, 2019 - 17:32:41 Django version 2.2.6, using settings 'company_db_manager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: /lo-fi-radio [02/Oct/2019 17:32:45] "SOURCE /lo-fi-radio HTTP/1.0" 404 1987 Traceback (most recent call last): File "/usr/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.6/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib/python3.6/wsgiref/handlers.py", line 274, in write self.send_headers() File "/usr/lib/python3.6/wsgiref/handlers.py", line 333, in send_headers self._write(bytes(self.headers)) File "/usr/lib/python3.6/wsgiref/handlers.py", line 453, in _write result = self.stdout.write(data) File "/usr/lib/python3.6/socketserver.py", line 803, in write self._sock.sendall(b) ConnectionResetError: [Errno 104] Connection reset by peer [02/Oct/2019 17:32:45] "SOURCE /lo-fi-radio HTTP/1.0" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 36856) Traceback (most recent call last): … -
How to add Q search filter in subquery
How to add a Q search filter on this view subquery. def inventary(request): credits = Credit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_credits=Sum('amount')) debits = Debit.objects.filter(account=OuterRef('pk')).values('account_id').annotate(sum_debits=Sum('amount')) dif =Account.objects.annotate(credit_sum=Subquery(credits.values('sum_credits')),debit_sum=Subquery(debits.values('sum_debits')),balance=F('credit_sum') F('debit_sum')).values_list('name', 'balance') context = { 'credits ': credits , 'debits ': debits , 'dif': dif, } return render(request, 'inventary/inventary.html', context) -
How can I filter out objects where todays date falls within a range of a calculated date?
Here is the code I currently have. models = Model.objects.annotate( start_range=ExpressionWrapper( F('the_date') + datetime.timedelta(days=-7), output_field=DateField(), ), end_range=ExpressionWrapper( F('the_date') + datetime.timedelta(days=-2), output_field=DateField(), ) ).filter( F('today')__range=[F('start_range'), F('end_range')] ) Obviously I can not do a range on F('now') because it's not a database column / keyword but I'm just showing that I have a variable called today that I'm trying to compare against. I feel like I'm close but could use some help wrapping this up. Note: -7 and -2 will be dynamic days but just hardcoded for example. -
In django mapping how to get complete count of choice filed
I want the Count of My (Booking Type) I have 3 Types of choices (choice field in Model) Individual, Group, and Certificate. d1 = Booking.objects.values('booking_type').annotate(booking_count=Count('booking_type')) {f.get('booking_type'): f.get('booking_count') for f in d1} Here below is the Output of Above: But why the code Will Cant give me the Count of Certificate {'GROUP': 2, 'INDIVIDUAL': 3} I Changed Values To filter also But Nothing Works -
Cannot move URL to import URL in Django
django 2.2.5 I haven't been having problems moving urls until now. reporting/reporting.html (index): ... {% url "line_chart_json" %} ... reporting/views.py class LineChartJSONView(BaseLineChartView): def get_labels(self): """Return 7 labels for the x-axis.""" return ["January", "February", "March", "April", "May", "June", "July"] .... When it's in the main app url.py, it's fine from django.urls import path, include from reporting.views import LineChartJSONView urlpatterns = [ ... path('reporting/', include('reporting.urls')), path('line_chart/json/', LineChartJSONView.as_view(), name='line_chart_json'), ] When I move it to reporting from django.urls import path from . import views from .views import LineChartJSONView app_name = 'reporting' urlpatterns = [ path('', views.summary_properties_user, name='index'), path('line_chart/json/', LineChartJSONView.as_view(), name='line_chart_json'), ] I get an error coming back from it's use on reporting.html: NoReverseMatch at /reporting/ Reverse for 'line_chart_json' not found. 'line_chart_json' is not a valid view function or pattern name. I assume a simple oversight. Only a few weeks in, and Django URLs are still something to get my head around. -
How to show a message dynamically in a django app?
I've created a webapp using django where in one of the section I asks for user's feedback and on clicking the submit button I send user an email thanking him for feedback. But every time I click on submit, the page refreshes itself, the email get delivered successfully But What I want is when user click on submit I want to show a "Thank you" message right there in place of feedback form. and feedback form to get removed Here's a section of my index.html <form action="" method="POST"> {% csrf_token %} <div>{{ form.message }}</div> <div>{{ form.email }}</div> <p class="formerrors" >{{ form.email.errors.as_text }}</p> <hr> <input id="submitbutton" type="submit" name="submit" value="Submit"> </form> here's my view def index(request): if request.method == 'POST': form = FeedbackForm(request.POST) if form.is_valid(): subject = "You got a message" message = form.cleaned_data['message'] email = form.cleaned_data['email'] actual_message = "You got a message from {} \n\n {} \n\nGo to work\nWith regards".format(email,message) recipients = ['example@mail.com'] sender = 'example@mail.com' send_mail(subject, actual_message, sender ,recipients,fail_silently=False) return HttpResponseRedirect('') else: form = FeedbackForm() return render(request,'my_webapp/index.html',{'form':form}) I can do this by writing a JS onClick function but is there any better way to do this? Also the built-in django messages refreshes the page I guess and are always on … -
Django - Filter related objects
Let's say I have a list of locations where each location has a list of some objects. I want to make sure that I get these locations, but with a filtered list of objects. Here's the structure of models.py: class Location(models.Models): # fields class LocationObject(models.Models): location = models.ForeignKey(Location, related_name="objects_list") # other fields that are used in filtering Here's how I do filtering: locations = Location.objects.all() if request_square_from: locations = locations.filter(objects_list__size__gte=request_square_from) if request_square_to: locations = locations.filter(objects_list__size__lte=request_square_to) # Other filters ... The problem is that by using this method of filtering, I get in each location a list of objects in which there is at least one object that satisfies the condition in locations.filter(). This is not what I actually need. I need to exclude every object (I mean LocationObject) that doesn't satisfy the condition in the filter() method. Is there any idea to do that? -
Django Api - 'str' object has no attribute '_meta'
I get this Attribute Error 'str' object has no attribute '_meta' views.py def display_mobiles(request,*args,**kwargs): items = Mobiles.objects.all() context = { 'items': items, } data_serialized = serializers.serialize('json', context) return JsonResponse(data_serialized,safe=False) Thank you for any help -
Database design approach: suggestions needed
I am designing training video marketplace application. There is going to be Paid and Unpaid customers. For Unpaid customers, I want to provide few videos as free access for selected training package. For example, if there is total 10 training videos in a given training package, 4 videos are going to be free. But, to view remaining 6 videos, customer needs to purchase whole training package. I am not able to decide proper approach to design database tables for this scenario. Here is what I can think of. I am not sure this is going to be correct approach. First Approach: I am assuming, I need three tables like below: Customer Table (Columns: customer_id, customer info) Training Video Table (Columns: video_id, video url, free_access as boolean) Purchase Table (columns: Customer_id as foreign key, video_id as Foreign Key) When user accessing any training video, I will check if the user is paid or unpaid. For this I will take help of Purchase_table. Then on the basis of boolean free_access column, video will be served/denied. But, this seems too costly performance wise (I might be wrong on this!). Second Approach: I should create view on top of Training Video Table for Paid … -
django custom relationship #2
helo; supose i've tow models: class Product(models.Model): ref= models.CharField(max_length=12, unique=True) code_prod= models.CharField(max_length=50) description= models.CharField(max_length=150) class Detail(models.Model): ref = models.CharField(max_length=10) year= models.IntegerField() code = models.CharField(max_length=10) month = models.IntegerField() created_at = models.DateField() class Meta: db_table = 'details' to make oneToMany relationship on Detail model, we can use ForeignKey. this supose in Detail table there is column named product_id, i want know if i can use another field for example "ref" to make this relationship ? also how can i perform this SQL query : query = "select product.ref, product.description, details.year, details.code from product left join details on details.ref = product.ref where product.code = 'abcd' ; " thank you very much. -
What's wrong with this Nginx configuration that can't locate media directory?
I'm learning Django for some months. Right now I am working with a demo project of video blog which I am trying to host on a local Ubuntu Server 18.04 LTS with Gunicorn, Nginx, Redis and Postgresql. I have installed this server on Virtualbox and assigned a fixed IP. Site has been hosted and static files (html, css, js) are working well but video and a default image file of media folder are not connected. Both static and media folders are in the project root directory. I think have not configured properly the Nginx configuration file. But everything works fine with the development server. I am very new my dear and have a lack of advance programming knowledge. In this case, I am asking for your help for solving this problem. Please have a look the code bellow. Thanks in advance! Project structure part of settings.py file # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'kiji/static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # For sending email EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Redis Configuration REDIS_HOST = 'localhost' REDIS_PORT = 6379 REDIS_DB = 0 Nginx congiration server { listen 80; … -
How to access foreign key table's data in Django templates?
I want to access foreign key table's data into django templates. my code is as below. class TutorialCategory(models.Model): tutorial_category = models.CharField(max_length=200) category_summary = models.CharField(max_length=200) category_slug = models.CharField(max_length=200, default=1) class TutorialSeries(models.Model): tutorial_series = models.CharField(max_length=200) tutorial_category = models.ForeignKey(TutorialCategory, verbose_name="Category", on_delete=models.SET_DEFAULT) series_summary = models.CharField(max_length=200) Tutorial_obj = TutorialSeries.objects.get(pk=1) {{ Tutorial_obj.tutorial_series}} {{Tutorial_obj.category_summary}} // Not able to access TutorialCategory I have searched on SO also & found to use _set which I have used but still not able to access table. Pls if anyone have suggestion pls guide me .