app/soc/views/site/sponsor/profile.py
changeset 512 aae25d2b4464
parent 500 44ea4620c5c0
equal deleted inserted replaced
511:52557918ec8f 512:aae25d2b4464
    57     
    57     
    58     #: list of model fields which will *not* be gathered by the form
    58     #: list of model fields which will *not* be gathered by the form
    59     exclude = ['founder', 'inheritance_line']
    59     exclude = ['founder', 'inheritance_line']
    60   
    60   
    61   # TODO(pawel.solyga): write validation functions for other fields
    61   # TODO(pawel.solyga): write validation functions for other fields
    62   def clean_link_name(self):
    62   def clean_link_id(self):
    63     link_name = self.cleaned_data.get('link_name')
    63     link_id = self.cleaned_data.get('link_id')
    64     if not validate.isLinkNameFormatValid(link_name):
    64     if not validate.isLinkIdFormatValid(link_id):
    65       raise forms.ValidationError("This link name is in wrong format.")
    65       raise forms.ValidationError("This link ID is in wrong format.")
    66     if models.sponsor.logic.getFromFields(link_name=link_name):
    66     if models.sponsor.logic.getFromFields(link_id=link_id):
    67       raise forms.ValidationError("This link name is already in use.")
    67       raise forms.ValidationError("This link ID is already in use.")
    68     return link_name
    68     return link_id
    69 
    69 
    70 
    70 
    71 class EditForm(CreateForm):
    71 class EditForm(CreateForm):
    72   """Django form displayed when editing a Sponsor.
    72   """Django form displayed when editing a Sponsor.
    73   """
    73   """
    74   link_name = forms.CharField(widget=helper.widgets.ReadOnlyInput())
    74   link_id = forms.CharField(widget=helper.widgets.ReadOnlyInput())
    75   founded_by = forms.CharField(widget=helper.widgets.ReadOnlyInput(),
    75   founded_by = forms.CharField(widget=helper.widgets.ReadOnlyInput(),
    76                                required=False)
    76                                required=False)
    77 
    77 
    78   def clean_link_name(self):
    78   def clean_link_id(self):
    79     link_name = self.cleaned_data.get('link_name')
    79     link_id = self.cleaned_data.get('link_id')
    80     if not validate.isLinkNameFormatValid(link_name):
    80     if not validate.isLinkIdFormatValid(link_id):
    81       raise forms.ValidationError("This link name is in wrong format.")
    81       raise forms.ValidationError("This link ID is in wrong format.")
    82     return link_name
    82     return link_id
    83 
    83 
    84 
    84 
    85 DEF_SITE_SPONSOR_PROFILE_EDIT_TMPL = 'soc/site/sponsor/profile/edit.html'
    85 DEF_SITE_SPONSOR_PROFILE_EDIT_TMPL = 'soc/site/sponsor/profile/edit.html'
    86 DEF_SPONSOR_NO_LINKNAME_CHANGE_MSG = 'Sponsor link name cannot be changed.'
    86 DEF_SPONSOR_NO_LINK_ID_CHANGE_MSG = 'Sponsor link ID cannot be changed.'
    87 DEF_CREATE_NEW_SPONSOR_MSG = ' You can create a new sponsor by visiting' \
    87 DEF_CREATE_NEW_SPONSOR_MSG = ' You can create a new sponsor by visiting' \
    88                           ' <a href="/site/sponsor/profile">Create ' \
    88                           ' <a href="/site/sponsor/profile">Create ' \
    89                           'a New Sponsor</a> page.'
    89                           'a New Sponsor</a> page.'
    90 
    90 
    91 @decorators.view
    91 @decorators.view
    92 def edit(request, page_name=None, link_name=None,
    92 def edit(request, page_name=None, link_id=None,
    93          template=DEF_SITE_SPONSOR_PROFILE_EDIT_TMPL):
    93          template=DEF_SITE_SPONSOR_PROFILE_EDIT_TMPL):
    94   """View for a Developer to modify the properties of a Sponsor Model entity.
    94   """View for a Developer to modify the properties of a Sponsor Model entity.
    95 
    95 
    96   Args:
    96   Args:
    97     request: the standard django request object
    97     request: the standard django request object
    98     page_name: the page name displayed in templates as page and header title
    98     page_name: the page name displayed in templates as page and header title
    99     link_name: the Sponsor's site-unique "link_name" extracted from the URL
    99     link_id: the Sponsor's site-unique "link_id" extracted from the URL
   100     template: the "sibling" template (or a search list of such templates)
   100     template: the "sibling" template (or a search list of such templates)
   101       from which to construct the public.html template name (or names)
   101       from which to construct the public.html template name (or names)
   102 
   102 
   103   Returns:
   103   Returns:
   104     A subclass of django.http.HttpResponse which either contains the form to
   104     A subclass of django.http.HttpResponse which either contains the form to
   117   user = models.user.logic.getForFields(
   117   user = models.user.logic.getForFields(
   118       {'account': users.get_current_user()}, unique=True)
   118       {'account': users.get_current_user()}, unique=True)
   119   sponsor_form = None
   119   sponsor_form = None
   120   existing_sponsor = None
   120   existing_sponsor = None
   121 
   121 
   122   # try to fetch Sponsor entity corresponding to link_name if one exists
   122   # try to fetch Sponsor entity corresponding to link_id if one exists
   123   try:
   123   try:
   124     existing_sponsor = sponsor.logic.getIfFields(link_name=link_name)
   124     existing_sponsor = sponsor.logic.getIfFields(link_id=link_id)
   125   except out_of_band.ErrorResponse, error:
   125   except out_of_band.ErrorResponse, error:
   126     # show custom 404 page when link name doesn't exist in Datastore
   126     # show custom 404 page when link ID doesn't exist in Datastore
   127     error.message = error.message + DEF_CREATE_NEW_SPONSOR_MSG
   127     error.message = error.message + DEF_CREATE_NEW_SPONSOR_MSG
   128     return simple.errorResponse(request, page_name, error, template, context)
   128     return simple.errorResponse(request, page_name, error, template, context)
   129      
   129      
   130   if request.method == 'POST':
   130   if request.method == 'POST':
   131     if existing_sponsor:
   131     if existing_sponsor:
   132       sponsor_form = EditForm(request.POST)
   132       sponsor_form = EditForm(request.POST)
   133     else:
   133     else:
   134       sponsor_form = CreateForm(request.POST)
   134       sponsor_form = CreateForm(request.POST)
   135 
   135 
   136     if sponsor_form.is_valid():
   136     if sponsor_form.is_valid():
   137       if link_name:
   137       if link_id:
   138         # Form doesn't allow to change link_name but somebody might want to
   138         # Form doesn't allow to change link_id but somebody might want to
   139         # abuse that manually, so we check if form link_name is the same as
   139         # abuse that manually, so we check if form link_id is the same as
   140         # url link_name
   140         # url link_id
   141         if sponsor_form.cleaned_data.get('link_name') != link_name:
   141         if sponsor_form.cleaned_data.get('link_id') != link_id:
   142           msg = DEF_SPONSOR_NO_LINKNAME_CHANGE_MSG
   142           msg = DEF_SPONSOR_NO_LINK_ID_CHANGE_MSG
   143           error = out_of_band.ErrorResponse(msg)
   143           error = out_of_band.ErrorResponse(msg)
   144           return simple.errorResponse(request, page_name, error, template, context)
   144           return simple.errorResponse(request, page_name, error, template, context)
   145       
   145       
   146       fields = {}      
   146       fields = {}      
   147       
   147       
   151         fields[field] = value
   151         fields[field] = value
   152       
   152       
   153       if not existing_sponsor:
   153       if not existing_sponsor:
   154         fields['founder'] = user
   154         fields['founder'] = user
   155       
   155       
   156       form_ln = fields['link_name']
   156       form_ln = fields['link_id']
   157       key_fields = models.sponsor.logic.getKeyFieldsFromKwargs(fields)
   157       key_fields = models.sponsor.logic.getKeyFieldsFromKwargs(fields)
   158       form_sponsor = models.sponsor.logic.updateOrCreateFromFields(
   158       form_sponsor = models.sponsor.logic.updateOrCreateFromFields(
   159           fields, key_fields)
   159           fields, key_fields)
   160       
   160       
   161       if not form_sponsor:
   161       if not form_sponsor:
   162         return http.HttpResponseRedirect('/')
   162         return http.HttpResponseRedirect('/')
   163         
   163         
   164       # redirect to new /site/sponsor/profile/form_link_name?s=0
   164       # redirect to new /site/sponsor/profile/form_link_id?s=0
   165       # (causes 'Profile saved' message to be displayed)
   165       # (causes 'Profile saved' message to be displayed)
   166       return helper.responses.redirectToChangedSuffix(
   166       return helper.responses.redirectToChangedSuffix(
   167           request, None, form_ln,
   167           request, None, form_ln,
   168           params=profile.SUBMIT_PROFILE_SAVED_PARAMS)
   168           params=profile.SUBMIT_PROFILE_SAVED_PARAMS)
   169 
   169 
   170   else: # request.method == 'GET'
   170   else: # request.method == 'GET'
   171     if existing_sponsor:
   171     if existing_sponsor:
   172       # is 'Profile saved' parameter present, but referrer was not ourself?
   172       # is 'Profile saved' parameter present, but referrer was not ourself?
   173       # (e.g. someone bookmarked the GET that followed the POST submit) 
   173       # (e.g. someone bookmarked the GET that followed the POST submit) 
   174       if (request.GET.get(profile.SUBMIT_MSG_PARAM_NAME)
   174       if (request.GET.get(profile.SUBMIT_MSG_PARAM_NAME)
   175           and (not helper.requests.isReferrerSelf(request, suffix=link_name))):
   175           and (not helper.requests.isReferrerSelf(request, suffix=link_id))):
   176         # redirect to aggressively remove 'Profile saved' query parameter
   176         # redirect to aggressively remove 'Profile saved' query parameter
   177         return http.HttpResponseRedirect(request.path)
   177         return http.HttpResponseRedirect(request.path)
   178       
   178       
   179       # referrer was us, so select which submit message to display
   179       # referrer was us, so select which submit message to display
   180       # (may display no message if ?s=0 parameter is not present)
   180       # (may display no message if ?s=0 parameter is not present)
   182           helper.requests.getSingleIndexedParamValue(
   182           helper.requests.getSingleIndexedParamValue(
   183               request, profile.SUBMIT_MSG_PARAM_NAME,
   183               request, profile.SUBMIT_MSG_PARAM_NAME,
   184               values=profile.SUBMIT_MESSAGES))    
   184               values=profile.SUBMIT_MESSAGES))    
   185               
   185               
   186       # populate form with the existing Sponsor entity
   186       # populate form with the existing Sponsor entity
   187       founder_link_name = existing_sponsor.founder.link_name
   187       founder_link_id = existing_sponsor.founder.link_id
   188       sponsor_form = EditForm(instance=existing_sponsor, 
   188       sponsor_form = EditForm(instance=existing_sponsor, 
   189                               initial={'founded_by': founder_link_name})
   189                               initial={'founded_by': founder_link_id})
   190     else:
   190     else:
   191       if request.GET.get(profile.SUBMIT_MSG_PARAM_NAME):
   191       if request.GET.get(profile.SUBMIT_MSG_PARAM_NAME):
   192         # redirect to aggressively remove 'Profile saved' query parameter
   192         # redirect to aggressively remove 'Profile saved' query parameter
   193         return http.HttpResponseRedirect(request.path)
   193         return http.HttpResponseRedirect(request.path)
   194       
   194       
   195       # no Sponsor entity exists for this link name, so show a blank form
   195       # no Sponsor entity exists for this link ID, so show a blank form
   196       sponsor_form = CreateForm()
   196       sponsor_form = CreateForm()
   197     
   197     
   198   context.update({'form': sponsor_form,
   198   context.update({'form': sponsor_form,
   199                   'entity':  existing_sponsor,
   199                   'entity':  existing_sponsor,
   200                   'entity_type': sponsor_model.Sponsor.TYPE_NAME,
   200                   'entity_type': sponsor_model.Sponsor.TYPE_NAME,
   205 
   205 
   206 DEF_SITE_SPONSOR_PROFILE_CREATE_TMPL = 'soc/group/profile/edit.html'
   206 DEF_SITE_SPONSOR_PROFILE_CREATE_TMPL = 'soc/group/profile/edit.html'
   207 
   207 
   208 @decorators.view
   208 @decorators.view
   209 def create(request, page_name=None, template=DEF_SITE_SPONSOR_PROFILE_CREATE_TMPL):
   209 def create(request, page_name=None, template=DEF_SITE_SPONSOR_PROFILE_CREATE_TMPL):
   210   """create() view is same as edit() view, but with no link_name supplied.
   210   """create() view is same as edit() view, but with no link_id supplied.
   211   """
   211   """
   212   return edit(request, page_name=page_name, link_name=None, template=template)
   212   return edit(request, page_name=page_name, link_id=None, template=template)
   213 
   213 
   214 
   214 
   215 @decorators.view
   215 @decorators.view
   216 def delete(request, page_name=None, link_name=None,
   216 def delete(request, page_name=None, link_id=None,
   217            template=DEF_SITE_SPONSOR_PROFILE_EDIT_TMPL):
   217            template=DEF_SITE_SPONSOR_PROFILE_EDIT_TMPL):
   218   """Request handler for a Developer to delete Sponsor Model entity.
   218   """Request handler for a Developer to delete Sponsor Model entity.
   219 
   219 
   220   Args:
   220   Args:
   221     request: the standard django request object
   221     request: the standard django request object
   222     page_name: the page name displayed in templates as page and header title
   222     page_name: the page name displayed in templates as page and header title
   223     link_name: the Sponsor's site-unique "link_name" extracted from the URL
   223     link_id: the Sponsor's site-unique "link_id" extracted from the URL
   224     template: the "sibling" template (or a search list of such templates)
   224     template: the "sibling" template (or a search list of such templates)
   225       from which to construct the public.html template name (or names)
   225       from which to construct the public.html template name (or names)
   226 
   226 
   227   Returns:
   227   Returns:
   228     A subclass of django.http.HttpResponse which redirects 
   228     A subclass of django.http.HttpResponse which redirects 
   238   context = helper.responses.getUniversalContext(request)
   238   context = helper.responses.getUniversalContext(request)
   239   context['page_name'] = page_name
   239   context['page_name'] = page_name
   240 
   240 
   241   existing_sponsor = None
   241   existing_sponsor = None
   242 
   242 
   243   # try to fetch Sponsor entity corresponding to link_name if one exists
   243   # try to fetch Sponsor entity corresponding to link_id if one exists
   244   try:
   244   try:
   245     existing_sponsor = models.sponsor.logic.getIfFields(link_name=link_name)
   245     existing_sponsor = models.sponsor.logic.getIfFields(link_id=link_id)
   246   except out_of_band.ErrorResponse, error:
   246   except out_of_band.ErrorResponse, error:
   247     # show custom 404 page when link name doesn't exist in Datastore
   247     # show custom 404 page when link ID doesn't exist in Datastore
   248     error.message = error.message + DEF_CREATE_NEW_SPONSOR_MSG
   248     error.message = error.message + DEF_CREATE_NEW_SPONSOR_MSG
   249     return simple.errorResponse(request, page_name, error, template, context)
   249     return simple.errorResponse(request, page_name, error, template, context)
   250 
   250 
   251   if existing_sponsor:
   251   if existing_sponsor:
   252     # TODO(pawel.solyga): Create specific delete method for Sponsor model
   252     # TODO(pawel.solyga): Create specific delete method for Sponsor model