简体   繁体   English

Django中的主键检查

[英]Primary key check in django

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 im 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? 我该如何告诉用户该名称已经存在?

保存后捕获不可避免的异常 ,并告诉它们。

采用:

per_job.save(force_insert=True)

What you are looking for is Form and Form Validation: 您正在寻找的是表单和表单验证:

http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#customizing-the-form-template http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#customizing-the-form-template

Define a PersonalForm class, move your validation checks in form field definitions or clean*() methods, then show error fields from form in template. 定义一个PersonalForm类,将验证检查移到表单字段定义或clean *()方法中,然后在模板中显示表单中的错误字段。

Django book link for form processing: 用于表单处理的Django书链接:

http://www.djangobook.com/en/2.0/chapter07/ http://www.djangobook.com/en/2.0/chapter07/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM