Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 view.py and urls.py for perform this task.

like image 518
Gath Avatar asked Nov 22 '08 10:11

Gath


People also ask

How do I delete a specific record in Django?

To delete a record we do not need a new template, but we need to make some changes to the members template. Of course, you can chose how you want to add a delete button, but in this example, we will add a "delete" link for each record in a new table column. The "delete" link will also contain the ID of each record.

How do I delete a field in Django?

If you want to drop the data completely, you need to create a Django migration (using ./manage.py makemigrations preferably) that will remove those columns from the database.


1 Answers

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

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

to delete it just do:

emp.delete()

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
   emp.name = request.POST.get('name')
   emp.save()
   return HttpResponse('updated')

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

In urls.py you'd need two entries like this:

(r'^delete/(\d+)/$','myproject.myapp.views.delete'),
(r'^update/(\d+)/$','myproject.myapp.views.update'),

I suggest you take a look at the docs

like image 125
Vasil Avatar answered Oct 03 '22 18:10

Vasil