Primary key check in django

怎甘沉沦 提交于 2019-12-08 12:54:18

问题


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?


回答1:


Catch the inevitable exception upon saving, and tell them.




回答2:


Use:

per_job.save(force_insert=True)



回答3:


What you are looking for is Form and Form Validation:

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.

Django book link for form processing:

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



来源:https://stackoverflow.com/questions/6034574/primary-key-check-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!