Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ID parameter in Django REST API URL
I have two models: Article Comment Comments are connected to Article with ForeingKey. I want to create an endpoint like: {GET} /article/97/comments # get all comments of article (id:97) {POST} /article/97/comments # create an comment for article (id=97) But I want to use GenericViewSet or ModelMixins. Can you guide me, how can I do so? Thanks. -
Got Key Error on Django Serializer when combining 2 models
Good day SO. I want to combine two models in one django serializer. I just want to first get them inside one serializer and I can do the rest. Based on other SO question, I need to first declare a serializer and add it to my 2nd serializer. But it is giving me an error. I thought I just need to use the word major and declare it to my minor fields. class PrefectureMajorSerializer(serializers.ModelSerializer): id = serializers.IntegerField() text = serializers.CharField(source='prefecture_name') class Meta: model = PrefectureMajor fields = ["id", "text"] class PrefectureSerializer(serializers.ModelSerializer): id = serializers.IntegerField() text = serializers.CharField(source='prefecture_name') major = PrefectureMajorSerializer() class Meta: model = PrefectureMinor fields = ['id', 'text', 'prefecture_major_id', 'major'] Models: class PrefectureMajor(models.Model): prefecture_name = models.CharField(max_length=100, default='', null=False) is_active = models.BooleanField(default=True, null=False) def __str__(self): return self.prefecture_name class PrefectureMinor(models.Model): prefecture_major = models.ForeignKey("PrefectureMajor", related_name="PrefectureMinor.prefecture_name +", on_delete=models.CASCADE) prefecture_name = models.CharField(max_length=100, default='', null=False) is_active = models.BooleanField(default=True, null=False) def __str__(self): return self.prefecture_name -
Why does Django update other apps/databases while migrating?
I would just like to understand something about Django migrations. I have a project with several apps and most of them have their own database. Now, let's say I add one field to the app App_A in the models.py and run makemigrations App_A. Then this runs smoothly and tells me that there is just one field to be added. But when I run migrate --database=the_db_of_app_a it lists lots of migrations of other apps, but there I haven't change anything lately. So, I would like to know, why it does not only list the migrations of App_A. Best regards -
Get the database of the Django web application deployed on Heroku
I have deploy a Django web application on Heroku. How can I get the database link to that web application which is deployed on Heroku? Once I get that database, then how can I link that database to my new Django project? Basically, I want to do this because we need to change the URL of the web application deployed on Heroku. If there is any other way via which we can do then please let me do. Thanks in advance. -
Django: Get previous values of a multi-step form to dynamically display the fields of the next step
I am making a project in Django but Im not using Django built-in forms. Rather, I am using html and bootstrap to render forms. On a page, I want to create a quiz. I am doing this via a multi-step form where I input the number of questions on the first form. Then based upon this field, when I hit next, I want to have the same number of the fields for questions and corresponding answers to appear so that I can set them. For example, if I type 5 questions and hit next, it should have 5 fields for me to enter the questions and each question field should have 4 answer fields. Is there a way to dynamically do this? Please help :(((( This is very important. Thank you n here is my code snippet {% block content %} <div class="row"> <h2 style="color: darkblue;" class="text-center">Add a Quiz</h2> </div> <form action="" id="add_test_form" method="POST"> <!--This form will contain the quiz information--> {% csrf_token %} <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Name of test</label> <input type="text" class="form-control" name="test_name" required> </div> </div> </div> <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Number of questions</label> <input type="number" class="form-control" name="test_num_questions" min="1" oninput="validity.valid||(value='')" required> </div> … -
my program doen"t enter the try portion? I have write program for login but that doesn't work
def signin(request): if request.method=="POST": try: userdetails = employees.objects.get(username = request.POST.get('username'),password = request.POST.get('password')) print("username" , userdetails) request. Session['username'] = userdetails.username return render(request,'pimapp/main.html') except employees.DoesNotExist as e : messages. Success(request, 'username/password is invalid..!') return render(request,'pimapp/home.html') -
django: log raw sql and als othe output
In django to see the logging of raw sql we can use 'loggers': { 'django.db.backends': { 'handlers': ['sql'], 'level': 'DEBUG', 'propagate': False, }, in the settings file Is there any chance we can see the output of these raw sqls, i.e the data being fetched etc -
How to extract text from images and populate them into output fields using tesseract-ocr in django project?
I am developing an application to detect text from images(when user upload images), and then populate those extracted text into output fields. I have completed the text extraction part using tesseract-ocr (This part is working). But I'm stuck with populating those extracted text into output fields. Here's my code for text extraction: utils.py Here's my utils.py file where I have written the text extraction code. This is working. I need ideas to populate these extracted result into output fields. (It is better if I can do it without saving extracted data into database. I need to save into database only after validating the extracted data by the user.) import pytesseract pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe' def get_filtered_image(image, action): img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) if action == 'NO_FILTER': filtered = img elif action == 'COLORIZED': filtered = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) elif action == 'GRAYSCALE': filtered = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) elif action == 'BLURRED': width, height = img.shape[:2] if width > 500: k = (50,50) elif width > 200 and width <= 500: k = (25,25) else: k = (10,10) blur = cv2.blur(img, k) filtered = cv2.cvtColor(blur, cv2.COLOR_BGR2RGB) elif action == 'BINARY': gray = filtered = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, filtered = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY) elif … -
How to get the name of the user with their id in follower and following system in Django rest framework?
I want to create a follower and following system, and I created but I want to add username along with their following_user_id or user_id. How can I do this? models.py from django.db import models from django.contrib.auth.models import User from django.http import JsonResponse ## Create your models here. class UserFollowing(models.Model): user_id = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following_user_id = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: unique_together = (('user_id', 'following_user_id'),) index_together = (('user_id', 'following_user_id'),) ordering = ["-created"] def __str__(self): f"{self.user_id} follows {self.following_user_id}" serializers.py/UserSerializers class UserSerializer(serializers.ModelSerializer): following = serializers.SerializerMethodField() followers = serializers.SerializerMethodField() # for validate user email def validate_email(self, value): lower_email = value.lower() if User.objects.filter(email=lower_email).exists(): raise serializers.ValidationError("Email already exists") return lower_email class Meta: model = User fields = ['id', 'first_name', 'username', 'last_name', 'email', 'password', 'date_joined','following','followers'] # extra_kwargs for validation on some fields. extra_kwargs = {'password': {'write_only': True, 'required': True}, 'first_name': {'required': True}, 'last_name': {'required': True}, 'email': {'required': True} } def get_following(self, obj): return FollowingSerializer(obj.following.all(), many=True).data def get_followers(self, obj): return FollowersSerializer(obj.followers.all(), many=True).data def create(self, validated_data): user = User.objects.create_user(**validated_data) # create user Token.objects.create(user=user) # create token for particular user return user FollowingSerializer and FollowerSerializes class FollowingSerializer(serializers.ModelSerializer): class Meta: model = UserFollowing fields = ("id", "following_user_id", "created") class FollowersSerializer(serializers.ModelSerializer): class Meta: model = UserFollowing fields … -
Django: totals subtotals item view in Django template
I have Models like from django.db import models class Order(models.Model): Category = models.CharField(max_length=225) # Men, Women, Child etc. Item = models.CharField(max_length=225) # Shirt, Pant, T-Shirt Price = models.IntegerField() Desire view in Templets by for loop Men Items Name Price Shirt 20 Pant 30 T-Shirt 10 Subtotal 60 Women Items Name Price Shirt 20 Pant 30 T-Shirt 10 Subtotal 60 Child Items Name Price Shirt 20 Pant 30 T-Shirt 10 Subtotal 60 Grand Total 180 -
Django Channels WebSocket argument
I am trying out an example from the book Django By Example, Chapter 13. There is an example there showing how to establish a socket for a chat room later on. Below is the code where I am sure the error comes from: room.html {% extends "base.html" %} {% block title %}Chat room for "{{ course.title }}"{% endblock %} {% block content %} <div id="chat"> </div> <div id="chat-input"> <input id="chat-message-input" type="text"> <input id="chat-message-submit" type="submit" value="Send"> </div> {% endblock %} {% block domready %} var url = 'ws://' + window.location.host + '/ws/chat/room/' + '{{ course.id }}/'; var chatSocket = new WebSocket(url); {% endblock %} Below are the routing.py and consumer.py routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/room/(?P<course_id>\d+)/$', consumers.ChatConsumer), ] consumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass # receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({'message': message})) Below is the error message I got when running python manage.py runserver WebSocket HANDSHAKING /ws/chat/room/6/ [127.0.0.1:57288] Exception inside application: object.__init__() takes exactly one argument (the instance to initialize) Traceback (most recent call last): File "/home/xxx/.local/share/virtualenvs/chat-ayPz2iC9/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) … -
how can i add a new key value to my request.data in django
I would like to know how can I add a new value to my request.data this is my request.data, structure: [{'fname': 'john', 'lname': 'Doe'}] how can I add the age key for example -
Django - NameError when trying to test ContentType
I have the following 3 models in my program - Actor, User and Applicant. Actor is a superset of User and Applicant. I made this approach ContentType to make Actor as a superset. Therefore, although the relationship of them is working properly I am not being able to test ContentType to check if it is returning the entity as it is when I return the value in /manage.py shell. The error I am getting is: NameError: name 'ContentType' is not defined ---------------------------------------------------------------------- Ran 2 tests in 0.004s Here is my models.py: from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.db import models # for testing Actor and ContentType: class Actor(models.Model): """ Actor: the superset for User and Applicant """ choices = models.Q(app_label='coretest', model='user') | \ models.Q(app_label='coretest', model='applicant') entity_type = models.ForeignKey(ContentType, limit_choices_to=choices, related_name='entity_types', on_delete=models.CASCADE, null=True) entity_id = models.PositiveIntegerField(_('object ID'), null=True) content_object = GenericForeignKey('entity_type', 'entity_id') company_id = models.IntegerField() created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.content_type) class User(models.Model): actor_id = models.ForeignKey(Actor, on_delete=models.CASCADE) created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.actor_id) class Applicant(models.Model): actor_id = models.ForeignKey(Actor, on_delete=models.CASCADE) created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.actor_id) test_models.py from django.contrib.contenttypes.models import ContentType, ContentTypeManager from django.test import TestCase from … -
How to send data from JavaScript file to views.py django?
How can I send data ( the user_to_follow in this example ) to my views.py function ( follow ) to do some updates? I'm trying to send the username from my JavaScript and then add the logged-in username to that username following list ( all done in my views.py function ) Views.py. def follow(request, profile_to_follow): try: user_to_follow = User.objects.get(username=profile_to_follow) user_to_following = Profile.objects.get(user=request.user.id) except User.DoesNotExist: return JsonResponse({"error": "Profile not found."}, status=404) if request.method == "PUT": user_to_following.following.add(user_to_follow) return HttpResponse(status=204) index.js function follow_user(user_to_follow){ // How To send the user_to_follow to my views.py method. // to add the current logged in user to the user_to_follow following list console.log(user_to_follow) } urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), # API Routes path("posts", views.compose_post, name="compose_post"), path("posts/all_posts", views.show_posts, name="show_posts"), path("posts/<int:post_id>", views.post, name="post"), path("profile/<str:profile>", views.display_profile, name="profile"), path("<str:profile_posts>/posts", views.display_profile_posts, name="profile_posts"), path("follow/<str:user_to_follow>", views.follow, name="follow"), ] -
Django - Cannot Create Follower Functionality
I'm new to Django and I'm trying to create a project similar to a social media site, where users can go to a user profile, and 'follow' another user profile. When I click 'follow' on the profile, currently I don't get any errors at all. Nothing happens. I don't see anything in my console/terminal etc. There's no error. Help is appreciated! views.py def fol(request, username): if request.method == 'GET': currentuser = request.user profileuser = get_object_or_404(User, username=username) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() follower = Follow.objects.filter(target=profileuser) following = Follow.objects.filter(follower=profileuser) following_each_other = Follow.objects.filter(follower=currentuser, target=profileuser) totalfollower = len(follower) totalfollowing = len(following) paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts.count(), 'profileuser': profileuser, 'follower': follower, 'totalfollower': totalfollower, 'following': following, 'totalfollowing': totalfollowing, 'followingEachOther': following_each_other } return render(request, "network/profile.html", context) else: currentuser = request.user profileuser = get_object_or_404(User, username=username) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() following_each_other = Follow.objects.filter(follower=currentuser, target=profileuser) paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) if not following_each_other: f = Follow.objects.create(target=profileuser, follower=currentuser) f.save() follower = Follow.objects.filter(target=profileuser) following = Follow.objects.filter(follower=profileuser) following_each_other = Follow.objects.filter(follower=request.user, target=profileuser) totalfollower = len(follower) totalfollowing = len(following) context = { 'posts': posts.count(), 'profileuser': profileuser, 'page_obj': page_obj, 'follower': follower, 'following': following, 'totalfollowing': totalfollowing, 'totalfollower': totalfollower, 'followingEachOther': following_each_other } return render(request, "network/profile.html", context) … -
How to update Foreign Key from another Foreign Key reference Models Django
I made two models that both have same foreign key reference models (usersold) and (currentuserbid) to User model(settings.AUTH_USER_MODEL). I have filled out the data for AuctionBids models.currentuserbid. When I try to reference it and set it to same value in AuctionListing model in view.py it doesn't get saved. I also tried , listing.sold = User.objects.get(id=listing.bid.currentuserbid.id) Thank you very much! Models.py class AuctionListing(models.Model): title = models.CharField(max_length=64) description = models.TextField() image = models.TextField() bid = models.ForeignKey(AuctionBids, on_delete=models.CASCADE, related_name="auctionbidding", null=True) usersold = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="auctionsold",null=True) class AuctionBids(models.Model): currentBid = models.IntegerField() currentuserbid = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="currentuserbid",null=True) Views.py listing = AuctionListing.objects.get(pk=id) listing.sold = listing.bid.currentuserbid listing.save() -
video not working in safari with django static files
It's a video page to make a website with django. It comes out well on Chrome, but it doesn't come out on Safari... The same goes for mobile safari. Playsinline and video tag are all correct. Video source is the address of a video on the Internet, but it doesn't play when I import it from a static file. Is there a solution? If I have to encode, I also want to know the code that automatically encodes when I load a video. -
Django - Can't access data from object in many to many relationship
In my Django project, I am trying to create a website that streams TV shows. Each show belongs in many categories, hence the use of many to many relations in my model. What I want to do with a certain page on my website is dynamically load a page of shows belonging to a specific category. However, all of my attempts have ended in failure as I am unable to figure out a way on how to access the actual category data from each show. In views.py def shows_in_category(request, category_slug): category = get_object_or_404(Category, slug=category_slug) showsall = animeShow.objects.all() shows = [] for show in showsall: print(show.category.name, category.name) if show.category.name == category.name: shows.append(show) print(shows) return render(request, 'show/show_list_view.html', {'category':category, 'shows': shows}) In models.py class Category(models.Model): name = models.CharField(max_length=255, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse("theshowapp:shows_in_category", args=[self.slug]) class theShow(models.Model): english_name = models.CharField(max_length=400) show_type = models.CharField(max_length=200, blank=True) is_active = models.BooleanField(default=False) category = models.ManyToManyField(Category) slug = models.SlugField(max_length=400,unique=True) class Meta: verbose_name_plural = 'Shows Series' def __str__(self): return self.english_name In the template (show_list_view.html) {% for show in shows %} <script> console.log("I'm trying to get in")</script> <script> console.log("{{ show.name }} {{show.category.name}}")</script> <script> console.log("I'm in")</script> <div class="row"> <div class="col-lg-4 … -
object has no attribute '_committed' error
I want django automatically download and locally save image from image_url and "connect" it with image_file how Upload image from an URL with Django i have error object has no attribute '_committed' error from PIL import Image import requests url = 'https://i.stack.imgur.com/0jot2.png' respone = requests.get(url, stream= True).raw img = Image.open(respone) img.save() def home(request): Topic(title='hjb',content='vf',slug='fvrs',image=img, author=User.objects.first() ) .save() -
In Django, how do add indefinite amount of images with text?
I am new to Django. I am building a website like a blog but I could not understand the scenerio how to add multiple images with text. "Creating seperate class which hold the images and which are connected by foreign key ?" Or another method ? In my plan, users will add some articles which we dont know the amount of images and text. I saw a website and I lıked the concept of it but I could not understand the structure. In this website, each part with contain text and image is composed of a section If you give me an idea about these kind of single-detail-page, I would be glad. Thank you -
module 'django.template' has no attribute 'resolve_variable'
I am porting an old Django project to Django 3.2. I have come across this code segment, which causes an exception to be raised. I have looked through the django documentation, but it seems the method has been removed completely - with no comments regarding replacement etc. Here is the offending code segment: class AddGetNode(template.Node): def __init__(self, new_values): self.new_values = new_values def render(self, context): request = template.resolve_variable('request', context) # <- barfs here ... params = request.GET.copy() for key, value in self.new_values.items(): resolved = value.resolve(context) if resolved: params[key] = resolved elif key in params: del params[key] return '?%s' % params.urlencode() What is the new method to fetch the request object from a context? -
How to pass image file from one page to another in multi-page form
In my django web app, I need to pass a form from one page to another so it can be completed and saved. In this form is an ImageField, and when I try the following, all other fields come pre-populated, but the image field shows "no file selected". Written below is a simplified version of my code. If I uncomment the code where I create an instance of the form in the views.py, the image field in the HTML shows the message "Upload a valid image. The file you uploaded was either not an image or a corrupted image." I have no idea why every other field can get passed into the next page, except the image field. Does anyone know how to do this? Or is there another way to go about this? models.py class MyModel(models.Model): name = models.CharField(max_length=50) age = models.CharField(max_length=50) picture = models.ImageField(default=None, upload_to='media/') forms.py class MyForm(ModelForm): class Meta: model = MyModel fields = '__all__' views.py def index_view(request): if request.method == 'POST': form = MyForm(request.POST, request.FILES) if form.is_valid(): ''' instance = form.save(commit=False) form = ConnectorForm(data=request.POST, files=request.FILES, instance=instance) ''' return render(request, 'main/page2.html', { 'form': form }) else: form = MyForm() return render(request, 'main/index.html', { 'form':form, "base":base }) def … -
Getting AttributeError: sender while iterating to get specific values
Getting "AttributeError: sender" is thrown as the exchange query iterates. Same with other values (message_id, etc) too. My only option at this point is to put a try/catch around it and need to refactor a lot of content under the loop. However, I would think the query should not be crashing under normal circumstances due to any data issue. Please let me know what could be going wrong. There appears to be a 'bad' email object that causes it? kwargs = {"is_read": False} kwargs["datetime_received__gt"] = some_date_time filtered_items = my_exchange._service_account.inbox.filter(**kwargs) filtered_items.page_size = 20 print(filtered_items.count()) 3 <-- 3 objects for sender_obj, msg_id, msg_subj, msg_text, msg_size in filtered_items.values_list("sender", "message_id", "subject", "text_body", "size").iterator(): print(sender_obj) count = count + 1 print(count) Mailbox(name='Some User1', email_address='someuser1@myemail.acme', routing_type='SMTP', mailbox_type='Mailbox') 1 Mailbox(name='Some User2', email_address='someuser2@myemail.acme', routing_type='SMTP', mailbox_type='OneOff') 2 Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 273, in __iter__ yield from self._format_items(items=self._query(), return_format=self.return_format) File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 352, in _item_yielder yield item_func(i) File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 380, in <lambda> item_func=lambda i: tuple(f.get_value(i) for f in self.only_fields), File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 380, in <genexpr> item_func=lambda i: tuple(f.get_value(i) for f in self.only_fields), File "/usr/local/lib/python3.6/site-packages/exchangelib/fields.py", line 189, in get_value return getattr(item, self.field.name) AttributeError: sender -
How to retrieve all messages in a Twilio Programmable Chat Channel?
privatechannel.getMessages().then(function (messages) { const totalMessages = messages.items.length; for (let i = 0; i < totalMessages; i++) { const message = messages.items[i]; console.log('Author:' + messages.author); printMessage(message.author, message.body); } console.log('Total Messages:' + totalMessages); deleteNotifs() }); This is listed as the way in Twilio docs to retrieve the most recent messages. I tried it and the maximum number of messages it displays are not even like 100, it just shows me the last 30 messages in the conversation. Is there a way to retrieve and display all the messages in a Twilio Programmable Chat channel ( private or otherwise )? -
Displaying relationship data inside Django templates
I followed the process of creating multi user type from this tutorial class User(AbstractUser): is_owner = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) class Owner(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, primary_key=True) I have a driver and owner profile with field user which has a OneToOneField relationship with the user model class OwnerProfile(models.Model): ] user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name='owner_profile') phone = models.CharField(max_length=15, blank=True, null=True) bio = models.TextField(blank=True, null=True) class DriverProfile(models.Model): ] user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name='owner_profile') phone = models.CharField(max_length=15, blank=True, null=True) bio = models.TextField(blank=True, null=True) Owners can create Cars class Car(models.Model): car_owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='car_owner', on_delete=models.CASCADE) car_make = models.CharField(max_length=20, blank=True, null=True) … While drivers can create CarRents class CarRent(models.Model): car = models.ForeignKey(Car, related_name='rented_car', on_delete=models.CASCADE) driver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='driver_renting', on_delete=models.CASCADE) start_date = models.DateTimeField(blank=True, null=True) … I have a detailView class ActiveRent(DetailView): model = CarRent template_name = 'app/ActiveRent_detail.html' in my template i tried to access data in the Owner profile using each of the following {{object.car_owner.owner_profile.phone}, {{object.car.ownerProfile.phone}}, {{object.ownerProfile.phone}} but nothing is working. Thanks for your help in advance