Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I decrease the value of a field of a queryset simultaneously?
I want to make a site where people can make listings for things to sell. I want it to have a front page where the most popular (hot) items are always displayed. Popularity decreases with time and increases with activity (bidding, commenting, clicking). Every item starts with a popularity of 100. That way uninteresting items dissapear quickly and interesting ones stay on longer. So everytime a user interacts with the objects its popularity should increase (for example, everytime a get request from a unique user is made for the details of the object, its popularity value goes up by 1, every bid increases it by 10). On the opposite, everytime a minute or so passes, the popularity of all currently active items decreases. Once it hits 0, it will be "deactivated" it will still be tradable, but it will never hit the frontpage again. The problem is, how do I decrease the popularity of a queryset of all active items? I realize that everytime the user request the front page. I could just fetch all active objects, calculate the popularity within python code and sort them by hand, but that seams rather wastefull. I know I can easily set a … -
How do you clone a model and its dependencies in Django 2.2?
How do I clone a model in such a way that it includes (clones) data on FK-related models? I've looked through various related questions on Stack, and found most of them are for old/outdated versions of Django. Here's some illustrative model code (with str methods, etc omitted for brevity): class Tracking(models.Model): entry = models.CharField(blank=False, max_length=50) timestamp = models.DateTimeField(null=True, auto_now_add=True) active = models.BooleanField(default=False) class Author(models.Model): entry = models.ForeignKey(Tracking, on_delete=models.CASCADE) first_name = models.CharField(blank=False, max_length=50) last_name = models.ImageField(null=True, blank=True) class Scene(models.Model): entry = models.ForeignKey(Tracking, on_delete=models.CASCADE) location = models.CharField(blank=False, max_length=50) image = models.ImageField(null=True, blank=True) My desired result would be to clone an existing "entry" on the Tracking model, such that a new "entry" on a new row is created with its own PK, as well as cloned copies of "Author" and "Scene" data on their respective tables which also point to the new cloned "entry". Any pointers in the right direction would be helpful. I'm not finding anything in the django docs. -
'Keyerror at /' when passing user with primary key in queryset for a listview
models.py class Notes(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() date_added = models.DateTimeField(default=timezone.now) views.py class HomepageView(ListView): model = Notes template_name = "home.html" def get_queryset(self): # object_list = Notes.objects.filter(Q(author=self.kwargs['pk'])) return Notes.objects.filter(Q(author=self.kwargs['pk'])) It points out pk has KeyError, is there any way to get rid of it Thanks in advance...! -
SSH tunnel (via Serveo.net) not connecting to Django server
I'm using Django to host a small server (i.e. etesync), and while I'm not fully familiar with all the technical details that go into this sort of thing, I know that I run the server at 0.0.0.0:8000. I can confirm that it connects successfully when I navigate to http://localhost:8000/ and http://192.168.1.XXX:8000/ (where XXX is local device's static IP). I'm trying to set up an SSH tunnel to Serveo.net so I can access this server from outside my LAN. So, I ran: ssh -R xyz:80:localhost:8000 serveo.net in my SSH client and received the output, "Forwarding HTTP traffic from https://xyz.serveo.net." If I then navigate to http://xyz.serveo.net/, my SSH client will output, "HTTP request from [my external IP] to https://xyz.serveo.net/." However, it does not connect to my Django server. In the python terminal where I'm running my server, I do not see any new requests (whereas navigating to http://localhost:8000/ will output, "GET HTTP/1.1" for the server). Am I doing something wrong with configuring Serveo? As this is my first project involving hosting and SSH, I'm not super familiar with what the "80" in "80:localhost:8000" refers to. I've tried changing this to: ssh -R xyz:8000:localhost:8000 serveo.net but that just results in the output, "Warning: … -
Annotate and Extract to Group Attribute returns 'Sequence Item 0'
I'm trying to build a query to count occurrences from distinct months in my SQL DB, using annotate and extract for this purpose. Here is the code used: Model class Results(model.Model): trip = models.BooleanField(default=False) created_on = models.DateTimeField(default=datetime.now) Query from django.db.models.functions import Extract, ExtractYear from django.db.models import Count res = Results.objects.annotate(month=ExtractMonth('created_on')) .values('month').annotate(count=Count('month')) OR res = Results.objects.annotate(month=Extract('created_on','month')) .values('month').annotate(count=Count('month')) Both return: Error Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\query.py", line 244, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\query.py", line 268, in __iter__ self._fetch_all() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\query.py", line 106, in __iter__ for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size): File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1017, in results_iter results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1052, in execute_sql sql, params = self.as_sql() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 449, in as_sql extra_select, order_by, group_by = self.pre_sql_setup() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 50, in pre_sql_setup self.setup_query() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 41, in setup_query self.select, self.klass_info, self.annotation_col_map = self.get_select() File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 244, in get_select sql, params = self.compile(col, select_format=True) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\sql\compiler.py", line 390, in compile sql, params = node.as_sql(self, self.connection) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\aggregates.py", line 76, in as_sql return super().as_sql(compiler, connection, **extra_context) File "C:\Users\VIBRITO\Desktop\Projetos\webapp\venv\lib\site-packages\django\db\models\expressions.py", line 618, in as_sql data['expressions'] = data['field'] = … -
How to calculate count of related many to many objects based on another queryset?
class Zone(Model): ... class Flight(Model): zones = ManyToManyField(Zone) flights = Flight.objects.filter(...) qs1 = Zone.objects.annotate( count=flights.filter(zones__pk=F('pk')).distinct().count(), # this is not valid expression ) Despite having F inside queryset with count() in annotation it still throw an error TypeError: QuerySet.annotate() received non-expression(s): 0. meaning that that queryset was executed in place. Also doesn't work: qs1 = Zone.objects.annotate( count=Count('pk', filter=flights.filter(zones__pk=F('pk'))), ) -
Django: How to validate / Validator a "greater then" between two FormFields?
I am testing writing validator in django. So far it worked, but now i would like to write something like a "range". forms.py class AnimalForm(forms.ModelForm): weight = forms.DecimalField(validators=[validate_gtr]) class Meta: model = Animal fields = [ 'name', 'weight', 'daily_food_min', 'daily_food_max', 'species', 'farmer', ] def __init__(self, *args, **kwargs): super(AnimalForm, self).__init__(*args, **kwargs) self.fields['name'].help_text = 'Name of Animal' self.fields['weight'].help_text = 'Weight in Kg' self.fields['species'].help_text = 'choose a species' validator.py from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_gtr(value): if value > 100: raise ValidationError( _('(value) Kg. Animal is too heavy'), params={'value': value}, ) Question As you can see i already wrote a simple validation validate_gtr to check the weight of my animals - it worked. Now i would like to validate daily_food_min and daily_food_max against each other, meaning that daily_food_max has to be greater then daily_food_min, when saving or when entering the numbers in my html form. this was my approach forms.py class AnimalForm(forms.ModelForm): weight = forms.DecimalField(validators=[validate_gtr]) daily_food_min = forms.IntegerField(min_value=0, validators=[validate_food]) daily_food_max = forms.IntegerField(min_value=1, validators=[validate_food]) <...> validator.py <...> def validate_food(daily_food_min, daily_food_max): if daily_food_min > daily_food_max: raise ValidationError( _('(daily_food_min) Kg. is higher then max.'), params={ 'daily_food_max': daily_food_max, 'daily_food_min': daily_food_min, }, ) Unfortunately i receive i Error Message when i fill out … -
assign foreign key to user custom field
i am trying t assign the foreign key of a model to specific custom field in custom user model. how should i handle it in the views. def create_generalinfoform(request): args = {'startup_id':request.user} if request.method == 'POST': form = generalinfoform(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.str_geninfo_id = args.startup_name instance.save() return redirect('create_teamsizeform') else: form = generalinfoform() return render(request, 'application/form_template.html', {'form': form}) -
how to retrieve data related to a primary key when selected from a form before saving the instance
how to retrieve data related to a primary key when selected from a form before saving the instance i'm trying to something like that , when i selected a model for instance dell venue before i hit the save button it will return the related data depend on the primary key without saving the instance <form method="POST" id="print-form">{% csrf_token %} <div class="card text-center box-2" id="print-form"> <table class="table"> <thead> <tr> <th class="float-right"> Date : {{ form.date }}</th> <th class="float-left">Customer : {{ form.customer }}</th> </tr> </thead> </table> <table class="table"> <thead> <tr> <td scope="col">model</td> <td><div class="form-group floating-label"> {{ form.model | add_class:'form-control select2-list' | attr:'id:model'}} </div></td> </tr> <tr> {{ form.order.errors }} <td scope="col">quantity</td> <td scope="col">{{form.order}}</td> </tr> <tr> {{ form.CPU.errors }} <td scope="col">CPU</td> <td scope="col" style="width: 50%">{{form.CPU}}</td> </tr> <tr> {{ form.RAM.errors }} <td scope="col">RAM</td> <td scope="col">{{form.RAM}}</td> </tr> <tr> {{ form.Hard.errors }} <td scope="col">Hard</td> <td scope="col">{{form.Hard}}</td> </tr> <tr> {{ form.Graphic.errors }} <td scope="col">Graphic</td> <td scope="col">{{form.Graphic}}</td> </tr> <tr> {{ form.price.errors }} <td scope="col">price</td> <td scope="col">{{form.price}}</td> </tr> <tr> {{ form.get_cost.errors }} <td scope="col">cash</td> <td scope="col">{{form.get_cost}}</td> </tr> <tr> {{ form.guarantee.errors }} <th>warrantor</th> <th>{{form.guarantee}}</th> </tr> </tbody> </table> <input type="submit" name="save" value="selling" class="btn btn-primary btn-block"> ... is it possible to retrieve the data before saving the form? -
DJANGO REST FRAMEWORK How to log in using username or email
I need to configure the settings.py so that it is possible to log in using username or email #Login con correo ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False #Following is added to enable registration with email instead of username -
Django Cycle Includes Template Tags
I want to cycle the include tags in a django template, but I am unable to nest cycle inside of includes. The cycle should be like I am trying to avoid creating a custom template just to keep it simple. I wanted to see if anyone had any suggestions of how to do this: {% for s in sections %} <section class="{% cycle 'lighter-section' 'cover cover-bg-section' %}"> {% if s.media.values %} {% include 'web_builder/apple-pie/sections/left_align.html' %} {% else %} {% include 'web_builder/apple-pie/sections/center_align.html' %} {% endif %} </section> {% endfor %} -
django redirect view with parameter
I was wondering if something like this is possible in Django. In my App i have the file urls.py that contains these rows: ... path('home/', views.home, name='home'), path('page/', views.page, name='page'), .... and in my view.py file i have two view like this: def home(request, value=0): print("value=", value) return render(request, 'template.html', context) def page(request): if bad: return redirect(reverse('home'), value=1) Is it possible to have the view function with a parameter (like value in this case) and then use redirection from the page view passing some value based on same condition like value=1 in this case using the format described in the urls.py? The code above always prints value=0 no matter what. The only way i can think to do this is to use global variables which i would really like to avoid.. Thank you -
How to render queryset according to radio buttons in Django
I need to render products list view according what user select in radio buttons in template if user select "men" only products with gender='men' appear and so for women products , so how to do that correctly? for that I coded some snippets but it didn't work ever I need help to do that correctly here is my code models.py GENDER_CHOISES=( ('men', "Men"), ('women', "Women"),) class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to='products', null=True, blank=False) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) gender = models.CharField(max_length=120,default="" ,choices=GENDER_CHOISES) timestamp = models.DateTimeField(auto_now_add=True) views.py def ProductListView(request): if request.method=='post': queryset = Product.objects.filter(gender=request.POST.get(['gender'])) else: queryset = Product.objects.all() template_name = "products/list.html" return render(request,template_name,{'object_list':queryset}) list.html {% extends "base.html" %} {% block content %} <form method='post'> <div class="mx-auto mx-0"></div> <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary"> <input type="radio" name="gender" autocomplete="off" value='men'> Men </label> <label class="btn btn-secondary"> <input type="radio" name="gender" autocomplete="off" value='women'> Women </label> </div></form> {{object_list.count}} <div class="row"> {% for product in object_list %} <div class="col"> <!-- {{ forloop.counter }} --> {% include 'products/snippets/card.html'%} {% if forloop.counter|divisibleby:3 %} </div></div> <div class="row"><div class="col-12"><hr></div> {% else %} </div> {% endif %} {% endfor %} </div> {% endblock %} Any help Appreciated … -
Can I name a model using a field from another model in django admin?
Such as... class firstModel(models.Model) name = models.CharField() def __str__(self): return self.name class secondModel(models.Model) paragraph = models.TextField() def __str__(firstModel): return firstModel.name Basically I have two model forms both of which the user fills in - user fills in firstModelForm on page 1, then page 2 is secondModelForm. In django admin I want secondModel to display the name that was inputted in firstModel, instead of secondModel object(1). I know the above code isn't how you achieve that, but I thought it illustrates what I'm trying to achieve. Thanks. -
Django - Update an html table every 1 minute
Is it possible to update an HTML table (client side) every minute without refreshing the page in a django project? If yes, please, just let me know what I should look for in order to achieve this result. Please, do not down vote my question due no code. I did not start the project yet. -
Content-length header lost during request (django)
Using clen = os.path.getsize(the_file) response['content-disposition'] = "attachment; filename=%s" % filename response['content-length'] = clen return response Results in a response header with only the content disposition, but not the content-length If I add a non-sense header like response['bla'] = 'some non-sense' it appears perfectly in the response. Is there somewhere else where headers are being overwritten or something. I'm using nginx with uwsgi. -
Django form is not showing
I want to create a simple html login form with django forms, but whenever I run the server the form does not show, only a button. This is what I have in my forms.py file from django import forms class LogForm(forms.Form): email = forms.CharField(label='email') psword = forms.CharField(label='pasword') Then in views.py from django.shortcuts import render from django.http import HttpResponse from blog.forms import LogForm def get_info(request): form = LogForm() return render(request, 'login.html', {'form': form}) And finally in login.html <h1>LOGIN PAGE!</h1> <form method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> And the only thing that shows is this View of the webpage with only the sumbit button Thanks for the help -
How to link two variable DBs together
I am trying to think about the right way of implementing this schema. I have a piece of music with a pre-determined instrumentation. For example, Beethoven wrote a piano trio. The instrumentation is 3 instruments: 1 piano, 1 violin, and 1 cello. class Work_Music(MPTTModel, Work): composer = models.ForeignKey(Composer, verbose_name=_('composer'), null=True, blank=True, on_delete=models.PROTECT) key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('instrumentation'), null=True, blank=True, on_delete=models.PROTECT) class Instrumentation(models.Model): name = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) class Instrument(MPTTModel): name = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) instrumentation = models.ManyToManyField(Instrumentation, verbose_name=_('instrumentation'), related_name='instrument', blank=True) player_name = models.CharField(max_length=100, null=True, blank=True) Separately, I have have a performance model. On a high level, I think of Performance is an "instance" of a piece of music. One would expect there to be 1 pianist, 1 violist, and 1 cellist to perform. class Performance(Event): work = models.ManyToManyField(Work_Music, verbose_name=_('work'), blank=True) players = models.ManyToManyField(Ensemble, verbose_name=_('players'), blank=True) //Ensemble is just multiple players What is the best way to parallel link the two models? The issue here is instrumentation for each piece may be different. How do I create an admin.py that I can easily select a pianist to link to the piano role. … -
How do I translate Javascript standard error messages in Django?
I've a couple of Django projects using translations and everything works fine except Javascript error messages on forms are not translating. For example, on my Login form, if I simply press enter I will get the JS error message "Please fill in this field" in English, whether I've selected English, French, German or any other language. This is not my JS error message and if I run manage.py makemessages -d djangojs, then this message doesn't show up to translate so I don't think I need to correct through that process. Can anyone advise me how to ensure the user is getting JavaScript error messages in their language. Thanks -
Django Filtering Articles by Categories
I'm building a news web site as a part of a task I was given, homework. I have a "articles.html" template which renders all of my news articles by publish date. I added a for loop in the template to loop over the Category model and display Categories as a list. What I'm trying to do now is to filter my articles by category, so when I click "sports" on the list, my site now displays only sports related articles. I have read so much online, and I just got confused, I'm supposed to do this today but I'm having a rough day and would appreciate some guidance ! Here are my models.py : from django.db import models from datetime import datetime from autoslug import AutoSlugField class Category(models.Model): category_title = models.CharField(max_length=200, default="") def __str__(self): return self.category_title class Article(models.Model): title = models.CharField('title', max_length=200, blank=True) slug = AutoSlugField(populate_from='title', default="", always_update=True, unique=True) author = models.CharField('Author', max_length=200, default="") description = models.TextField('Description', default="") is_published = models.BooleanField(default=False) article_text = models.TextField('Article text', default="") pub_date = models.DateTimeField(default=datetime.now, blank=True) article_image = models.ImageField('Article Image') article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="") img2 = models.ImageField('Article Image 2', default="", blank=True) img3 = models.ImageField('Article Image 3', default="", blank=True) img4 = models.ImageField('Article Image 4', default="", blank=True) … -
How to send an image file on POST request on unit test Django
I have a few logo files that I'm trying to send via a POST request, which in turn then will be sent to an AWS S3 bucket by the view. I already have worked out how to do it on a standalone python script, but I'm trying to implement it with Django's MVC now. def test_post_photo(self): first_file_name = join(abspath(dirname(__file__)), 'logos/color_palette.png') url = reverse( "bige_transactions:merchant-logo-list", kwargs={"merchant_id": self.merchant_1.prefixed_id}, ) with open(first_file_name, 'rb') as data: resp_data = self.post(url, {"image": data}) views.py: class MerchantLogoViewSet(GetPrefixedIDMixin, FiltersMixin, viewsets.ModelViewSet): """GET and POST support for /metchants/<merchant_id>/logo/.""" merchant_lookup_field = "merchant_id" # used by `IsMerchantAdmin` permission permission_classes = permissions.IsPostRequest def post(self, request, *args, **kwargs): print(request.data) urls.py: merchants_router = routers.NestedSimpleRouter(router, r"merchants", lookup="merchant") merchants_router.register( r"members", views.MerchantMemberViewSet, base_name="merchant-members" ) merchants_router.register( r"transactions", views.MerchantTransactionsViewSet, base_name="merchant-transactions", ) merchants_router.register( r"logo", views.MerchantLogoViewSet, base_name="merchant-logo", ) models.py: class MerchantFile(BigeModel): """Store Merchant files.""" file = models.FileField() merchant = models.ForeignKey(Merchant, on_delete=models.CASCADE) title = models.CharField(max_length=50) type = models.CharField(max_length=20) I am getting TypeError: Object of type 'BufferedReader' is not JSON serializable with the current test. I just need to able to send the image file in a POST request to the the view and be able to access the file from the view. -
Use instance in django form widget.[input field value]
forms.py class Update_Movies_form(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Avenger','maxlength':50,'value':this.name})) country = forms.ModelChoiceField(queryset=Country_list.objects.all()) story_line = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Description'})) cost = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder': '$','maxlength':11})) release_date=forms.DateField(widget=forms.DateInput(attrs={'placeholder': 'Release date (yyyy-mm-dd)'})) imdb_rating = forms.FloatField(widget=forms.NumberInput(attrs={'placeholder': 'IMDB rating','maxlength':11})) imdb_link = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'IMDB link'})) trailer_link = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Trailer link'})) quality = forms.ModelChoiceField(queryset=Quality_list.objects.all()) movies_type = forms.ModelChoiceField(queryset=Movies_type_list.objects.all()) movies_thumbnail=forms.ImageField(widget=forms.ClearableFileInput(attrs={'placeholder': 'thumbnail'})) urls.py path('movies/<int:movies_id>/update',Movies_update,name='movies-update'), views.py @login_required def Movies_update(request,movies_id): obj=get_object_or_404(Movies_list,movies_id=movies_id) form=Update_Movies_form( data=(request.POST or None), files=(request.FILES or None), # instance=obj ) context={ "form":form, } return render(request,'movies_list/list_create.html',context) I want to create raw html for using django Form for updating movies list but i dont know how to initialize input text field with object details stored in database. -
How to Model Peer to Peer Transactions in Django?
I'm trying to figure out the correct way to model transactions between users in an ecommerce site I'm building. I want the transaction to be available to both users in a dashboard. It seems incorrect to have the transaction, and all its details, saved to both users objects. I think I need to create a separate model for transactions, with a unique id for each transaction. Then, in each user's object I could simply save that transaction id. Would I then simply give each transaction two primary keys, one for the purchaser's user.id and one for the purchasee's user.id? Is this "many to many"? Thanks for any guidance here. -
1 GB max download with uwsgi+nginx
I cannot use X-Accel-redirect because I am generating content on-the-fly, I tried: proxy_max_temp_file_size 1000000M; client_max_body_size 4G; proxy_request_buffering off; fastcgi_max_temp_file_size 1000000M; in nginx.conf but still my downloads served by a Django view are capped at exactly 1024 MB. Does anybody know how to disable this NGinx/uwsgi limit? Using the Django built-in webserver serves the large files (>1 GB) just fine so it is an Nginx/Uwsgi thing... -
How can i filter the relationship between parents and child?
Here is my code: \\models class ParentsProfile(models.Model): Fathers_Firstname = models.CharField(max_length=500,null=True,blank=True) Fathers_Middle_Initial = models.CharField("Middle Initial",max_length=500,null=True,blank=True, help_text="Father") Fathers_Lastname = models.CharField(max_length=500,null=True,blank=True) class ChildProfile(models.Model): Firstname = models.CharField(max_length=500,null=True,blank=True) Middle_Initial = models.CharField(max_length=500,null=True,blank=True) Lastname = models.CharField(max_length=500,null=True,blank=True) Parent_Users = models.ForeignKey(ParentsProfile, related_name='+', on_delete=models.CASCADE,null=True,blank=True,) \\and this is my view def Parents_login_form(request): students = StudentProfile.objects.all() return render(request, 'Homepage/parentsprofile.html', {"students": students}) How do I filter the relationship between parents and their children? And how to display it in html? Please help me....