def mark_researches(context, research_list=[], is_resize='false', width=None, height=400):
    request = context['request']
    location = get_location(request)
    context.update({
        'location': location,
        'research_list': research_list,
        'width': '%d%s' % (width, 'px') if width else '100%',
        'height': '%d%s' % (height, 'px'),
        'is_resize': is_resize
    })
    return context
def mark_all_researches(context, is_resize='false', width=None, height=400):
    request = context['request']
    location = get_location(request)
    research_list = Research.objects.filter(is_publish=True, is_complete=False)
    context.update({
        'location': location,
        'research_list': research_list,
        'width': '%d%s' % (width, 'px') if width else '100%',
        'height': '%d%s' % (height, 'px'),
        'is_resize': is_resize
    })
    return context
def add_scheme_location(request, scheme_id, template='department/add_scheme_location.html', extra_context=None):
    location = None
    if request.method == 'POST':
        location_id = request.REQUEST.get('location_id', None)
        form = DepartmentSchemeLocationForm(data=request.POST, files=request.FILES)
        try:
            location = UniversityDepartment.objects.get(id=location_id)
        except UniversityDepartment.DoesNotExist:
            location = UniversityDepartment(user=request.user)
        if form.is_valid():
            location.university = form.cleaned_data['university']
            location.department = form.cleaned_data['department']
            location.address = form.cleaned_data['address']
            location.lng = form.cleaned_data['lng']
            location.lat = form.cleaned_data['lat']
            location.save()
            success(request, _(u'Update location successful.'))
            return HttpResponseRedirect(reverse_lazy('choose_scheme_location', args=[scheme_id, ]))
    else:
        coord = get_location(request)

        initial = {
            'user': request.user,
            'university': '',
            'department': '',
            'address': '',
            'lng': coord['lng'],
            'lat': coord['lat'],
        }
        form = DepartmentSchemeLocationForm(initial=initial)

    context = {
        'form': form,
        'location': location,
        'scheme_id': scheme_id,
    }

    if extra_context:
        context.update(extra_context)
    return render_to_response(template, context, context_instance=RequestContext(request))
def get_research_form(request, research_id, type='edit', template='scientist/research_post.html', extra_context=None):
    research = None
    is_paid = False
    total_credit = 0

    if research_id:
        research = get_object_or_404(Research, id=research_id, scientistresearch__scientist=request.user)
        total_credit = research.total_credit
        if type == 'edit':
            is_paid = research.is_paid
            if research.is_complete:
                return HttpResponseRedirect(reverse_lazy('scientist_research_list'))

    if request.method == 'POST':
        form = ResearchForm(data=request.POST, files=request.FILES, instance=research)
        if form.is_valid():
            research = form.save(commit=False)

            address = form.cleaned_data['address']
            lng = form.cleaned_data['lng']
            lat = form.cleaned_data['lat']

            if address and lng > 0 and lat > 0:
                location_info = LocationInfo(address=address, lng=lng, lat=lat)
                location_info.save()
                research.location = location_info

            remind_scientist_info = json.loads(form.cleaned_data['remind_scientist_info'])

            if remind_scientist_info and len(remind_scientist_info) > 0:
                RemindScientistInfo.objects.filter(research=research).delete()

                for remind_scientist in remind_scientist_info:
                    message_type = remind_scientist['type']
                    time = remind_scientist['time']
                    time_type = remind_scientist['time_type']
                    message = remind_scientist['message']
                    RemindScientistInfo(research=research, type=message_type, time=time, time_type=time_type,
                                        message=message).save()

            remind_participant_info = json.loads(form.cleaned_data['remind_participant_info'])

            if remind_participant_info and len(remind_participant_info) > 0:
                RemindParticipantInfo.objects.filter(research=research).delete()

                for remind_participant in remind_participant_info:
                    message_type = remind_participant['type']
                    time = remind_participant['time']
                    time_type = remind_participant['time_type']
                    message = remind_participant['message']
                    RemindParticipantInfo(research=research, type=message_type, time=time, time_type=time_type,
                                          message=message).save()

            if type == 'edit':
                research.is_publish = True
            elif type == 'draft':
                research.is_publish = False
            elif type == 'copy':
                research.id = None
                research.is_paid = False
                research.is_complete = False
                research.payment_dt = None
                research.created = now()

            if is_paid:
                research.total_credit = total_credit

            research.save()

            scientist_research = ScientistResearch.objects.filter(scientist=request.user, research=research)
            if not scientist_research:
                ScientistResearch(scientist=request.user, research=research).save()

            # If the research is not paid, redirect to payment page
            if research.is_publish and research.total_credit > 0 and research.is_paid is False:
                userprofile = request.user.userprofile
                userprofile.available_balance -= research.total_credit

                if research.payment_type == 'cash':
                    research.is_paid = True
                    research.save()
                elif userprofile.available_balance >= 0:
                    research.is_paid = True
                    research.save()
                    userprofile.save()
                    ScientistPaymentRecord(scientist=request.user, credit=-research.total_credit,
                                           description='payment for [id=%s, name=%s] research' % (
                                               research.id, research.name)).save()
                else:
                    research.is_publish = False
                    research.save()
                    if research.payment_type == 'paypal':
                        return HttpResponseRedirect(
                            reverse_lazy('scientist_research_payment_paypal', args=[research.id, ]))
                    elif research.payment_type == 'amazon':
                        return HttpResponseRedirect(
                            reverse_lazy('scientist_research_payment_amazon', args=[research.id, ]))
                    elif research.payment_type == 'fake':
                        return HttpResponseRedirect(
                            reverse_lazy('scientist_research_payment_fake', args=[research.id, ]))
            return HttpResponseRedirect(reverse_lazy('scientist_research_list'))
    else:
        location = get_location(request)

        if research:
            form = ResearchForm(instance=research, initial={
                'address': research.location.address if research.location else '',
                'lng': research.location.lng if research.location else location['lng'],
                'lat': research.location.lat if research.location else location['lat'],
            })
        else:
            form = ResearchForm(initial={
                'address': '',
                'lng': location['lng'],
                'lat': location['lat'],
            })

    context = {
        'form': form,
        'type': type,
        'research_id': research_id,
        'is_paid': is_paid,
        'remind_scientist_info': research.remindscientistinfo_set.all() if research else None,
        'remind_participant_info': research.remindparticipantinfo_set.all() if research else None,
    }

    if extra_context:
        context.update(extra_context)
    return render_to_response(template, context, context_instance=RequestContext(request))
def userprofile_basic_info(request, form_class, success_url, user_type, template, extra_context=None):
    """
    User basic_info

    **Context**

    ``RequestContext``

    """
    if not user_type or user_type not in USER_TYPE:
        raise Http404

    user_profile = UserProfile.objects.get_or_create(user=request.user)[0]
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            if len(user_profile.get_roles()) <= 0:
                user_profile.set_role(user_type)
            user_profile.basic_info[user_type] = form.cleaned_data
            first_name = form.cleaned_data.get('first_name', None)
            middle_name = form.cleaned_data.get('middle_name', None)
            last_name = form.cleaned_data.get('last_name', None)

            for key in USER_TYPE:
                basic_info = user_profile.basic_info.get(key, None)
                if basic_info:
                    basic_info['first_name'] = first_name
                    basic_info['middle_name'] = middle_name
                    basic_info['last_name'] = last_name
                else:
                    user_profile.basic_info[key] = {
                        'first_name': first_name,
                        'middle_name': middle_name,
                        'last_name': last_name,
                    }

            user_profile.save()

            '''
            user = user_profile.user
            user.first_name = first_name
            user.last_name = last_name
            user.save()
            '''
            return HttpResponseRedirect(success_url)
    else:
        location = get_location(request)

        initial = {
            'address': '',
            'lng': location['lng'],
            'lat': location['lat'],
        }
        basic_info = user_profile.basic_info.get(user_type, None)
        if basic_info:
            initial.update(basic_info)
        form = form_class(initial=initial)

    context = {
        'form': form,
        'user_type': user_type,
    }
    if extra_context:
        context.update(extra_context)
    return render_to_response(template, context, context_instance=RequestContext(request))