如何在Django中编辑和删除数据? [英] How do I edit and delete data in Django?

查看:171
本文介绍了如何在Django中编辑和删除数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是django 1.0,我已经使用Django书中的例子创建了我的模型。我能够执行添加数据的基本功能;现在我需要一种检索该数据的方式,将其加载到一个表单(change_form ?!或某事),编辑并将其保存回数据库。其次我如何删除数据库中的数据?请搜索,然后删除!

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!

请给我一个代码示例,我需要在我的 view.py urls.py 执行此任务。

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

推荐答案

说你有一个模型Employee。要编辑具有主键emp_id的条目:

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()

删除它只是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')

在urls.py中,您需要两个这样的条目:

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

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

我建议您查看文档

这篇关于如何在Django中编辑和删除数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆