开启代码之旅 Launch With Code


1217 浏览 5 years, 6 months

11 Create a Social Sharing Page to Share

版权声明: 转载请注明出处 http://www.codingsoho.com/

第一步:创建分享页,包括

  • 增加redirect到分享页的入口处理
  • URL routing
  • 分享后台处理函数
  • template
urlpatterns = patterns('',
    url(r'^(?P<ref_id>.*)$', 'joins.views.share', name='share'),
)
from django.shortcuts import render, HttpResponseRedirect
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()
        return HttpResponseRedirect("/%s" %(new_join_old.ref_id))       
    context = {"form":form}
    template = "home.html"
    return render(request, template, context)

将email字段unique去掉

class Join(models.Model):
    #email =  models.EmailField(unique = True)
    email =  models.EmailField()
    friend = models.ForeignKey("self", related_name='referral', null=True, blank=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",)

unique改成False,否则Join的时候check不过

joins/views.py

def share(request, ref_id):
    join_obj = Join.objects.get(ref_id=ref_id)
    context = {"ref_id": join_obj.ref_id }
    template = "share.html"
    return render(request, template, context)   

templates/share.html

{% extends "base.html" %}
{% block content %}
{% include "navbar.html" %}

ref_id : {{ref_id}}

{% endblock %}