Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to communicate between different sessions in django or flask
here is an application case, my description is simplified. here are 3 roles of a website: admin, moderator, and visitor admin can control everything, moderator manages some part of the website, and visitors can post threads and read threads the relationship of the users, roles and permissions are stored in the database in RBAC style now admin want to downgrade a moderator to visitor, it's easy to manipulate the operation in the database. but if the moderator is still online when this action is performed, there will be problem. the admin and the moderator have two different session, and to accelerate the website speed, normally we put the roles and permissions in session, we don't query it every time when the user send request, so the admin's manipulation would not modify the session of the moderator. once the moderator session is not expired, the moderator still has the permissions. so the essential requirement is how to manipulate one session by another session in the web service. my website is based on python. Because RBAC is required, so I prefer flask more than django django.auth module can control the access permission to each model, but what we want to control is … -
Serialize models like with .values(), but also include ManyToMany related field
class Book(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, related_name="books") I'm have pre-existing JavaScript code that works on input that I feed from django like this: json.dumps(list(Book.objects.all().values()), cls=DjangoJSONEncoder) list(Book.objects.all().values()) gives me an array of dictionaries upon which my entire frontend code is based on. [{ "user": 1 }, { ... }, ... ] However, now I've added the tags property. I was expecting to find the tags property in my dictionary but there's not: apparently, Django doesn't serialize ManyToMany managers by default. The offered solution is this: from django.core import serializers serializers.serialize("json", Book.objects.all()) that, however, outputs a dictionary that it's in a completely different form, where all my model properties are inside of a fields parameter. [{"model": "Main.book", "pk": 1, "fields": { "user": ... }] How can I have a tags field like with serializers.serialize while maintaining the .values() form? Do I have to re-write my frontend code entirely to use the format of serializers.serialize or is there a simpler solution? -
Running and controlling python scripts from django Views
My Django View will run a big and quite complex task. It will run a few python scripts to prepare the data and then it will feed generated files to big Java aplication that will run the task. Once run, the Task may run for a few hours. What im aiming at is to create a view that will act as a supervisor for the whole process. It should be able to: Start whole process Get feedback from working python scripts once they are complete Be able to stop the process at any time I have considered things like subprocess or multiprocess but i dont think that they will do the task. Subprocess will either block the View, or i wont be able to get the results. The biggest issue i am facing is the ability to interact django view with running python script. What i would like to achive would look something like this in pseudocode: if 'cancel' in POST: process.stop() #sends kill signal to running instance if 'start' in POST: process.start() #begins the task if 'get_info' in POST: progress = process.communicate() return({'progress':progress}) I am looking for recomendation on how to solve this issue neatly. I am wondering if … -
Django Rest Framework APIClient not handling exceptions during tests
I'm testing an API endpoint that is supposed to raise a ValidationError in a Django model (note that the exception is a Django exception, not DRF, because it's in the model). from rest_framework.test import APITestCase class TestMyView(APITestCase): # ... def test_bad_request(self): # ... response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) However, my test errors out with an exception instead of passing. It doesn't even fail because it gets a 500 instead of 400, it doesn't even get there at all. Isn't DRF's APIClient supposed to handle every exception? I've search online but found nothing. I've read that DRF doesn't handle Django's native ValidationError, but still that doesn't explain why I am not even getting a 500. Any idea what I'm doing wrong? -
I lose data in my serializer (django/angular)
I have data in my front that I get from my serializer except that I lose two data "user" and "establishment". const workplaceBody = { "user": this.currentUser.id, "establishment": response.body.id, "is_main_establishment": false }; When I print validated_data in my serializer I only have one "is_main_establishment" data. {'is_main_establishment': False} I want to create a workplace linked to an establishment. this.workplaceEstablishment.create(workplaceBody).subscribe(response => { console.log(response); }); My workplacesSerializer: class WorkplacesSerializer(ModelSerializer): id = IntegerField(source="establishment.id", read_only=True) name = CharField(source="establishment.name", read_only=True) type = CharField(source="establishment.type", read_only=True) selected = SerializerMethodField() def get_selected(self, instance): #print(instance) #print(self.context["request"].data) return ( get_selected_establishment_id_from_request(self.context["request"]) #"== instance.id ) def create(self, validated_data): print(validated_data) workplace = UserWorksAtEstablishment.objects.create( **validated_data, establishment_id=validated_data.establishment, user_id=validated_data.user ) return workplace class Meta: model = UserWorksAtEstablishment fields = ("id", "name", "type", "is_main_establishment", "selected") I don't see why I'm losing this data. Thank you in advance -
Ajax FormData() is returning null file when uploading a file and a string
I have been looking for a way to upload a file to MongoDB by using the IP string to locate the correct document to upload. However, when I upload the file and check its field value in MongoDB it shows as null. I'm doubting that there might be an issue with the way I'm appending the file OR how I'm uploading it to MongoDB. HTML Code: <h5 class="modal-title h5Modal" id="htmlIP"></h5> <div class="modal-body"> <form method="POST"> <div class="form-group"> <label for="Uploadfile">Choose a File To Upload:</label> <input type="file" id="Uploadfile" accept="image/*,.pdf,.pptx" class="file-path"> </div> </form> </div> <div class="modal-footer"> <button class="btn btn-primary submitFile" data dismiss="modal">Submit</button> </div> Ajax Code: $(document).ready(function() { $('.submitFile').on('click',function(){ formdata = new FormData(); var ID = $('#htmlIP').text(); var file = document.getElementById('Uploadfile').files[0]; formdata.append('Uploadfile', file); formdata.append('IP', ID); $.ajax({ type: "POST", url: 'PythonSubmit/', data: formdata, processData: false, contentType: false, success: function(data){ alert(data.version); window.location.reload(); }, error: function(err){ alert(err); } }); }); }); Python Code: def PythonSubmit(request): if request.method == "POST": PC_IP = request.POST.get('IP', False) FileUploaded = request.POST.get('Uploadfile') res = PC.uploadFileToDB(PC_IP,FileUploaded) data = { 'version' : res, } return JsonResponse(data) res accesses the function uploadFileToDB inside PC class and add the values using $set method which is as follows: uploadFileToDB: @staticmethod def uploadFileToDB(PC_IP, file): PC_collection = PC._get_collection() try: PC_collection.find_one_and_update({"ip":PC_IP}, {"$set":{"file":file}}) … -
How To Track Number of Times Post Was Shared - Django
The task I want to accomplish is simple: track the number of times a post on my blog has been shared because I want the number to be displayed beside the post. However, I cannot figure it out. Here is the the anchors with hrefs that allow the user to click on them and share the post on social media: <ul class="mb-30 list-a-bg-grey list-a-hw-radial-35 list-a-hvr-primary list-li-ml-5"> <li class="mr-10 ml-0">Share</li> <li><a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"><i class="ion-social-facebook"></i></a></li> <li><a href="http://twitter.com/share?url={{ request.build_absolute_uri }}"><i class="ion-social-twitter"></i></a></li> </ul> I have a Post model with a variable called share_count. Obviously, I have a view that helps renders out the HTML too. My issue is that I do not understand how to connect the hrefs to my view in order to increment the share_count of the post in the database. I searched all over and could not find an answer, I would appreciate any helps or hints. -
Scrapy concatenate array elements inside div in python
I need to concatenate some text inside a <div> with xpath in Scrapy. The div has the next structure: <div class="col-12 e-description" itemprop="description"> "-Text1" <br> <br> "-Text2" <br> <br> "-Text3" </div> I've created a ScrapyItem in my Spider: class MyScrapyItem(scrapy.Item): name = scrapy.Field() description = scrapy.Field() If I do this, item['description'] = response.xpath('//div[@itemprop="description"]/text()').extract() everything gets mixed and separated by commas, like this: - Text1 ,- Text2 ,- Text3 I think that's because response.xpath('//div[@itemprop="description"]/text()').extract() returns an array so it adds commas to separate the array items. I'm trying to loop over the array and join each item inside the "description" ScrapyItem property. This is what I'm trying: def parse_item(self, response): item = MyScrapyItem() item['name'] = response.xpath('normalize-space(//span[@itemprop="name"]/text())').extract() for subItem in response.xpath('//div[@itemprop="description"]/text()'): item['description'] = " ".join(subItem.extract()) I know it would work if I could do something like this: for subItem in response.xpath('//div[@itemprop="description"]/text()'): item['description'] = " ".join(subItem.xpath('//div[@itemprop="something_here"]/text()')extract()) but the div that contains the text has no more tags inside. Any help would be appreciated, it's my first Scrapy project. -
Stripe API PaymentIntent and Billing with Python
I try to use the new Stripe's PaymentIntent system to be ready when SCA will be launched in EU. I only use one-time payment. I succeed to make the payment with the PaymentIntent following Stripe's documentation. But I'm unable to create a bill for every payment (I must have one according to the law), and I tried a lot of things. But first, I think I need to show my code to introduce the troubles I have. In my view, I create a Stripe Session : public_token = settings.STRIPE_PUBLIC_KEY stripe.api_key = settings.STRIPE_PRIVATE_KEY stripe_sesssion = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'name':'My Product', 'description': description, 'amount': amount, 'currency': 'eur', 'quantity': 1, }], customer=customer_id, success_url=f'{settings.SITE_URL}/ok.html', cancel_url=f'{settings.SITE_URL}/payment_error.html', ) Then, the user click on the "Purchase" button on my web page and is redirected to the Stripe's Checkout page. After the user filled his payment card informations, Stripe call my Webhook (according to the checkout.session.completed event triggered). Here's my webhook function code : @csrf_exempt def webhook_payment_demande(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None if settings.DEBUG is False: endpoint_secret = "whsec_xxx" else: endpoint_secret = "whsec_xxx" try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: … -
Django. Objects from several models, how to correct display url?
I have two models. I do filtering of objects by these models and display them in a template. Everything works fine, but an error occurs with url. my urls.py path('objects_model_A/<int:objects_A_id>', views.objects_A, name='objects_model_A'), path('objects_model_B/<int:objects_B_id>', views.objects_B, name='objects_model_B'), my views.py def index(request): objects_A = objects_A.objects.all().filter(is_published=True) objects_B = objects_B.objects.all().filter(is_published=True) queryset_list = list(chain(objects_A, objects_B)) context = {'queryset_list': queryset_list} return render(request, 'templates/index.html', context) def objects_A(request, objects_A_id): objects_A = get_object_or_404(objects_a, pk=objects_A_id) context = { 'objects_A': objects_A } return render(request, 'templates/objects_A.html', context) def objects_B(request, objects_B_id): objects_B = get_object_or_404(objects_b, pk=objects_B_id) context = { 'objects_A': objects_A } return render(request, 'templates/objects_B.html', context) my template.html {% if queryset_list %} {% for listing in queryset_list %} <div class="col-md-6 col-lg-4 mb-4"> <div> <a href="{% url 'objects_model_A' listing.id %}">Link </a> {% endfor %} {% endif %} Objects from different models are collected, have an appropriate data set, but url are wrong. The object with model_A, url: http://127.0.0.1:8000/objects_A/1 An object with model_B, url too: http://127.0.0.1:8000/objects_A/1 I understand the error in the template. Line <a href="{% url 'objects_model_A' listing.id %}. How to draw up URLs correctly so that objects from different models in the chain are displayed correctly. For object A was url: http://127.0.0.1:8000/objects_A/1 For object B was url: http://127.0.0.1:8000/objects_B/1 -
in search form enter wrong query get's me keyerror with pandas and django
in my basic search form with framework django , when i enter wrong keyword of a drug dataset in my search form gets me wrong like "KeyError" this search form work with pandas lib , so i am just want when i put word wrong do not show me error i want to show to the user message "nothing match try something else" this is the error when i put word not in my dataframe this is the error when i put word not in my dataframe the word is Tramadol this is my code def search_recommender(request): query = request.GET.get('q') if query: indices = pd.Series(df.index, index=df['drugName']).drop_duplicates() idx = indices[query] sim_scores = list(enumerate(cosine_sim[idx])) sim_scores = sorted(sim_scores, key=lambda x: x[0], reverse=True) sim_scores = sim_scores[1:6] mov_indices = [i[0] for i in sim_scores] gg_will = df['drugName'].iloc[mov_indices] json = gg_will.to_json(orient='values') else: qs = DrugDataset.objects.all() df = qs.to_dataframe() json=df.filter(drugName='q') -
Django - Execute python script, pause and start again after user input
I'm building a django app. In the view function, I'm calling a script. Basically, those scripts will operate actions behind the scene for the end user (novice in python). Now I'd like some of my python scripts to interact with my user. For instance, I want to display my user a message telling him to do some specific actions, and also pause the python script as long as the user doesn't give its input so that the script continues. This works well in terminal using input("Please do XXX and press enter when done") which makes the script hang as long as the user doesn't press enter. Would you have any idea 1) how I could make my python scripts communicate (ie print some results on my django app) and also 2) make a pause during python script processing which, after receiving an input from user, starts again. Thanks -
Django Dropbox storage: Validation error in admin
I´m trying to configure Dropbox storage for a Django APP. I´m using "Django Storages" library wich seems quite straight forward. I got my key from dropbox and configures everything I could see in the "Django storages" docs. The problem is that when I try to load an image in the Admin (still didn´t try it any other way) I get the following error: ValidationError at /admin/stockbucket/productosbase/1/change/ 'C:/Users/Lia love/inventory/Kinemed APP/Kinemed APP/image001.png' did not match pattern '(/(.|[\r\n])|id:.)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)' I read several Stack posts but couldn´t get an answer. Any clues welcome. Thanks in advance! Settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stockbucket.apps.StockbucketConfig', 'storages',] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = 'MyRealDropboxToken' DROPBOX_ROOT_PATH = 'Kinemed APP' Model foto_1 = models.ImageField(upload_to='', default="", blank=True, null=True) foto_2 = models.ImageField(upload_to='', default="", blank=True, null=True) -
Django, running code later/re rendering after page is opened , when token is acquired
I'm building an application in Django that uses a form that needs to gather some data from an API the token to authenticate with this API is gathered by using a login flow. However when the token expires Django refuses to run, so refreshing the token by re-authenticating becomes impossible. Is their a way to run the code from the form after the login has happened so that Django does not try to run it on start-up. Or re-render the form when the page is opened/refreshed However this form requires some data from the that API. To access this API I need to use a token, this token is obtained by going to the login flow in the beginning of the application, which then stores the token for use within the application. However when the Token expires Django won't start. So it's impossible to go true the sign-in flow to obtain a new token. I'm using the Microsoft graph API and requesting data from the AzureAD. I've tried to place the part of the form in a Try: Except: This works however it doesn't reload with the correct information on refreshing or reopening the page containing the form. The form: … -
Vue.js initialization in Django
I'm using django and Vue.js to build some panels. I'm joining Vue.js to Django in test mode and I have this issue: "dist" vue.js folder is served using the django.contrib.staticfiles module, and when I ask for index.html anything is downloaded with no issues. http://127.0.0.1:8000/wwwdocs/index.html However, when vue.js start and download other stuff it fails because it tries to download data from another path: http://127.0.0.1:8000/css/appb17d7483.css http://127.0.0.1:8000/js/app.a322f2ed.js It removed the "wwwdocs" from the url. Is here a fast solution to solve this and have vue.js downloading the modules from the same path it was downloaded ( /wwwdocs ) ? -
Pass a list from view context to template and assign it as an array in the template
I am trying to pass some list from view context: def list_test(request): l = ['a', 'b', 'c'] context = {'l': l} return render(request, 'app/list_test.html', context) to front-end as a JS array: <script> let l = {{ l }} console.log(l) </script> This however, logs Uncaught SyntaxError: Unexpected token & in the console. I have tried putting the variable in double quotes: let l = "{{ l }}" but then the variable gets assigned as a one big string and with unwanted encoding: [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;] Template loop will work: {% for x in l %} console.log("{{x}}") {% endfor %} but i don't want to iterate. I want to assign the list at once instead. Is there a simple way to do this? Should I somehow use the template loop to split the string into array items? -
Email is not receiving to reset password django rest-auth react js
I want to reset user password, for this purpose I am using django rest auth and I have react js on front end, the problem is when I request on http://127.0.0.1:8000/auth/password-rest, I got the message Password reset on 127.0.0.1:8000 and the link is provided with token and uid but on console whereas I want link in email,here below my code: settings.py: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'xyz@hotmail.com' // correct email EMAIL_HOST_PASSWORD = 'xyzzzz' // correct password DEFAULT_FROM_EMAIL = EMAIL_HOST_USER ACCOUNT_EMAIL_REQUIRED = True React part: forgotPassword=(evt)=>{ evt.preventDefault(); const payload={ email:"nabeelayz@hotmail.com" }; axios.post('http://127.0.0.1:8000/rest-auth/password/reset/',payload) .then(res=>{ console.log(res) }) .catch(err=>{ console.log(err) }) }; I am getting message in console but I want in my email. -
DRF accepts int value although it serialzes to a charfield
Hello good people good Django, I was exploring DRF and made a simple CRUD API and everything was smooth nothing special here. But when trying to test how DRF will handle the different cases of missing and wrong values in a POST request I got something was actually very weird. First, here is an example of a valid body of POST request data: { "title": "It doesn't matter", "description": "A short one because life is fast", "body": "Test test test test" } All is a string as you can see. So, I replaced a string value with an int value instead ( like 96 not "96" for sure ) and surprisingly the POST request was successful, the serializer converted the int value to string and inserts it, it didn't raise an error or anything, so is there an explanation for this? -
How to create search view for movie database that can find movie based on title, and tittle + year in search
I am looking to create a search class that can find the movie when the title has been input into my form, but also want it to find said movie when the title and year is input into form as well. This is the view.py I have atm which will find movie based on title, but once I add the year on the end, it will not find it. ''' from django.shortcuts import render from django.views.generic import TemplateView, ListView, DetailView from .models import Movie from django.db.models import Q class HomePageView(TemplateView): template_name = 'movies/front_page.html' class SearchResultsView(ListView): model = Movie template_name = 'movies/search_results.html' context_object_name = 'search_all_movies' def get_queryset(self): query = self.request.GET.get('q') return Movie.objects.filter(Q(title__icontains=query) ''' -
"How to integrate File upload field in wagtail with other Wagtail_Fields?"
I want code of how to upload files in wagtail user forms and when submit form I get form record on wagtail admin panel. I want this form in frontend and when submit data i got it on wagtail adminpanel like that. Same as this code but i want file upload field in Form Fields here. from modelcluster.fields import ParentalKey from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel ) from wagtail.core.fields import RichTextField from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField class FormField(AbstractFormField): page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='custom_form_fields') class FormPage(AbstractEmailForm): intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('custom_form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] def get_form_fields(self): return self.custom_form_fields.all() -
Django Admin how to add filter menu like basic UserModel:
This is how looks template of Django Admin Model: This is model which I created: class ProfileUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.URLField() is_qualified = models.BooleanField(default=False) How can I create same filter menu ? for is_qualified ? -
Passing a model object (with many fields) from a viewfunction to another using redirect and without saving it
I am quite new in this field... so be gentle :) The problem can be stated as follow: View 1: a form based on a model of 14 fields is presented. The user fills it and presses the post button. (important: not saving the model instance in the DB) View 2: A confirmation page appears containing a summary of what he entered. He is asked then to - cancel (don't bother to erase anything in the database) - edit (is not yet saved but the information can be changed) - confirm it (now it's time to save it in the database). And should be accessible only one time, if not completed... it disappears (avoid to create an enormous number of instance in the DB) At the moment everything is static as it save in the DB from the start and stay there, so if someone jsut leave, it will remain in the DB for nothing I looked for some solutions but always cracked below errors. The first one is to directly pass the model instance (Mycard) which landed to > 'str' object has no attribute '_meta' So I looked to pass the information through the URL but it looks like … -
Search engine url, removal get data from empty forms fields. Django, queryset
I create a simple search engine in django. I would like to get a nice URL from here, even if a field will not be selected. For example, I have a simple form in my forms.py class SearchForm(forms.Form): province = forms.ChoiceField(choices=PROVINCE, required=False) brand = forms.ChoiceField(choices=BRAND, required=False) price = forms.IntegerField(required=False) In my views.py, I use it in such a way: def search(request) #data - returns data GET or False province = request.GET.get('province', False) brand = request.GET.get('brand', False) price = request.GET.get('price', False) #search engine form = SearchForm(request.GET) query = Car.objects.all() if province: query = query.filter(province=province) if brand: query = query.filter(brand=brand) if price: query = query.filter(price__gtl=price) return render(request, 'searh.html', {'query' :query}) After filling out the form in the template, URL it looks something like this: http://127.0.0.1:8000/search/?brand=Ford&model=&price= Can I show only the fields that have been selected (As below), if so how to do it? http://127.0.0.1:8000/search/?brand=Ford *does not show '&model=&price='because the user has not entered anything I have one more question, I do not know if I can ask them in this topic. If don't I remove them. But how effective is the use of such a queryset (especially with a large number of fields and a large number of objects. Maybe there are … -
How to use forignkey?
I need to issue a book in my library, so when I click on issue, I need to get the book details to the issuer Here Post is the book details and BookIssue is the Issuer's details. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) book_author = models.CharField(default="",max_length=100) publisher = models.CharField(default="",max_length=100) content = models.TextField(max_length=200) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) issued_book_name = models.ForeignKey(BookIssue, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) class BookIssue(models.Model): issuer_name = models.CharField(max_length=100,null=False) issuer_email = models.EmailField(max_length=254) issuer_phone_number = models.CharField(default="",max_length=10) issuer_address = models.TextField(max_length=300) issued_book = models.OneToOneField( on_delete=models.CASCADE) def __str__(self): return self.issue_name def get_absolute_url(self): return reverse('blog-home', kwargs={'pk' : self.pk}) -
django inline formset with same parent and child model
I have a Person model which has a parent field which is foreign key to itself, so any instance of this model can have a parent which is another instance of the same model. What I am trying to achieve is to add/update children of a Person using the inlineformsets provided by django. However issue I am having is that inlineformset requires different parent and child models. Models.py from django.db import models # Create your models here. class FamilyMember(models.Model): name = models.CharField(max_length=20) age = models.PositiveIntegerField(null=True, blank=True) job = models.CharField(max_length=20, null=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) Views.py def add_child(request): member = FamilyMember.objects.get(name="Tom") child_formset_factory = inlineformset_factory(FamilyMember, FamilyMember, fields=('parent',)) formset = child_formset_factory(instance=member) return render(request, "family/add_child.html", {"formset": formset}) When i render this formset I do not see any children listed for any existing person, even when there are valid records in the db. Instead what I would like to see is this, lets say if a person X has 3 children A, B, C, then I would like to have 3 dropdowns, first dropdown should have A as selected value, second should have B as selected and so on. I am not sure if I am doing it the right way …