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 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.
Use:
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
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/
精彩评论