主键检查django [英] Primary key check in django

查看:234
本文介绍了主键检查django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型中的这个自定义主键:

  class Personal(models.Model):
name = models.CharField(max_length = 20,primary_key = True)
email = models.EmailField(blank = True,null = True)

现在我没有得到的东西是,我如何创建我的视图,以便没有输入重复的记录?我在线搜索,但可以找到任何技术来获取视图创建。



这里是视图的代码

  def uregister(request):
errors = []
如果request.method =='POST':
如果没有request.POST。 get('txtName','')
errors.append('输入名称')
如果没有错误:
n = request.POST ['txtName'] $ b $ = request.POST ['txtEmail']
try:
per_job = Personal(name = n,email = e)
per_job.save()
除了IntegrityError:
return render_to_response('gharnivas / register.html',{'exists':true},context_instance = RequestContext(request))

return HttpResponseRedirect('/')
else:
return render_to_response('register.html',{'errors':errors},context_instance = RequestContext(request))

如何使用该名称,该名称已经存在?

解决方案

在保存时捕获不可避免的异常并告知他们。 p>

I have this custom primary key in a model:

class Personal(models.Model):
    name = models.CharField(max_length=20,primary_key=True)
    email = models.EmailField(blank=True,null=True)

Now the thing i m not getting is, how can i create my view so that no duplicate record is entered? I searched this over online, but could find any technique to get the view created.

here is the code for views

def uregister(request):
    errors = []
    if request.method == 'POST':
        if not request.POST.get('txtName', ''):
            errors.append('Enter a Name.')
        if not errors:
            n = request.POST['txtName']
            e = request.POST['txtEmail']
            try:
                per_job = Personal(name=n, email=e)
                per_job.save()
            except IntegrityError:
                return render_to_response('gharnivas/register.html', {'exists': true}, context_instance=RequestContext(request))

            return HttpResponseRedirect('/')
        else:
            return render_to_response('register.html', {'errors': errors}, context_instance=RequestContext(request))

How can i tel the user that, the name already exists?

解决方案

Catch the inevitable exception upon saving, and tell them.

这篇关于主键检查django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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