开启代码之旅 Launch With Code
1404 浏览 6 years, 1 month
10 Create Custom Reference ID
版权声明: 转载请注明出处 http://www.codingsoho.com/Reference处理包括以下几个步骤
- 在join添加ref_id字段
- 从uuid里面拿出值,并置成ref_id
- 在form POST处理时把这个字段存进join
运行 python manage.py shell
>>> import uuid
>>> uuid.uuid4()
class Join(models.Model):
email = models.EmailField(unique = True)
ref_id = models.CharField(max_length=120, default='ABC', unique=True)
ip_address = models.CharField(max_length = 120, default = 'ABC')
timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
updated = models.DateTimeField(auto_now_add = False, auto_now = True)
def __unicode__(self):
return "%s %s" %(self.email, self.ref_id)
class Meta:
unique_together = ("email", "ref_id",)
import uuid
def get_ref_id():
ref_id = str(uuid.uuid4())[:11].replace('-','').lower()
try:
id_exists = Join.objects.get(ref_id=ref_id)
get_ref_id()
except:
return ref_id
def home(request):
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit = False)
email = form.cleaned_data['email']
new_join_old, created = Join.objects.get_or_create(email = email)
if created:
new_join_old.ref_id = get_ref_id()
new_join_old.ip_address = get_ip(request)
new_join_old.save()
context = {"form":form}
template = "home.html"
return render(request, template, context)