How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete!

Please show me an example of the code I need to write on my and for perform this task.

Asked by: Joyce655 | Posted: 28-01-2022

Answer 1

Say you have a model Employee. To edit an entry with primary key emp_id you do:

emp = Employee.objects.get(pk = emp_id) = 'Somename'

to delete it just do:


so a full view would be:

def update(request, id):
   emp = Employee.objects.get(pk = id)
   #you can do this for as many fields as you like
   #here I asume you had a form with input like <input type="text" name="name"/>
   #so it's basically like that for all form fields = request.POST.get('name')
   return HttpResponse('updated')

def delete(request, id):
   emp = Employee.objects.get(pk = id)
   return HttpResponse('deleted')

In you'd need two entries like this:


I suggest you take a look at the docs

Answered by: Ada931 | Posted: 01-03-2022

Answer 2

To do either of these you need to use something called queries.

check link below for really great documentation on that! (

To Delete Data:

b = ModelName.objects.get(id = 1)

This will delete the Object of the model w/ an ID of 1

To edit Data:

b = ModelName.objects.get(id = 1) = 'Henry'

This will change the name of the Object of the model w/ an ID of 1 to be Henry

Answered by: Chester796 | Posted: 01-03-2022

Answer 3

Read the following: The Django admin site. Then revise your question with specific details.

Answered by: Edgar945 | Posted: 01-03-2022

Similar questions

python - when to delete the cache entry in django

In my django application ,I have a BlogEntry which belongs to a Category.A BlogEntry may belong to many Categorys class BlogEntry(models.Model): creationdate=models.DateField( description=models.TextField() author=models.ForeignKey(User,null=True) categories=models.ManyToManyField(Category) class Category(models.Mode...

python - How can i have delete and edit link in django admin change list page

I am using django admin. But there are currenly no delete links infront of every row. they have delete selected thing but i want to have delete and edit with every row of model. how can i do that in django admin

python - Soft delete after 24 hours with Django

I need store a row in DB and after 24 hours mark it as deleted, (just with a flag variable), I am not clear about how I will get this done. I've thought to use Celery+Django to run async task, but when should it be ran? every row will have to be marked as deleted in different moments. Is there any Django...

python - How to delete a forms django

I just wish my delete button deletes the form to a specific id for now I can remove all items but i have an error : 'tuple' object has no attribute '_meta' My def delete_champs(request, instance): #+some code to check if this object belongs to the logged in user logged_user = get_logged_user_from_request(request) if ...

python - PUT and DELETE Django

I relatively new in django and python and now for a couple of days i'm trying to figure how to send PUT and DELETE requests throught django forms. I found this topics:

python - Delete a django model object with blank file field

I have a django model that looks like this class Foo(models.Model): ... article = models.FileField(upload_to='articles', blank=True, default=None, null=True) ... when I try to delete an object bar of Foo model using bar.delete() where any file has not been uploaded in the article field, I get the following error. [Error2] Is...

python - Django - How to allow only the owner of a new post to edit or delete the post?

I will be really grateful if anyone can help to resolve the issue below. I have the following Django project coding. The problem is: when the browser was given &quot;/posts/remove/&lt;post_id&gt;/&quot; or &quot;/posts/edit/(&lt;post_id&gt;/&quot; as the url, it will allow the second user (not owner) to perform the remove and edit jobs, respectively. How can I allow only the owner of a new post to edit or del...

python - How to delete a django JWT token?

I am using the Django rest framework JSON Web token API that is found here on github ( I can successfully create tokens and use them to call protected REST APis. However, there are certain cases where I would like to delete a specific token before its ...

python - Auto delete data which is older than 10 days in django

In my django project I want to auto delete data which is older than 10 days. How can I write this view? How can it execute automatically? In my model there is a post_date field, by which I want to check whether it is 10 days old or not. class CustomerLeads(models.Model): title = models.CharField(max_length=100, null=True, bl...

python - Delete image in Django

I have to delete image from my app. Image has to be deleted from "media" file (directory inside my project) and from database. Here is my class DeleteImage class DeleteImage(DeleteView): template_name = 'layout/delete_photo.html' model = Profile success_url = reverse_lazy('git_project:add_photo') This is HTML page {% extends 'layout/base.html' %} {% block body %...

python - Delete a post in Django

I new to django and I am trying to make a web application. I have this page page image and I want to delete one post when I press the delete button. How can I do that? This is my modal for 'Post' : class Post(models.Model): created_date = models.DateTimeField() title = models.CharField(max_length=100) profile_image = mod...

python - I can't delete users from my app in Django

I am developing a webpage for elderly people in Django for my internship. I received some code already done from another coworker but for some reason when I try to delete users from the /admin site it gives me and error. In addition, I only have one form to register and login in the webpage but it gives another error. login view: def login_view(request): if request.user.is_authenticated: re...

python - How do you delete a Django Object after a given amount of time?

I'm a new Django developer, and working on a website where users can store csv files outputted by the website to a field of a model along with a randomly generated key. I referred to this link: Delete an object automatically after 5 minutes for more information, but when I implemented it onto my own proje...

python - How to delete a row in table with Django

I am new in Django. I am trying to add a delete button to delete the row. However, the output is not what I want because it outputs multiple times because I create a loop to get data for other columns. For this reason, is there a solution the delete button can run outside the loop? add_stock.html {% extends 'base.html' %} {% block content %} &lt;h1&gt;Add Stock&lt;/h1&gt; &lt;form action=&quot;{% ur...

python - How to Do Soft Delete in Django

Hi I am new to Django and I have just completed CRUD using django and postgresql. now my aim is to do SOftDelete but I am unable to do it below is my code def Delemp(request,id): delemployee = EmpModel.objects.get(id=id) delemployee.delete() showdata=EmpModel.objects.all() return render(request,&quot;Index.html&quot;,{&quot;data&quot;:showdata}) I am unable to...

Why won't python allow me to delete files?

I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me: (32, 'The process cannot access the file because it is being used by another process') I've used two different tools to check whether the files are locked or not and I'm certain that they are not. I u...

python - delete a line based on logic

I have a file where i have multiple records with such data F00DY4302B8JRQ rank=0000030 x=800.0 y=1412.0 length=89 now i want to search for the line where if i find length&lt;=50 then delete this line and the next line in the file and write to another file. Thanks everyone

python - delete xml node using lxml

admin . . . . admin this my xml file. when i user clear()or del method it will clear all the child and a blank node is creating &lt;user/&gt; How can i avoid creating this blank node it will make problem when i use findall() and try to access any of its child can anyon...

python - Delete an item from a list

Hey, I was trying to delete an item form a list (without using set): list1 = [] for i in range(2,101): for j in range(2,101): list1.append(i ** j) list1.sort() for k in range(1,len(list1) - 1): if (list1[k] == list1[k - 1]): list1.remove(list1[k]) print "length = " + str(len(list1)) The set function works fine, but i want to apply this meth...

python - Numpy - why value error for NaN when trying to delete rows

I have a numpy array: A = array([['id1', '1', '2', 'NaN'], ['id2', '2', '0', 'NaN']]) I also have a list: li = ['id1', 'id3', 'id6'] I wish to iterate over the array and the list and where the first element in each row of the array is not in the list, then delete that entire row from the array. My code to date: from numpy...

python - How to delete a record from table?

I have a problem with deleting a record from my SQLite3 database: conn = sqlite3.connect('databaza.db') c = conn.cursor() data3 = str(input('Please enter name: ')) mydata = c.execute('DELETE FROM Zoznam WHERE Name=?', (data3,)) conn.commit() c.close Everything is OK, no errors, but the delete function doesn't work! Does anyone have an idea?

python - How to delete an item in a list if it exists?

I am getting new_tag from a form text field with self.response.get("new_tag") and selected_tags from checkbox fields with self.response.get_all("selected_tags") I combine them like this: tag_string = new_tag new_tag_list = f1.striplist(tag_string.split(",") + selected_tags) (f1.striplist is a function th...

python - Cannot seem to delete an object number

I seem to have a problem deleting order numbers in Django. In my views, there is an order number equals to some pk value. There is also a submit button which should delete this number in the template. Unfortunately it is doing nothing (not deleting). For some reason I thought these changes would delete an object, but it's still not working. Basically I have this. order = models.Order.object...

python - delete everything from output which is behind ":"

when python gives me an output in form like: randomfilename.txt:randomstringmniaonovinaio How can i make from it just randomfilename.txt in python/shell?

python - Delete rest of HTML file after some text

I am scraping HTML file using BeautifulSoup in python. I want to delete text after find a word. Ex: &lt;div class="content"&gt; &lt;p&gt; Page 1 &lt;/p&gt; &lt;p&gt; Page 2 &lt;/p&gt; &lt;p&gt; Page 3 &lt;/p&gt; &lt;p&gt; Page 4 &lt;/p&gt; &lt;p&gt; Page 5 &lt;/p&gt; &lt;/div&gt; I want to delete from Page 3. &lt;div class="content"&gt; &lt;p&gt; Page 1 &lt;/p&gt...

python - What's the best Django search app?

How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.

python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.

python - What is the best way to copy a list?

This question already has answers here:

python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?

python - How do I turn an RSS feed back into RSS?

According to the feedparser documentation, I can turn an RSS feed into a parsed object like this: import feedparser d = feedparser.parse('') but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XM...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python