Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax post requests seem to not work for some users?
I've been testing my site by having friends try it, and some friends have an issue where some of my javascript functions don't work, and some functions do. After figuring out it's not their browsers or devices, I noticed the functions that weren't working for them were the ones with Ajax post requests, so I think that's the issue here. Does anyone know why Ajax post requests work for only some users? Also, FYI, I'm using Django as a framework. Example of one of my functions using ajax: $('#button').click(function(){ $.ajax({ url: '/get_url/', type: "POST", data: { data_name: data_to_send }, beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", csrftoken); }, success: function (data) { //change some html text using data }, error: function (error) { console.log(error); } }); }); -
How to capture selected values, in Django, from two separate select fields and pass it to the view upon form submission?
I am trying to create a filtered list from model class "Animal" based off of two separate select field drop down values. If user selects "baby" and "dog" then a list of puppies would be generated from the Animal model. I cannot seem to figure out how to capture the value pks for both the "age_group" and "type" fields so that I can use them to filter the queryset. Any suggestions or guidance is appreciated. I am very new to Django. models.py class Animal(models.Model): name = models.CharField(max_length=500, blank=False, null=False) type = models.ForeignKey(Type, on_delete=models.SET_NULL, blank=False, null=True) ageGroup = models.ForeignKey(AgeGroup, max_length=300, on_delete=models.SET_NULL, blank=False, null=True) age = models.PositiveIntegerField(blank=False, null=False) sex = models.CharField(max_length=100, choices=SEX, blank=False, null=False, default='NA') breedGroup = models.ManyToManyField(BreedGroup, blank=False) breed = models.ManyToManyField(Breed, blank=False) tagLine = models.CharField(max_length=300, blank=False, null=False) goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information') goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information') goodWKids = models.BooleanField(null=False, blank=False, default='Not Enough Information') forms.py class AnimalSearchForm(ModelForm): chooseType = ModelChoiceField(queryset=Animal.objects.values_list('type', flat=True).distinct(),empty_label=None) chooseAge = ModelChoiceField(queryset=Animal.objects.values_list('ageGroup', flat=True).distinct(), empty_label=None) class Meta: model = Animal exclude = '__all__' views.py class VisitorSearchView(View): def get(self, request): animalList = AnimalSearchForm(self.request.GET) context = {'animal_list': animalList} return render(request, "animals/landing.html", context) templates {% extends 'base.html' %} {% block content %} <h1>Animal Search</h1> <form class="form-inline" action="." method="POST"> {% … -
POST 500 error django react site, POST /api/create-room
I have created a component for a Django React Rest Framework site and I keep getting an error when I click on the Create Room button on my site. The error seems to be located at the fetch portion of the component for the CreateRoom.js file I created. Any help in identifying the issue is much appreciated. Here is the error and the code that seems to be triggering the error. Please take a look at what I've got and let me know if I can provide any more information to help figure out what the issue is. Usually I try and figure it out myself but I've spent hours doing so and haven't been able to figure it out. Error: CreateRoomPage.js:67 POST http://localhost:8000/api/create-room 500 (Internal Server Error) handleRoomButtonPressed @ CreateRoomPage.js:67 Rb @ react-dom.production.min.js:52 Xb @ react-dom.production.min.js:52 Yb @ react-dom.production.min.js:53 Ze @ react-dom.production.min.js:100 se @ react-dom.production.min.js:101 eval @ react-dom.production.min.js:113 Jb @ react-dom.production.min.js:292 Nb @ react-dom.production.min.js:50 jd @ react-dom.production.min.js:105 yc @ react-dom.production.min.js:75 hd @ react-dom.production.min.js:74 exports.unstable_runWithPriority @ scheduler.production.min.js:18 gg @ react-dom.production.min.js:122 Hb @ react-dom.production.min.js:292 gd @ react-dom.production.min.js:73 create:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.then (async) handleRoomButtonPressed @ CreateRoomPage.js:67 Rb @ react-dom.production.min.js:52 Xb @ react-dom.production.min.js:52 … -
My images is lost it, after to send from reactjs, in my backend django
I have problem with send images from reactjs to django, before to send images, my images is present, but after the send that images to django, lost it, why?, please help me, my code is bellow. file send images import React from 'react' import {userForm} from 'react-hook-form' import {MyClass} from '../../somewhere' type uploadType = { imagen_main: any more_data: string } const SendImages:React.FC = () =>{ const [showImg, SetShowImg] = React.useState() let SendData = new Myclass() const {register, handleSubmit, errors} = userForm<uploadType>({ mode: 'onChange' }) const onSubmit = handleSubmit({imagen_main, more_data}) => { let send_data = { imagen_main: imagen_main[0], // HERE I TRY REMOVE [0], BUT NOT WORKING more_data: more_data } // HERE SHOW ME MY IMAGES BEFORE THE SEND AND MY ANOTHER DATA console.info(send_data) SendData.saveData().then(resp => { console.info(resp.data) }).catch(err => { console.error(err) // ALWAYS IN HERE }) } // THIS FUNCTION IS LIKE A PREVIEW THE IMAGES const onChange = (event: React.ChangeEvent<HTMLInputElement>) => { let file: any = event.currentTarget.files let reader = new FileReader() reader.onloadeend = () => { SetShowImg(reader.result) } reader.readAsDataURL(file[0]) } return( <form onSubmit={onSubmit} encType="multipart/form-data"> <input type='file' name="imagen_main" ref={register({required: true})} accept="image/png, image/jpeg" onChange={_onChange} /> {/* A PREVIEW IMAGES */} <img src={showImg ? showImg: '' } /> <input type="text" name="more_data" … -
How to create model/view/serializer with multiple rows in django?
I am a newbie in django and am trying to create a social media type app. So, I have created this models: Post (to create a post) Comment (to comment on post) And so far I have views like /api/post /api/post/1 (to fetch post with id 1) /api/post/1/comment (to comment on post) /api/post/1/comment/1 (to fetch comment with id 1 on post 1) Now, I am trying to make an API /api/feed (that gives the home feed of posts for a given user) (and also, a user unable to see other user feed.. i.e. they can only see their feed) I am at lost of how to define a model, serializer and view here. Basically, what I want to send to user is something like this [ { 'id': 'some unique id', 'user' :foo, 'post_id': some_post_id}, {'id': 'some unique id','user' :bar, 'post_id': some_post_id}, {'id': 'some unique id','user' :baz, 'post_id': some_post_id}, {'id': 'some unique id','user' :foobar, 'post_id': some_post_id} ] What I don't particularly understand is how to generate same unique id for all the posts in the feed.. Also, bonus points on how to implement infinite scroll? -
Is there a way to generate an "infinite" amount of charts using chart.js in Django?
I am relatively new to Django and HTML. I need to display many charts on one page in Django. I know that I need to give each of these charts a different id value in the tag, but haven't been able to. Here's what I'm working with. <script>var count = 0;</script> <ul> forloop open here of the different elements on the page <li> <script> count = count + 1; ... eval('var chart_id = "myChart' + count + '"'); eval('var ctx' + count + ' = document.getElementById(chart_id)'); eval('var myChart = new Chart(ctx' + count + ', graph_data)');` </script> <canvas id= myChart1 width="400" height="400"></canvas> </li> for loop close here I haven't been able to pass in variables to the id of the tag or find an equivalent to the eval() function that could work in HTML. The real maximum number of charts I could need is roughly 100, but I am trying to treat it as if it's an infinite number. Worst case, I could use brute force and make 100 if statements that say if the count is a certain number, display the corresponding chart, but I am trying to find a cleaner solution. If there isn't a way to do … -
Passing bunch of data/list in Django ajax
I'm having a trouble to filter all data in my looping. In the first place in my views.py I tried to print my for loop and it works fine and it filter the list under paid_by. The problem is when I pass the data to my ajax it only returns one data, and I think it should be done by using looping, how can I implement it?.Is there any way or idea that can solve this problem? Thanks in advance for p in Person.objects.raw('SELECT id, paid_by, IF(paid = "Yes" || paid = "YES", "paid", "unpaid") as id,paid, category, category_status, count(paid) FROM app_person WHERE paid_by != "" GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid'): print(p.paid_by) # I tried to print it works fine it filter the list under paid_by list_sample= p.paid_by totals = {'list_report':list_sample} return JsonResponse(totals) ajax success: function(response){ console.log(response.list_report) # When I tried to view my console it retrieve only one data instead bunch of data $("#rports").modal('show'); $("#rports").val(null).trigger("change"); } -
How to use post and get with django and react
I would like to know how can I recieve data from React and using Django what I'm trying to do right know is to send coordinates from react to django but I don't know what I should do. There are some things I don¿t understand like how I'm suposed to connect both parts? do they have to be in the same folder first? I'm asking because I deployed my app on heroku but only the backend side -
Django Error - NoReverseMatch at /listings/1. Reverse for 'addcomment' with arguments '('',)' not found. (Creating a comment section)
I'm new to Django and I think I'm having issues setting up a dynamic url. I'm creating a way to add comments to a page, called a listing. The listing page loaded fine before I added anything about comments. When I try to go to that particular listing, I get the error: "NoReverseMatch at /listings/1. Reverse for 'addcomment' with arguments '('',)' not found. 1 pattern(s) tried: ['addcomment/(?P[0-9]+)$']" Any help is appreciated because even after looking at the documentation I am having trouble understanding how dynamic urls work/how to create them. I think my html page might also have problems, in terms of pulling in the correct info with the url etc. views.py urls.py models.py html for the listing page -
Dealing with nested serializer validation in Django Rest Framework
What would be a good way to handle creating an object that has a ManyToMany field? class PersonSerializerForScene(serializers.ModelSerializer): class Meta: model = Person fields = ['id', 'name'] class MovieSerializer(serializers.ModelSerializer): people = PersonSerializerForScene(many=True) class Meta: model = Scene fields = ['id', 'title', 'description', 'people', 'pub_date'] I thought of posting data to the people field in a list of ids format, for example [ 198, 87, 52 ] iterate over these values in the create method of the MovieSerializer filter people with the submitted ids and add them to the newly created object, but this approach doesn't seem to work since the nested serializer expects an array of dictionaries. -
How do I structure YAML data for a many-to-many field (Python 3.9, Django 3)?
I'm using Python 3.9 and Django 3.0. I have defined the following models. The second has a many-to-many relationship with the first ... class CoopType(models.Model): name = models.CharField(max_length=200, null=False) objects = CoopTypeManager() class Meta: # Creates a new unique constraint with the `name` field constraints = [models.UniqueConstraint(fields=['name'], name='coop_type_unq')] ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() For the child entity, I have defined this "get_by_natural_key" method (the name field) ... class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] How do I structure my YAML so that I can create a Coop with multiple types? This YAML works fine when there is only one type pk: 243 fields: name: "Dill Pickle Food Co-op" types: - ['food coop'] but when I try and add more than one type, like so ... pk: 243 fields: name: "Dill Pickle Food Co-op" types: - ['store', 'food coop'] I get this error ... django.core.serializers.base.DeserializationError: Problem installing fixture '/tmp/seed_data.yaml': get_by_natural_key() takes 2 positional arguments but 3 were given: (directory.coop:pk=243) field_value was '['store', 'food coop']' -
Django ou PHP WordPress [closed]
Boa Noite Pessoal, tudo bem? Tenho a seguinte dúvida estou estudando desenvolvimento web e de início já estou aprendendo a fazer alguns sites e gostaria de fazer a parte administrativa, é aí que entra minha dúvida a hospedagem em Django é do mesmo preço do q a de PHP, é melhor WordPress ou Django pra sites institucionais por exemplo? -
Access Django admin from Firebase
I have a website which has a React frontend hosted on Firebase and a Django backend which is hosted on Google Cloud Run. I have a Firebase rewrite rule which points all my API calls to the Cloud Run instance. However, I am unable to use the Django admin panel from my custom domain which points to Firebase. I have tried two different versions of rewrite rules - "rewrites": [ { "source": "/**", "run": { "serviceId": "serviceId", "region": "europe-west1" } }, { "source": "**", "destination": "/index.html" } ] --- AND --- "rewrites": [ { "source": "/api/**", "run": { "serviceId": "serviceId", "region": "europe-west1" } }, { "source": "/admin/**", "run": { "serviceId": "serviceId", "region": "europe-west1" } }, { "source": "**", "destination": "/index.html" } ] I am able to see the log in page when I go to url.com/admin/, however I am unable to go any further. Just as an FYI, it is not to do with my username and password as I have tested the admin panel and it works fine when accessing it directly using the Cloud Run url. Any help will be much appreciated. -
Re-create django migrations without migrations folder
I have a bit of an issue. I tried to re-create my sqlite db of my project. Only problem is that by uploading my project on a git, I ignore the "migrations" folder of each app so my client wouldn't be bothered by it (wrong practice?). But today, I would like to take that db from scratch (column order, recreate full install from csv data, ...) but when i execute my migrations commands, they detect no changes and only migrate django table. Django version : 2.0.13 Python : 3.7.3 -
Passing data through from form submission depending on value
I am trying to pass data through from a form depending on different calculations from the form submission Model class Price(models.Model): name = models.CharField(max_length=100) contract = models.CharField(max_length=5, choices=year_choice) start_date = models.DateField(default=datetime.now) end_date = models.DateField(default=datetime(2021,3,31)) epoch_year = date.today().year year_start = date(epoch_year, 1, 4) year_end = date(epoch_year, 3 , 31) def __str__(self): return self.name @property def pricing(self): price_days = self.start_date - self.year_end return price_days Views def price_detail(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = PriceForm(request.POST) # check whether it's valid: if form.is_valid(): form.save() return render(request,'confirmation.html',{'form_data': form.cleaned_data}) else: form = PriceForm() return render(request, 'main.html', {'form': form}) So the idea is to change show details on the confirmation.html page depending on the contract type and start date, a basic but most like incorrect example is below: def pricingcalc(request): if PriceForm.contract == 'year1' return Price.pricing * AdminData.day_rate_year1 else return Price.pricing * AdminData.day_rate_year3 To summarise: List output of values on confirmation page Output based on number of days x price depending on a one year contract or a three year contract. Hope this makes sense. Thanks for the help. -
How can I extend a Django Form class?
I want to create multiple, similar forms based on this one: class DatabaseForm(forms.Form): label = "Database label" # This does not work, but I also can't define it in __init__ method, as I can't access self below in "name" field name = forms.BooleanField(label=label, required=False) username = forms.CharField(label="Username", required=False) password = forms.CharField(label="Password", required=False) where I only change the label, like this: class MySQLForm(DatabaseForm): label = "MySQL" # Somehow override label of super class How can I achieve this? -
Django dynamic HTML table - row insertion issue
I'm trying to create a HTML table that the users can fill with DB data (in this case, jump parameters) that they request with a form. This data will then be used to create a chart with Highcharts. I got to the point where I successfully load the requested Jump to the table, but somehow the row is automatically erased after I insert it. Can you please tell me what I'm doing wrong? Also if you can think of a better approach to what I'm trying to do, I'm more than open to suggestions. Thanks! main/views.py @login_required def index(request): current_user = Person.objects.get(person_user=request.user) if request.method == 'GET': current_user = Person.objects.get(person_user=request.user) data = {'current_user_id': current_user.id} form = PersonJumpSelectForm(initial=data) context = { 'form': form, } return render(request, 'main/index.html', context) charts/views.py def insert_data(request): jump_requested = Jump.objects.get(pk=request.GET['date']) context = { 'jump_requested': jump_requested, } if request.is_ajax(): data = {'rendered_table': render_to_string('charts/table.html', context=context)} return JsonResponse(data) index.html <div class="row no-gutters"> <div class="col-2 chart-container form-col"> <h2>Opciones</h2> <form id="get-data-form" data-jumps-url="{% url 'charts:ajax_load_jump' %}" novalidate> {{form}} <button id="data-form-btn" insert-data-url="{% url 'charts:insert_data' %}" class="data-form_btn full-width hov green-border transparent" type="submit">Graficar</button> </form> </div> <div class="col-7 chart-container"> <div id="container2"></div> </div> <div class="col-3 table-col"> <table id="jump-table" class="data-table"> <tr> <th>Tipo de salto</th> <th>Altura</th> <th>Tiempo de salto</th> <th>Velocidad</th> <th>Potencia</th> … -
Vue in Django app - How to setup Vue instance from static js files
I'm struggling with initializing the vue instance from separate js file (I don't ant to keep the code inside each template html). template: <html> <head> <title>Cinema project</title> <meta name="viewport" content="width=device-width, initail-scale=1.0"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.4.0.min.js"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> {% load static %} </head> <body> <div class="container"> <ul class="list-group mt-2"> {% for x in huj%} <li class="list-group-item">{{x}}</li> {% endfor %} </ul> [[rate]] </div> <script src="{% static 'js/vue.js' %}" type="text/javascript"></script> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </body> </html> js_file: new Vue({ delimiters: ['[[', ']]'], el:".container", data: { rate: "test", }, }) The staticfiles_dir works - I tested it with some random js code. In the above vue instance simply can't hook with my template. Is there any way to fix it ? -
Any advice for python hosting server? [closed]
I have just finished a python Django project and I need a good hosting server any advices with good price and performance -
django get queryset which is latest of other column value
I have a model with some columns, between them there are 2 columns: equipment_id (a CharField) and date_saved (a DateTimeField). I have multiple rows with the same equipment_id and but different date_saved (each time the user saves the record I save the now date time). I want to retrieve a list of records that have a specific equipment_id and is the latest saved, i.e.: | Equipment_id | Date_saved | | --- ----- | --------------------- -------- | | 1061a | 26-DEC-2020 10:10:23| | 1061a | 26-DEC-2020 10:11:52| | 1061a | 26-DEC-2020 10:22:03| | 1061a | 26-DEC-2020 10:31:15| | 1062a | 21-DEC-2020 10:11:52| | 1062a | 25-DEC-2020 10:22:03| | 1073a | 20-DEC-2020 10:31:15| Output: | 1061a | 26-DEC-2020 10:31:15| | 1062a | 25-DEC-2020 10:22:03| | 1073a | 20-DEC-2020 10:31:15| I have tried various approach without success: try: progall=Program.objects.filter(equipment_id__startswith=str(b_id_to_search)).latest('saved_date') The command doesn't work, the program goes to the except line -
Docker Compose and Django app using AWS Lighstail containers fail to deploy
I'm trying to get a Django application running on the latest version of Lightsail which supports deploying docker containers as of Nov 2020 (AWS Lightsail Container Announcement). I've created a very small Django application to test this out. However, my container deployment continues to get stuck and fail. Here are the only logs I'm able to see: This is my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ And this is my docker-compose.yml: version: "3.9" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . image: argylehacker/app-stats:latest command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db I'm wondering a few things: Right now I'm only uploading the web container to Lightsail. Should I also be uploading the db container? Should I create a postgres database in Lightsail and connect to it first? Do I need to tell Django to run the db migrations before the application starts? Is there a way to enable more logs from the containers? Or does the lack of logs mean that the containers aren't even able to start. Thanks for the help! -
how do I make sure a particular user is the one logged in?
so I have some code which creates a user but how do I make sure every url that the user goes to will be in his/her own "user session" such that request.user will be the user i created? def liked(request): try: sp = Spotify(auth_manager=oauth) liked = sp.current_user_saved_tracks(limit=30)['items'] spotify_user = sp.current_user() user__ , created = User.objects.get_or_create(username=spotify_user['uri'], first_name=spotify_user["display_name"]) userprofile = UserProfile.objects.get_or_create(user=user__)[0] i have other views i want only accessible to the user created or gotten from the get_or_create, i reckon I'd have to use the @login_required decorator but then again I do not know what constitutes this "login" with respect to the userI created. How do I do ensure that user is the logged in user? -
Django adding foreign key
I am working on a student assignment submission project, I have made the submission model, which has assignment as foreign key to question, student as a foreign key to the profile. I am working on some way where teacher can select the list of students who have submitted the assignment and assign marks to them, I tried the following way, but its form is not getting validated stating that "select a valid choice" Submission model class Submission(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, verbose_name='assignment') student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE, verbose_name='student') answer = models.URLField() time_submitted = models.DateTimeField(auto_now_add=True) marks_obtained = models.IntegerField(null=True) MarkUpdateForm class MarksUpdateForm(forms.ModelForm): class Meta: model = Submission fields = ['student', 'marks_obtained'] def __init__(self, *args, **kwargs): self.assignment_id = kwargs.pop('assignment_id', None) super(MarksUpdateForm, self).__init__(*args, **kwargs) self.fields['student'].queryset = Submission.objects.filter(assignment__id=self.assignment_id).values_list( 'student__user__username', flat=True) My view form = MarksUpdateForm(request.POST) if form.is_valid(): row = Submission.objects.get(id=assignmentId, student__user__username=form.cleaned_data['student']) row.marks_obtained = form.cleaned_data['marks_obtained'] row.save() messages.success(request, message="Marks Updated Successfully") else: print(form.errors) I tried updating my marksupdateform by overriding label_from_instance and creating custom form instead of model form, but didnt solve the error of "select a valid choice" Thank you. -
Recreate deleted django_migrations table
I am building a Django web application and I dropped the table django_migrations using psql command line and I want to recreate it. -
How to save an Inline Formset inside another?
I have the following situation: I have to create a project, and inside this project I can have multiple internships and for each internship I can have multiple interns. I was able to create and save the Internship, but I can't find a way to create the interns. Is there a way to do so? Here's my code: view.py def cadastrar_bolsa(request, projeto_id): if request.method == 'GET': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = EditForm(instance=projeto_editar) form_bolsa_factory = inlineformset_factory(Projeto, Bolsa, form=BolsaForm, extra=1) form_bolsa = form_bolsa_factory(instance=projeto_editar) form_bolsista_factory = inlineformset_factory(Bolsa, Bolsista, form=BolsistaForm, extra=1) form_bolsista = form_bolsista_factory(instance=????) context = { 'form': form, 'form_bolsa': form_bolsa, 'form_bolsista': form_bolsista, 'id': projeto_id, } return render(request, 'cadastrar_bolsa.html', context) elif request.method == 'POST': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = EditForm(request.POST, instance=projeto_editar) form_bolsa_factory = inlineformset_factory(Projeto, Bolsa, form=BolsaForm, extra=1) form_bolsa = form_bolsa_factory(request.POST, instance=projeto_editar) form_bolsista_factory = inlineformset_factory(Bolsa, Bolsista, form=BolsistaForm, extra=1) form_bolsista = form_bolsista_factory(instance=????) if form.is_valid() and form_bolsa.is_valid(): projeto_editado = form.save() form_bolsa.instance = projeto_editado form_bolsa.save() ????? return redirect('bolsas', projeto_id) else: context = { 'form': form, 'form_bolsa': form_bolsa, 'form_bolsista': form_bolsista, 'id': projeto_id, } return render(request, 'cadastrar_bolsa.html', context) I've put question marks on the part I couldn't find a way to solve.