Home > Software design >  How do I pass primary key of the entry created by a django-form, to the form in next page after that
How do I pass primary key of the entry created by a django-form, to the form in next page after that

Time:02-07

My Models.py contains 2 models, each Project can have multiple Role (i.e. one-to-many relationship):

class Project(models.Model):
    title = models.CharField(max_length=2000)
    state_of_project = models.CharField(max_length=10, default='ongoing')
    introduction = models.TextField(blank=True)

class Role(models.Model):
    role_name =  models.CharField(max_length=30)
    project = models.ForeignKey(Project, on_delete=models.SET_NULL, null = True)
    
    def __str__(self):
        return self.role_name 

After submitting a form for model Project, I wanted to redirect user to fill the next form for model Role. The new roles added there should automatically have their foreign key project point towards the project created just before.

How can I make that happen? I am specifically having problem adding mechanism of passing the primary key of newly submitted entry (for model Project) to the next form(for model Role).

CodePudding user response:

You have to pass the primary key to urls.py and get it through the views.py

for example :

#urls.py
path("add-role/<int:project_id>" ,views.add_role , name="add.role"),


------------

#views.py
def add_role(request , project_id):
        project = Project.objects.get(id=project_id)
        if request.method == "POST":
            form = ProjectForm(request.POST)
            if form.is_valid():
                f = form.save(commit=False)
                f.project = project
                f.save()
                return redirect("projects")
            else:
                return render(request , 'add-project.html' ,{"form":form})
        return render(request , 'add-project.html' ,  {"project":project})

and something like this in your html:

<form method="post" action="{% url 'add.role' project.id %}">
 {% csrf_token %}
 <input type="text" name="role_name" />
</form>
  •  Tags:  
  • Related