Hi,
I’m trying to work out how i can check a record exists in 1 model and then if true render a specific template.
There are 2 models. Project and Fundamentals. The Fundamentals has a FK to the projects model.
class Project(models.Model):
project_name = models.CharField(max_length=50, blank=False, unique=True)
project_website = models.URLField(max_length=50, blank=True)
project_description = models.TextField(blank=True)
ckeditor_classic = models.TextField(blank=True)
project_category = models.CharField(max_length=15, blank=True)
def __str__(self):
return str(self.project_name)
and
class Fundamentals(models.Model):
project_name = models.ForeignKey(Project, to_field='project_name', on_delete=models.CASCADE)
project_roadmap = models.CharField(max_length=25, blank=True)
project_tier_entry_level = models.CharField(max_length=25, blank=True)
project_tier_entry_level_notes = models.CharField(max_length=25, blank=True)
project_rebranded = models.CharField(max_length=25, blank=True)
def __str__(self):
return str(self.project_name)
If the PK (project_name ) already exists in the fundamentals model i wanted to render a update_fundamentals.html but im not sure how i check if exists.
my view
@login_required
def Add_or_updateFundamentals(request,project_id):
project = Project.objects.filter(pk=project_id)
check_exist = Fundamentals.objects.filter(project_name_id=project_id)
if request.method == 'POST':
if check_exist:
form = AddFundamentalsForm(request.POST,instance=project[0])
else:
form = AddFundamentalsForm(request.POST)
if form.is_valid():
if not check_exist:
form.instance.project = project
form.save()
return redirect('dashboard.html')
else:
if check_exist:
form = AddFundamentalsForm(instance=project[0])
return render(request, 'pages/update_fundamentals.html', {'project': project, "form": form})
else:
form = AddFundamentalsForm()
return render(request, 'pages/add_fundamentals.html', {'project': project, "form": form})
But this doesn’t seem to work. Any ideas?
Thanks