user16860615
user16860615

Reputation:

Deleting objects once inputted

I am building a simple web app, in which - I am trying to implement a feature that -

If a word inputted by user in the Another models's objects then the word will be deleted, I mean, I have stored few names on a model like :- car, bike, rain, and calendar. And I made another model named BlogPost, So when user submit form and if the mentioned name in the another model's objects then the name will be deleted. but the name is not deleting.

models.py

class BlogPost(models.Model):
    title = models.CharField(max_length=30,default='')
    name = models.CharField(max_length=30,default='')

class All_Name(models.Model):
    names = models.CharField(max_length=30,default='')

views.py

def new_blog_post(request):
    allNames= All_Name.objects.all().values_list('names', flat=True)

    if request.method == 'POST':
        form = PostForm(data=request.POST)
        if form.is_valid():

            formName = form.cleaned_data['name']
            new_post = form.save(commit=False)
            if formName in allNames:
                new_post.save()
       # Deleting Here
                allNames = formName
                allNames.delete()
                
            else:
                return redirect('home')

    else:
        form = PostForm()

    context = {'form':form}
    return render(request, 'new_blog_post.html', context)

What have i tried ? :-

formName.delete()

But it is not saving anything and not deleting the Name.

allNames.delete()

But it is showing

Cannot call delete() after .values() or .values_list()

I have tried many times but nothing worked for me.

Thank You.

Upvotes: 1

Views: 45

Answers (1)

Ruchit Micro
Ruchit Micro

Reputation: 604

Your delete logic is wrong. Here's what you should do.

allNames = All_Names.objects.get(names = formName) #Fetch the actual record from the ORM and then call delete
allNames.delete()

The reason it showed an error when you called .delete() is because value_list() collapses the ORM abilities of Django and gives returns you a native python list format. .delete() is a ORM feature of Django.

Upvotes: 1

Related Questions