Been stuck at this trying to delete data from the database, I'm clearly lost with the logic somewhere I'd grately appreciate any assistance.
resume-detail.html:
<div >
{% if educations %}
{% for education in educations %}
<div >
<div >
<div >
<h4 >{{education.institution}}</h4>
</div>
<div >
<div >
<div >
<p><strong>Qualification: </strong> {{education.qualification}}</p>
</div>
<div >
<p><strong>Level of Qualification: </strong> {{education.level}}</p>
</div>
</div>
<div >
<div >
<a href="{% url 'delete' educations.id %}" >Delete Qualification </a>
<!-- <button >Delete Qualification</button> -->
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
</div>
<div >
<div >
<h4 ><button type="button" data-toggle="modal" data-target="#addEducation"><span > </span> Add Education</button></h4>
</div>
</div>
i'm using a modal to capture this data
<div id="addEducation" tabindex="-1" aria-labelledby="addEducationLabel" aria-hidden="true">
<div >
<div >
<form action="" method="POST">
{% csrf_token %}....
urls.py
path('userapp/view/<slug:slug>/', user_views.resume_detail, name='resume-detail'),
path('delete/<str:id>/', user_views.delete_view, name='delete' )
views.py
def delete_view(request, id):
obj = Resume.objects.get(id = id)
if request.method =="POST":
obj.delete()
messages.success(request,"Information Deleted Successfully")
return redirect('resume-detail', id = id)
educations = Education.objects.get(resume = obj)
experiences = Experience.objects.get(resume = obj)
context = {}
context['object'] = obj
context['educations'] = educations
context['experiences'] = experiences
return render(request, 'resume-detail.html', context)
I would like to delete data for educations and experiences. Its the data I capture with the modals. What could I be doing wrong ?
models.py
class Resume(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
uniqueId = models.CharField(null=True, blank=True, max_length=200)
image = models.ImageField(default = 'default.jpg', upload_to='profile_images')
email_confirmed = models.BooleanField(default=False)
date_birth = models.DateField(blank=True, null=True)
sex = models.CharField(choices=SEX_CHOICES, default=OTHER, max_length=200)
marital_status = models.CharField(choices=MARITAL_CHOICES, default=SINGLE, max_length=200)
addressLine1 = models.CharField(null=True, blank=True, max_length=200)
addressLine2 = models.CharField(null=True, blank=True, max_length=200)
village = models.CharField(null=True,blank=True, max_length=200)
city = models.CharField(null=True, blank=True, choices=DISTRICT_CHOICES, default=KAMPALA, max_length=200)
district = models.CharField(choices=DISTRICT_CHOICES, default=KAMPALA, max_length=100)
phoneNumber = models.CharField(null=True, blank=True, max_length=200)
slug = models.SlugField(max_length=500, unique=True, blank=True, null=True)
date_created = models.DateTimeField(default= timezone.now)
last_updated = models.DateTimeField(blank=True, null=True)
cover_letter = models.FileField(upload_to='resumes', null=True, blank=True,)
cv = models.FileField(upload_to='resumes', null=True, blank=True,)
def __str__(self):
return '{} {} {}'.format(self.user.first_name, self.user.last_name, self.uniqueId)
def get_absolute_url(self):
return reverse('resume-detail', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if self.uniqueId is None:
self.uniqueId = str(uuid4()).split('-')[0]
self.slug = slugify('{} {} {}'.format(self.user.first_name, self.user.last_name, self.uniqueId))
if self.image == 'default.jpg':
self.image = random.choice(self.IMAGES)
self.slug = slugify('{} {} {}'.format(self.user.first_name, self.user.last_name, self.uniqueId))
super(Resume, self).save(*args, **kwargs)
class Education(models.Model):
institution = models.CharField(null=True, max_length=200)
qualification = models.CharField(null=True, max_length=200)
level = models.CharField(choices=LEVEL_CHOICES, default=LEVEL5A, max_length=200)
start_date = models.DateField()
graduated = models.DateField()
major_subject = models.CharField(null=True, max_length=200)
date_created = models.DateTimeField(default = timezone.now)
resume = models.ForeignKey(Resume, on_delete=models.CASCADE)
def __str__(self):
return '{} for {} {}'.format(self.qualification, self.resume.user.first_name, self.resume.user.last_name)
class Experience(models.Model):
company = models.CharField(null = True, max_length=200)
position = models.CharField(null = True, max_length=200)
start_date = models.DateField()
end_date = models.DateField()
experience = models.TextField()
skills = models.TextField()
resume = models.ForeignKey(Resume, on_delete = models.CASCADE)
def __str__(self):
return '{} at {}'.format(self.position, self.company)
CodePudding user response:
As @SunderamDubey said, if you need objects Education
and Experience
based by the Resume
relation - edit your urls.py
path to accept delete/<int:resume_pk>
instead of delete/<str:slug>/
.
Then:
# urls.py
path('delete/<int:resume_pk>/', user_views.delete_view, name='delete')
# views.py
def delete_view(request, resume_pk):
obj = Resume.objects.get(id=resume_pk)
...
educations = Education.objects.get(resume=obj)
experiences = Experience.objects.get(resume=obj)
...
# modal
<form action="{% url 'delete' resume_pk=obj.pk %}" method="POST">
CodePudding user response:
You need to give id
which is primary key in the Education
model, so:
<form action="{% url 'delete' educations.id %}" method="POST">
{% csrf_token %}....
Add education
as ForeignKey in the model, so:
class Resume(models.Model):
education=models.ForeignKey(Education,on_delete=models.CASCADE)
Change the url as:
path('userapp/view/<int:id>/', user_views.resume_detail, name='resume-detail'),
path('delete/<int:id>/', user_views.delete_view, name='delete' )
Then in view, get the object through id
then delete it.
from django.shortcuts import get_object_or_404
def delete_view(request, id):
education_instance=get_object_or_404(Education,id=id)
obj = get_object_or_404(Resume, education=education_instance)
if request.method =="POST":
obj.delete()
messages.success(request,"Information Deleted Successfully")
return redirect('resume-detail', id=id)
educations = get_object_or_404(Education, resume=obj)
experiences = get_object_or_404(Experience,resume=obj)
context = {}
context['object'] = obj
context['educations'] = educations
context['experiences'] = experiences
return render(request, 'resume-detail.html', context)
Note:
Generally, it is better to useget_object_or_404()
instead ofget()
as it calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.